Code

remove many unnecessary to_2geom and from_2geom calls
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /** @file
4  * @brief Miscellanous operations on selected items
5  */
6 /* Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "inkscape.h"
29 #include "desktop.h"
30 #include "desktop-style.h"
31 #include "selection.h"
32 #include "tools-switch.h"
33 #include "desktop-handles.h"
34 #include "message-stack.h"
35 #include "sp-item-transform.h"
36 #include "marker.h"
37 #include "sp-use.h"
38 #include "sp-textpath.h"
39 #include "sp-tspan.h"
40 #include "sp-tref.h"
41 #include "sp-flowtext.h"
42 #include "sp-flowregion.h"
43 #include "text-editing.h"
44 #include "text-context.h"
45 #include "connector-context.h"
46 #include "sp-path.h"
47 #include "sp-conn-end.h"
48 #include "dropper-context.h"
49 #include <glibmm/i18n.h>
50 #include "libnr/nr-matrix-rotate-ops.h"
51 #include "libnr/nr-matrix-translate-ops.h"
52 #include "libnr/nr-rotate-fns.h"
53 #include "libnr/nr-scale-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-translate-matrix-ops.h"
56 #include "libnr/nr-translate-scale-ops.h"
57 #include "xml/repr.h"
58 #include "style.h"
59 #include "document-private.h"
60 #include "sp-gradient.h"
61 #include "sp-gradient-reference.h"
62 #include "sp-linear-gradient-fns.h"
63 #include "sp-pattern.h"
64 #include "sp-radial-gradient-fns.h"
65 #include "sp-namedview.h"
66 #include "prefs-utils.h"
67 #include "sp-offset.h"
68 #include "sp-clippath.h"
69 #include "sp-mask.h"
70 #include "file.h"
71 #include "helper/png-write.h"
72 #include "layer-fns.h"
73 #include "context-fns.h"
74 #include <map>
75 #include <cstring>
76 #include <string>
77 #include "helper/units.h"
78 #include "sp-item.h"
79 #include "box3d.h"
80 #include "unit-constants.h"
81 #include "xml/simple-document.h"
82 #include "sp-filter-reference.h"
83 #include "gradient-drag.h"
84 #include "uri-references.h"
85 #include "libnr/nr-convert2geom.h"
86 #include "display/curve.h"
87 #include "display/canvas-bpath.h"
89 // For clippath editing
90 #include "tools-switch.h"
91 #include "shape-editor.h"
92 #include "node-context.h"
93 #include "nodepath.h"
95 #include "ui/clipboard.h"
97 using NR::X;
98 using NR::Y;
100 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
101 because the layer manipulation code uses them. It should be rewritten specifically
102 for that purpose. */
104 /**
105  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
106  * then prepends the copy to 'clip'.
107  */
108 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
110     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
112     // copy complete inherited style
113     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
114     sp_repr_css_set(copy, css, "style");
115     sp_repr_css_attr_unref(css);
117     // write the complete accumulated transform passed to us
118     // (we're dealing with unattached repr, so we write to its attr
119     // instead of using sp_item_set_transform)
120     gchar *affinestr=sp_svg_transform_write(full_t);
121     copy->setAttribute("transform", affinestr);
122     g_free(affinestr);
124     *clip = g_slist_prepend(*clip, copy);
127 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
129     // Sort items:
130     GSList *sorted_items = g_slist_copy ((GSList *) items);
131     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
133     // Copy item reprs:
134     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
135         sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
136     }
138     *clip = g_slist_reverse(*clip);
139     g_slist_free ((GSList *) sorted_items);
142 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
144     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
146     GSList *copied = NULL;
147     // add objects to document
148     for (GSList *l = *clip; l != NULL; l = l->next) {
149         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
150         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
152         // premultiply the item transform by the accumulated parent transform in the paste layer
153         NR::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
154         if (!local.test_identity()) {
155             gchar const *t_str = copy->attribute("transform");
156             NR::Matrix item_t (NR::identity());
157             if (t_str)
158                 sp_svg_transform_read(t_str, &item_t);
159             item_t *= local.inverse();
160             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
161             gchar *affinestr=sp_svg_transform_write(item_t);
162             copy->setAttribute("transform", affinestr);
163             g_free(affinestr);
164         }
166         parent->appendChildRepr(copy);
167         copied = g_slist_prepend(copied, copy);
168         Inkscape::GC::release(copy);
169     }
170     return copied;
173 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
175     for (GSList const *i = items ; i ; i = i->next ) {
176         sp_object_ref((SPObject *)i->data, NULL);
177     }
178     for (GSList const *i = items; i != NULL; i = i->next) {
179         SPItem *item = (SPItem *) i->data;
180         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
181         sp_object_unref((SPObject *)item, NULL);
182     }
186 void sp_selection_delete()
188     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
189     if (desktop == NULL) {
190         return;
191     }
193     if (tools_isactive (desktop, TOOLS_TEXT))
194         if (sp_text_delete_selection(desktop->event_context)) {
195             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
196                              _("Delete text"));
197             return;
198         }
200     Inkscape::Selection *selection = sp_desktop_selection(desktop);
202     // check if something is selected
203     if (selection->isEmpty()) {
204         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
205         return;
206     }
208     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
209     selection->clear();
210     sp_selection_delete_impl (selected);
211     g_slist_free ((GSList *) selected);
213     /* a tool may have set up private information in it's selection context
214      * that depends on desktop items.  I think the only sane way to deal with
215      * this currently is to reset the current tool, which will reset it's
216      * associated selection context.  For example: deleting an object
217      * while moving it around the canvas.
218      */
219     tools_switch ( desktop, tools_active ( desktop ) );
221     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
222                      _("Delete"));
225 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
227     if (!obj)
228         return;
230     ids.push_back(SP_OBJECT_ID(obj));
232     if (SP_IS_GROUP(obj)) {
233         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
234             add_ids_recursive (ids, child);
235         }
236     }
239 void sp_selection_duplicate(bool suppressDone)
241     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
242     if (desktop == NULL)
243         return;
245     SPDocument *doc = desktop->doc();
246     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
247     Inkscape::Selection *selection = sp_desktop_selection(desktop);
249     // check if something is selected
250     if (selection->isEmpty()) {
251         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
252         return;
253     }
255     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
257     selection->clear();
259     // sorting items from different parents sorts each parent's subset without possibly mixing
260     // them, just what we need
261     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
263     GSList *newsel = NULL;
265     std::vector<const gchar *> old_ids;
266     std::vector<const gchar *> new_ids;
267     bool relink_clones = prefs_get_int_attribute ("options.relinkclonesonduplicate", "value", 0);
269     while (reprs) {
270         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
271         Inkscape::XML::Node *parent = old_repr->parent();
272         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
274         parent->appendChild(copy);
276         if (relink_clones) {
277             SPObject *old_obj = doc->getObjectByRepr(old_repr);
278             SPObject *new_obj = doc->getObjectByRepr(copy);
279             add_ids_recursive (old_ids, old_obj);
280             add_ids_recursive (new_ids, new_obj);
281         }
283         newsel = g_slist_prepend(newsel, copy);
284         reprs = g_slist_remove(reprs, reprs->data);
285         Inkscape::GC::release(copy);
286     }
288     if (relink_clones) {
290         g_assert (old_ids.size() == new_ids.size());
292         for(unsigned int i = 0; i < old_ids.size(); i++) {
293             const gchar *id = old_ids[i];
294             SPObject *old_clone = doc->getObjectById(id);
295             if (SP_IS_USE(old_clone)) {
296                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
297                 for(unsigned int j = 0; j < old_ids.size(); j++) {
298                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
299                         // we have both orig and clone in selection, relink
300                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
301                         gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
302                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
303                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
304                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
305                         g_free (newref);
306                     }
307                 }
308             }
309         }
310     }
313     if ( !suppressDone ) {
314         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
315                          _("Duplicate"));
316     }
318     selection->setReprList(newsel);
320     g_slist_free(newsel);
323 void sp_edit_clear_all()
325     SPDesktop *dt = SP_ACTIVE_DESKTOP;
326     if (!dt)
327         return;
329     SPDocument *doc = sp_desktop_document(dt);
330     sp_desktop_selection(dt)->clear();
332     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
333     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
335     while (items) {
336         SP_OBJECT (items->data)->deleteObject();
337         items = g_slist_remove(items, items->data);
338     }
340     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
341                      _("Delete all"));
344 GSList *
345 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
347     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
348         if (SP_IS_ITEM(child) &&
349             !desktop->isLayer(SP_ITEM(child)) &&
350             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
351             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
352             (!exclude || !g_slist_find ((GSList *) exclude, child))
353             )
354         {
355             list = g_slist_prepend (list, SP_ITEM(child));
356         }
358         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
359             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
360         }
361     }
363     return list;
366 void sp_edit_select_all_full (bool force_all_layers, bool invert)
368     SPDesktop *dt = SP_ACTIVE_DESKTOP;
369     if (!dt)
370         return;
372     Inkscape::Selection *selection = sp_desktop_selection(dt);
374     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
376     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
377     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
378     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
380     GSList *items = NULL;
382     GSList const *exclude = NULL;
383     if (invert) {
384         exclude = selection->itemList();
385     }
387     if (force_all_layers)
388         inlayer = PREFS_SELECTION_ALL;
390     switch (inlayer) {
391         case PREFS_SELECTION_LAYER: {
392         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
393              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
394         return;
396         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
398         for (GSList *i = all_items; i; i = i->next) {
399             SPItem *item = SP_ITEM (i->data);
401             if (item && (!onlysensitive || !item->isLocked())) {
402                 if (!onlyvisible || !dt->itemIsHidden(item)) {
403                     if (!dt->isLayer(item)) {
404                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
405                             items = g_slist_prepend (items, item); // leave it in the list
406                         }
407                     }
408                 }
409             }
410         }
412         g_slist_free (all_items);
413             break;
414         }
415         case PREFS_SELECTION_LAYER_RECURSIVE: {
416             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
417             break;
418         }
419         default: {
420         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
421             break;
422     }
423     }
425     selection->setList (items);
427     if (items) {
428         g_slist_free (items);
429     }
432 void sp_edit_select_all ()
434     sp_edit_select_all_full (false, false);
437 void sp_edit_select_all_in_all_layers ()
439     sp_edit_select_all_full (true, false);
442 void sp_edit_invert ()
444     sp_edit_select_all_full (false, true);
447 void sp_edit_invert_in_all_layers ()
449     sp_edit_select_all_full (true, true);
452 void sp_selection_group()
454     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
455     if (desktop == NULL)
456         return;
458     SPDocument *doc = sp_desktop_document (desktop);
459     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
461     Inkscape::Selection *selection = sp_desktop_selection(desktop);
463     // Check if something is selected.
464     if (selection->isEmpty()) {
465         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
466         return;
467     }
469     GSList const *l = (GSList *) selection->reprList();
471     GSList *p = g_slist_copy((GSList *) l);
473     selection->clear();
475     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
477     // Remember the position and parent of the topmost object.
478     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
479     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
481     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
483     while (p) {
484         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
486         if (current->parent() == topmost_parent) {
487             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
488             sp_repr_unparent(current);
489             group->appendChild(spnew);
490             Inkscape::GC::release(spnew);
491             topmost --; // only reduce count for those items deleted from topmost_parent
492         } else { // move it to topmost_parent first
493                 GSList *temp_clip = NULL;
495                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
496                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
497                 gchar const *t_str = current->attribute("transform");
498                 NR::Matrix item_t (NR::identity());
499                 if (t_str)
500                     sp_svg_transform_read(t_str, &item_t);
501                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
502                 //FIXME: when moving both clone and original from a transformed group (either by
503                 //grouping into another parent, or by cut/paste) the transform from the original's
504                 //parent becomes embedded into original itself, and this affects its clones. Fix
505                 //this by remembering the transform diffs we write to each item into an array and
506                 //then, if this is clone, looking up its original in that array and pre-multiplying
507                 //it by the inverse of that original's transform diff.
509                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
510                 sp_repr_unparent(current);
512                 // paste into topmost_parent (temporarily)
513                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
514                 if (temp_clip) g_slist_free (temp_clip);
515                 if (copied) { // if success,
516                     // take pasted object (now in topmost_parent)
517                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
518                     // make a copy
519                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
520                     // remove pasted
521                     sp_repr_unparent(in_topmost);
522                     // put its copy into group
523                     group->appendChild(spnew);
524                     Inkscape::GC::release(spnew);
525                     g_slist_free (copied);
526                 }
527         }
528         p = g_slist_remove(p, current);
529     }
531     // Add the new group to the topmost members' parent
532     topmost_parent->appendChild(group);
534     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
535     group->setPosition(topmost + 1);
537     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
538                      _("Group"));
540     selection->set(group);
541     Inkscape::GC::release(group);
544 void sp_selection_ungroup()
546     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
547     if (desktop == NULL)
548         return;
550     Inkscape::Selection *selection = sp_desktop_selection(desktop);
552     if (selection->isEmpty()) {
553         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
554         return;
555     }
557     GSList *items = g_slist_copy((GSList *) selection->itemList());
558     selection->clear();
560     // Get a copy of current selection.
561     GSList *new_select = NULL;
562     bool ungrouped = false;
563     for (GSList *i = items;
564          i != NULL;
565          i = i->next)
566     {
567         SPItem *group = (SPItem *) i->data;
569         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
570         if (!SP_IS_OBJECT(group)) {
571             continue;
572         }
574         /* We do not allow ungrouping <svg> etc. (lauris) */
575         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
576             // keep the non-group item in the new selection
577             selection->add(group);
578             continue;
579         }
581         GSList *children = NULL;
582         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
583         sp_item_group_ungroup(SP_GROUP(group), &children, false);
584         ungrouped = true;
585         // Add ungrouped items to the new selection.
586         new_select = g_slist_concat(new_select, children);
587     }
589     if (new_select) { // Set new selection.
590         selection->addList(new_select);
591         g_slist_free(new_select);
592     }
593     if (!ungrouped) {
594         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
595     }
597     g_slist_free(items);
599     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
600                      _("Ungroup"));
603 static SPGroup *
604 sp_item_list_common_parent_group(GSList const *items)
606     if (!items) {
607         return NULL;
608     }
609     SPObject *parent = SP_OBJECT_PARENT(items->data);
610     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
611     if (!SP_IS_GROUP(parent)) {
612         return NULL;
613     }
614     for (items = items->next; items; items = items->next) {
615         if (SP_OBJECT_PARENT(items->data) != parent) {
616             return NULL;
617         }
618     }
620     return SP_GROUP(parent);
623 /** Finds out the minimum common bbox of the selected items. */
624 static boost::optional<NR::Rect>
625 enclose_items(GSList const *items)
627     g_assert(items != NULL);
629     boost::optional<NR::Rect> r;
630     for (GSList const *i = items; i; i = i->next) {
631         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
632     }
633     return r;
636 SPObject *
637 prev_sibling(SPObject *child)
639     SPObject *parent = SP_OBJECT_PARENT(child);
640     if (!SP_IS_GROUP(parent)) {
641         return NULL;
642     }
643     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
644         if (i->next == child)
645             return i;
646     }
647     return NULL;
650 void
651 sp_selection_raise()
653     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
654     if (!desktop)
655         return;
657     Inkscape::Selection *selection = sp_desktop_selection(desktop);
659     GSList const *items = (GSList *) selection->itemList();
660     if (!items) {
661         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
662         return;
663     }
665     SPGroup const *group = sp_item_list_common_parent_group(items);
666     if (!group) {
667         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
668         return;
669     }
671     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
673     /* Construct reverse-ordered list of selected children. */
674     GSList *rev = g_slist_copy((GSList *) items);
675     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
677     // Determine the common bbox of the selected items.
678     boost::optional<NR::Rect> selected = enclose_items(items);
680     // Iterate over all objects in the selection (starting from top).
681     if (selected) {
682         while (rev) {
683             SPObject *child = SP_OBJECT(rev->data);
684             // for each selected object, find the next sibling
685             for (SPObject *newref = child->next; newref; newref = newref->next) {
686                 // if the sibling is an item AND overlaps our selection,
687                 if (SP_IS_ITEM(newref)) {
688                     boost::optional<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
689                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
690                         // AND if it's not one of our selected objects,
691                         if (!g_slist_find((GSList *) items, newref)) {
692                             // move the selected object after that sibling
693                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
694                         }
695                         break;
696                     }
697                 }
698             }
699             rev = g_slist_remove(rev, child);
700         }
701     } else {
702         g_slist_free(rev);
703     }
705     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
706                      //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
707                      Q_("undo_action|Raise"));
710 void sp_selection_raise_to_top()
712     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
713     if (desktop == NULL)
714         return;
716     SPDocument *document = sp_desktop_document(desktop);
717     Inkscape::Selection *selection = sp_desktop_selection(desktop);
719     if (selection->isEmpty()) {
720         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
721         return;
722     }
724     GSList const *items = (GSList *) selection->itemList();
726     SPGroup const *group = sp_item_list_common_parent_group(items);
727     if (!group) {
728         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
729         return;
730     }
732     GSList *rl = g_slist_copy((GSList *) selection->reprList());
733     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
735     for (GSList *l = rl; l != NULL; l = l->next) {
736         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
737         repr->setPosition(-1);
738     }
740     g_slist_free(rl);
742     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
743                      _("Raise to top"));
746 void
747 sp_selection_lower()
749     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
750     if (desktop == NULL)
751         return;
753     Inkscape::Selection *selection = sp_desktop_selection(desktop);
755     GSList const *items = (GSList *) selection->itemList();
756     if (!items) {
757         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
758         return;
759     }
761     SPGroup const *group = sp_item_list_common_parent_group(items);
762     if (!group) {
763         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
764         return;
765     }
767     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
769     // Determine the common bbox of the selected items.
770     boost::optional<NR::Rect> selected = enclose_items(items);
772     /* Construct direct-ordered list of selected children. */
773     GSList *rev = g_slist_copy((GSList *) items);
774     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
775     rev = g_slist_reverse(rev);
777     // Iterate over all objects in the selection (starting from top).
778     if (selected) {
779         while (rev) {
780             SPObject *child = SP_OBJECT(rev->data);
781             // for each selected object, find the prev sibling
782             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
783                 // if the sibling is an item AND overlaps our selection,
784                 if (SP_IS_ITEM(newref)) {
785                     boost::optional<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
786                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
787                         // AND if it's not one of our selected objects,
788                         if (!g_slist_find((GSList *) items, newref)) {
789                             // move the selected object before that sibling
790                             SPObject *put_after = prev_sibling(newref);
791                             if (put_after)
792                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
793                             else
794                                 SP_OBJECT_REPR(child)->setPosition(0);
795                         }
796                         break;
797                     }
798                 }
799             }
800             rev = g_slist_remove(rev, child);
801         }
802     } else {
803         g_slist_free(rev);
804     }
806     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
807                      _("Lower"));
810 void sp_selection_lower_to_bottom()
812     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
813     if (desktop == NULL)
814         return;
816     SPDocument *document = sp_desktop_document(desktop);
817     Inkscape::Selection *selection = sp_desktop_selection(desktop);
819     if (selection->isEmpty()) {
820         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
821         return;
822     }
824     GSList const *items = (GSList *) selection->itemList();
826     SPGroup const *group = sp_item_list_common_parent_group(items);
827     if (!group) {
828         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
829         return;
830     }
832     GSList *rl;
833     rl = g_slist_copy((GSList *) selection->reprList());
834     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
835     rl = g_slist_reverse(rl);
837     for (GSList *l = rl; l != NULL; l = l->next) {
838         gint minpos;
839         SPObject *pp, *pc;
840         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
841         pp = document->getObjectByRepr(sp_repr_parent(repr));
842         minpos = 0;
843         g_assert(SP_IS_GROUP(pp));
844         pc = sp_object_first_child(pp);
845         while (!SP_IS_ITEM(pc)) {
846             minpos += 1;
847             pc = pc->next;
848         }
849         repr->setPosition(minpos);
850     }
852     g_slist_free(rl);
854     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
855                      _("Lower to bottom"));
858 void
859 sp_undo(SPDesktop *desktop, SPDocument *)
861         if (!sp_document_undo(sp_desktop_document(desktop)))
862             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
865 void
866 sp_redo(SPDesktop *desktop, SPDocument *)
868         if (!sp_document_redo(sp_desktop_document(desktop)))
869             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
872 void sp_selection_cut()
874     sp_selection_copy();
875     sp_selection_delete();
878 /**
879  * \pre item != NULL
880  */
881 SPCSSAttr *
882 take_style_from_item (SPItem *item)
884     // write the complete cascaded style, context-free
885     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
886     if (css == NULL)
887         return NULL;
889     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
890         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
891         // if this is a text with exactly one tspan child, merge the style of that tspan as well
892         // If this is a group, merge the style of its topmost (last) child with style
893         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
894             if (SP_OBJECT_STYLE (last_element) != NULL) {
895                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
896                 if (temp) {
897                     sp_repr_css_merge (css, temp);
898                     sp_repr_css_attr_unref (temp);
899                 }
900                 break;
901             }
902         }
903     }
904     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
905         // do not copy text properties from non-text objects, it's confusing
906         css = sp_css_attr_unset_text (css);
907     }
909     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
910     double ex = NR::expansion(sp_item_i2doc_affine(item));
911     if (ex != 1.0) {
912         css = sp_css_attr_scale (css, ex);
913     }
915     return css;
919 void sp_selection_copy()
921     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
922     cm->copy();
925 void sp_selection_paste(bool in_place)
927     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
928     if(cm->paste(in_place))
929         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE, _("Paste"));
932 void sp_selection_paste_style()
934     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
935     if(cm->pasteStyle())
936         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
940 void sp_selection_paste_livepatheffect()
942     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
943     if(cm->pastePathEffect())
944         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
945                      _("Paste live path effect"));
949 void sp_selection_remove_livepatheffect_impl(SPItem *item)
951     if ( item && SP_IS_LPE_ITEM(item) ) {
952         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
953     }
956 void sp_selection_remove_livepatheffect()
958     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
959     if (desktop == NULL) return;
961     Inkscape::Selection *selection = sp_desktop_selection(desktop);
963     // check if something is selected
964     if (selection->isEmpty()) {
965         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
966         return;
967     }
969     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
970         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
972         sp_selection_remove_livepatheffect_impl(item);
974     }
976     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
977                      _("Remove live path effect"));
980 void sp_selection_remove_filter ()
982     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
983     if (desktop == NULL) return;
985     Inkscape::Selection *selection = sp_desktop_selection(desktop);
987     // check if something is selected
988     if (selection->isEmpty()) {
989         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
990         return;
991     }
993     SPCSSAttr *css = sp_repr_css_attr_new();
994     sp_repr_css_unset_property(css, "filter");
995     sp_desktop_set_style(desktop, css);
996     sp_repr_css_attr_unref(css);
998     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
999                      _("Remove filter"));
1003 void sp_selection_paste_size (bool apply_x, bool apply_y)
1005     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1006     if(cm->pasteSize(false, apply_x, apply_y))
1007         sp_document_done(sp_desktop_document(SP_ACTIVE_DESKTOP), SP_VERB_EDIT_PASTE_SIZE,
1008                      _("Paste size"));
1011 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1013     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1014     if(cm->pasteSize(true, apply_x, apply_y))
1015         sp_document_done(sp_desktop_document(SP_ACTIVE_DESKTOP), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1016                      _("Paste size separately"));
1019 void sp_selection_to_next_layer(bool suppressDone)
1021     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1023     Inkscape::Selection *selection = sp_desktop_selection(dt);
1025     // check if something is selected
1026     if (selection->isEmpty()) {
1027         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1028         return;
1029     }
1031     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1033     bool no_more = false; // Set to true, if no more layers above
1034     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1035     if (next) {
1036         GSList *temp_clip = NULL;
1037         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1038         sp_selection_delete_impl (items, false, false);
1039         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1040         GSList *copied;
1041         if(next) {
1042             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1043         } else {
1044             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1045             no_more = true;
1046         }
1047         selection->setReprList((GSList const *) copied);
1048         g_slist_free (copied);
1049         if (temp_clip) g_slist_free (temp_clip);
1050         if (next) dt->setCurrentLayer(next);
1051         if ( !suppressDone ) {
1052             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1053                              _("Raise to next layer"));
1054         }
1055     } else {
1056         no_more = true;
1057     }
1059     if (no_more) {
1060         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1061     }
1063     g_slist_free ((GSList *) items);
1066 void sp_selection_to_prev_layer(bool suppressDone)
1068     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1070     Inkscape::Selection *selection = sp_desktop_selection(dt);
1072     // check if something is selected
1073     if (selection->isEmpty()) {
1074         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1075         return;
1076     }
1078     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1080     bool no_more = false; // Set to true, if no more layers below
1081     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1082     if (next) {
1083         GSList *temp_clip = NULL;
1084         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1085         sp_selection_delete_impl (items, false, false);
1086         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1087         GSList *copied;
1088         if(next) {
1089             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1090         } else {
1091             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1092             no_more = true;
1093         }
1094         selection->setReprList((GSList const *) copied);
1095         g_slist_free (copied);
1096         if (temp_clip) g_slist_free (temp_clip);
1097         if (next) dt->setCurrentLayer(next);
1098         if ( !suppressDone ) {
1099             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1100                              _("Lower to previous layer"));
1101         }
1102     } else {
1103         no_more = true;
1104     }
1106     if (no_more) {
1107         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1108     }
1110     g_slist_free ((GSList *) items);
1113 bool
1114 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1116     bool contains_original = false;
1118     bool is_use = SP_IS_USE(item);
1119     SPItem *item_use = item;
1120     SPItem *item_use_first = item;
1121     while (is_use && item_use && !contains_original)
1122     {
1123         item_use = sp_use_get_original (SP_USE(item_use));
1124         contains_original |= selection->includes(item_use);
1125         if (item_use == item_use_first)
1126             break;
1127         is_use = SP_IS_USE(item_use);
1128     }
1130     // If it's a tref, check whether the object containing the character
1131     // data is part of the selection
1132     if (!contains_original && SP_IS_TREF(item)) {
1133         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1134     }
1136     return contains_original;
1140 bool
1141 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1143     bool clone_with_original = false;
1144     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1145         SPItem *item = SP_ITEM(l->data);
1146         clone_with_original |= selection_contains_original(item, selection);
1147         if (clone_with_original)
1148             break;
1149     }
1150     return clone_with_original;
1154 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1155 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1156 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1157 that case, items are already in the new position, but the repr is in the old, and this function
1158 then simply updates the repr from item->transform.
1159  */
1160 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1162     if (selection->isEmpty())
1163         return;
1165     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1166         SPItem *item = SP_ITEM(l->data);
1168         NR::Point old_center(0,0);
1169         if (set_i2d && item->isCenterSet())
1170             old_center = item->getCenter();
1172 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1173          At the time of writing, this is the only place to re-enable. */
1174         sp_item_update_cns(*item, selection->desktop());
1175 #endif
1177         // we're moving both a clone and its original or any ancestor in clone chain?
1178         bool transform_clone_with_original = selection_contains_original(item, selection);
1179         // ...both a text-on-path and its path?
1180         bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item)))) ));
1181         // ...both a flowtext and its frame?
1182         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // (only the first frame is checked so far)
1183         // ...both an offset and its source?
1184         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1186         // If we're moving a connector, we want to detach it
1187         // from shapes that aren't part of the selection, but
1188         // leave it attached if they are
1189         if (cc_item_is_connector(item)) {
1190             SPItem *attItem[2];
1191             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1193             for (int n = 0; n < 2; ++n) {
1194                 if (!selection->includes(attItem[n])) {
1195                     sp_conn_end_detach(item, n);
1196                 }
1197             }
1198         }
1200         // "clones are unmoved when original is moved" preference
1201         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1202         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1203         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1205         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1206         // transform of its original and respond to it itself. Without this, a clone is doubly
1207         // transformed, very unintuitive.
1208       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1209       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1210       // Same for linked offset if we are also moving its source: do not move it.
1211         if (transform_textpath_with_path || transform_offset_with_source) {
1212                 // restore item->transform field from the repr, in case it was changed by seltrans
1213             sp_object_read_attr (SP_OBJECT (item), "transform");
1215         } else if (transform_flowtext_with_frame) {
1216             // apply the inverse of the region's transform to the <use> so that the flow remains
1217             // the same (even though the output itself gets transformed)
1218             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1219                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1220                     continue;
1221                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1222                     if (!SP_IS_USE(use)) continue;
1223                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1224                 }
1225             }
1226         } else if (transform_clone_with_original) {
1227             // We are transforming a clone along with its original. The below matrix juggling is
1228             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1229             // transform and its move compensation are both cancelled out.
1231             // restore item->transform field from the repr, in case it was changed by seltrans
1232             sp_object_read_attr (SP_OBJECT (item), "transform");
1234             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1235             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1236             NR::Matrix t = parent_transform * from_2geom(matrix_to_desktop (matrix_from_desktop (affine, item), item)) * parent_transform.inverse();
1237             NR::Matrix t_inv =parent_transform * from_2geom(matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item)) * parent_transform.inverse();
1238             NR::Matrix result = t_inv * item->transform * t;
1240             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1241                 // we need to cancel out the move compensation, too
1243                 // find out the clone move, same as in sp_use_move_compensate
1244                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1245                 NR::Matrix clone_move = parent.inverse() * t * parent;
1247                 if (prefs_parallel) {
1248                     NR::Matrix move = result * clone_move * t_inv;
1249                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1251                 } else if (prefs_unmoved) {
1252                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1253                     //    clone_move = NR::identity();
1254                     NR::Matrix move = result * clone_move;
1255                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1256                 }
1258             } else {
1259                 // just apply the result
1260                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1261             }
1263         } else {
1264             if (set_i2d) {
1265                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1266             }
1267             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1268         }
1270         // if we're moving the actual object, not just updating the repr, we can transform the
1271         // center by the same matrix (only necessary for non-translations)
1272         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1273             item->setCenter(old_center * affine);
1274             SP_OBJECT(item)->updateRepr();
1275         }
1276     }
1279 void sp_selection_remove_transform()
1281     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1282     if (desktop == NULL)
1283         return;
1285     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1287     GSList const *l = (GSList *) selection->reprList();
1288     while (l != NULL) {
1289         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1290         l = l->next;
1291     }
1293     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1294                      _("Remove transform"));
1297 void
1298 sp_selection_scale_absolute(Inkscape::Selection *selection,
1299                             double const x0, double const x1,
1300                             double const y0, double const y1)
1302     if (selection->isEmpty())
1303         return;
1305     boost::optional<NR::Rect> const bbox(selection->bounds());
1306     if ( !bbox || bbox->isEmpty() ) {
1307         return;
1308     }
1310     NR::translate const p2o(-bbox->min());
1312     NR::scale const newSize(x1 - x0,
1313                             y1 - y0);
1314     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1315     NR::translate const o2n(x0, y0);
1316     NR::Matrix const final( p2o * scale * o2n );
1318     sp_selection_apply_affine(selection, final);
1322 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1324     if (selection->isEmpty())
1325         return;
1327     boost::optional<NR::Rect> const bbox(selection->bounds());
1329     if ( !bbox || bbox->isEmpty() ) {
1330         return;
1331     }
1333     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1334     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1335          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1336     {
1337         return;
1338     }
1340     NR::translate const n2d(-align);
1341     NR::translate const d2n(align);
1342     NR::Matrix const final( n2d * scale * d2n );
1343     sp_selection_apply_affine(selection, final);
1346 void
1347 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1349     NR::translate const d2n(center);
1350     NR::translate const n2d(-center);
1351     NR::rotate const rotate(rotate_degrees(angle_degrees));
1352     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1353     sp_selection_apply_affine(selection, final);
1356 void
1357 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1359     NR::translate const d2n(align);
1360     NR::translate const n2d(-align);
1361     NR::Matrix const skew(1, dy,
1362                           dx, 1,
1363                           0, 0);
1364     NR::Matrix const final( n2d * skew * d2n );
1365     sp_selection_apply_affine(selection, final);
1368 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1370     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1373 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1375     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1379 /**
1380  * \brief sp_selection_rotate_90
1381  *
1382  * This function rotates selected objects 90 degrees clockwise.
1383  *
1384  */
1386 void sp_selection_rotate_90_cw()
1388     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1390     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1392     if (selection->isEmpty())
1393         return;
1395     GSList const *l = selection->itemList();
1396     NR::rotate const rot_neg_90(NR::Point(0, -1));
1397     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1398         SPItem *item = SP_ITEM(l2->data);
1399         sp_item_rotate_rel(item, rot_neg_90);
1400     }
1402     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1403                      _("Rotate 90&#176; CW"));
1407 /**
1408  * @brief Rotates selected objects 90 degrees counter-clockwise.
1409  */
1410 void sp_selection_rotate_90_ccw()
1412     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1414     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1416     if (selection->isEmpty())
1417         return;
1419     GSList const *l = selection->itemList();
1420     NR::rotate const rot_neg_90(NR::Point(0, 1));
1421     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1422         SPItem *item = SP_ITEM(l2->data);
1423         sp_item_rotate_rel(item, rot_neg_90);
1424     }
1426     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1427                      _("Rotate 90&#176; CCW"));
1430 void
1431 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1433     if (selection->isEmpty())
1434         return;
1436     boost::optional<NR::Point> center = selection->center();
1437     if (!center) {
1438         return;
1439     }
1441     sp_selection_rotate_relative(selection, *center, angle_degrees);
1443     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1444                            ( ( angle_degrees > 0 )
1445                              ? "selector:rotate:ccw"
1446                              : "selector:rotate:cw" ),
1447                            SP_VERB_CONTEXT_SELECT,
1448                            _("Rotate"));
1451 /**
1452 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1453 */
1454 void
1455 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1457     if (selection->isEmpty())
1458         return;
1460     boost::optional<NR::Rect> const bbox(selection->bounds());
1461     boost::optional<NR::Point> center = selection->center();
1463     if ( !bbox || !center ) {
1464         return;
1465     }
1467     gdouble const zoom = selection->desktop()->current_zoom();
1468     gdouble const zmove = angle / zoom;
1469     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1471     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1473     sp_selection_rotate_relative(selection, *center, zangle);
1475     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1476                            ( (angle > 0)
1477                              ? "selector:rotate:ccw"
1478                              : "selector:rotate:cw" ),
1479                            SP_VERB_CONTEXT_SELECT,
1480                            _("Rotate by pixels"));
1483 void
1484 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1486     if (selection->isEmpty())
1487         return;
1489     boost::optional<NR::Rect> const bbox(selection->bounds());
1490     if (!bbox) {
1491         return;
1492     }
1494     NR::Point const center(bbox->midpoint());
1496     // you can't scale "do nizhe pola" (below zero)
1497     double const max_len = bbox->maxExtent();
1498     if ( max_len + grow <= 1e-3 ) {
1499         return;
1500     }
1502     double const times = 1.0 + grow / max_len;
1503     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1505     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1506                            ( (grow > 0)
1507                              ? "selector:scale:larger"
1508                              : "selector:scale:smaller" ),
1509                            SP_VERB_CONTEXT_SELECT,
1510                            _("Scale"));
1513 void
1514 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1516     sp_selection_scale(selection,
1517                        grow_pixels / selection->desktop()->current_zoom());
1520 void
1521 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1523     if (selection->isEmpty())
1524         return;
1526     boost::optional<NR::Rect> sel_bbox = selection->bounds();
1528     if (!sel_bbox) {
1529         return;
1530     }
1532     NR::Point const center(sel_bbox->midpoint());
1533     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1534     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1535                      _("Scale by whole factor"));
1538 void
1539 sp_selection_move(gdouble dx, gdouble dy)
1541     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1542     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1543     if (selection->isEmpty()) {
1544         return;
1545     }
1547     sp_selection_move_relative(selection, dx, dy);
1549     if (dx == 0) {
1550         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1551                                _("Move vertically"));
1552     } else if (dy == 0) {
1553         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1554                                _("Move horizontally"));
1555     } else {
1556         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1557                          _("Move"));
1558     }
1561 void
1562 sp_selection_move_screen(gdouble dx, gdouble dy)
1564     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1566     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1567     if (selection->isEmpty()) {
1568         return;
1569     }
1571     // same as sp_selection_move but divide deltas by zoom factor
1572     gdouble const zoom = desktop->current_zoom();
1573     gdouble const zdx = dx / zoom;
1574     gdouble const zdy = dy / zoom;
1575     sp_selection_move_relative(selection, zdx, zdy);
1577     if (dx == 0) {
1578         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1579                                _("Move vertically by pixels"));
1580     } else if (dy == 0) {
1581         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1582                                _("Move horizontally by pixels"));
1583     } else {
1584         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1585                          _("Move"));
1586     }
1589 namespace {
1591 template <typename D>
1592 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1593                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1595 template <typename D>
1596 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1597                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1599 struct Forward {
1600     typedef SPObject *Iterator;
1602     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1603     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1604     static void dispose(Iterator /*i*/) {}
1606     static SPObject *object(Iterator i) { return i; }
1607     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1608 };
1610 struct Reverse {
1611     typedef GSList *Iterator;
1613     static Iterator children(SPObject *o) {
1614         return make_list(o->firstChild(), NULL);
1615     }
1616     static Iterator siblings_after(SPObject *o) {
1617         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1618     }
1619     static void dispose(Iterator i) {
1620         g_slist_free(i);
1621     }
1623     static SPObject *object(Iterator i) {
1624         return reinterpret_cast<SPObject *>(i->data);
1625     }
1626     static Iterator next(Iterator i) { return i->next; }
1628 private:
1629     static GSList *make_list(SPObject *object, SPObject *limit) {
1630         GSList *list=NULL;
1631         while ( object != limit ) {
1632             list = g_slist_prepend(list, object);
1633             object = SP_OBJECT_NEXT(object);
1634         }
1635         return list;
1636     }
1637 };
1641 void
1642 sp_selection_item_next(void)
1644     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1645     g_return_if_fail(desktop != NULL);
1646     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1648     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1649     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1650     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1652     SPObject *root;
1653     if (PREFS_SELECTION_ALL != inlayer) {
1654         root = selection->activeContext();
1655     } else {
1656         root = desktop->currentRoot();
1657     }
1659     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1661     if (item) {
1662         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1663         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1664             scroll_to_show_item(desktop, item);
1665         }
1666     }
1669 void
1670 sp_selection_item_prev(void)
1672     SPDocument *document = SP_ACTIVE_DOCUMENT;
1673     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1674     g_return_if_fail(document != NULL);
1675     g_return_if_fail(desktop != NULL);
1676     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1678     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1679     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1680     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1682     SPObject *root;
1683     if (PREFS_SELECTION_ALL != inlayer) {
1684         root = selection->activeContext();
1685     } else {
1686         root = desktop->currentRoot();
1687     }
1689     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1691     if (item) {
1692         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1693         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1694             scroll_to_show_item(desktop, item);
1695         }
1696     }
1699 void sp_selection_next_patheffect_param(SPDesktop * dt)
1701     if (!dt) return;
1703     Inkscape::Selection *selection = sp_desktop_selection(dt);
1704     if ( selection && !selection->isEmpty() ) {
1705         SPItem *item = selection->singleItem();
1706         if ( item && SP_IS_SHAPE(item)) {
1707             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1708                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1709             } else {
1710                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1711             }
1712         }
1713     }
1716 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1718     if (!dt) return;
1720     Inkscape::Selection *selection = sp_desktop_selection(dt);
1721     if ( selection && !selection->isEmpty() ) {
1722         SPItem *item = selection->singleItem();
1723         if ( item ) {
1724             SPObject *obj = NULL;
1725             if (clip)
1726                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1727             else
1728                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1730             if (obj) {
1731                 // obj is a group object, the children are the actual clippers
1732                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1733                     if ( SP_IS_ITEM(child) ) {
1734                         // If not already in nodecontext, goto it!
1735                         if (!tools_isactive(dt, TOOLS_NODES)) {
1736                             tools_switch_current(TOOLS_NODES);
1737                         }
1739                         ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
1740                         // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1741                         shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1742                         shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1743                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1744                         if (np) {
1745                             // take colors from prefs (same as used in outline mode)
1746                             np->helperpath_rgba = clip ? 
1747                                 prefs_get_int_attribute("options.wireframecolors", "clips", 0x00ff00ff) : 
1748                                 prefs_get_int_attribute("options.wireframecolors", "masks", 0x0000ffff);
1749                             np->helperpath_width = 1.0;
1750                             sp_nodepath_show_helperpath(np, true);
1751                         }
1752                         break; // break out of for loop after 1st encountered item
1753                     }
1754                 }
1755             } else if (clip) {
1756                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1757             } else {
1758                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1759             }
1760         }
1761     }
1765 namespace {
1767 template <typename D>
1768 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1769                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1771     SPObject *current=root;
1772     while (items) {
1773         SPItem *item=SP_ITEM(items->data);
1774         if ( root->isAncestorOf(item) &&
1775              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1776         {
1777             current = item;
1778             break;
1779         }
1780         items = items->next;
1781     }
1783     GSList *path=NULL;
1784     while ( current != root ) {
1785         path = g_slist_prepend(path, current);
1786         current = SP_OBJECT_PARENT(current);
1787     }
1789     SPItem *next;
1790     // first, try from the current object
1791     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1792     g_slist_free(path);
1794     if (!next) { // if we ran out of objects, start over at the root
1795         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1796     }
1798     return next;
1801 template <typename D>
1802 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1803                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1805     typename D::Iterator children;
1806     typename D::Iterator iter;
1808     SPItem *found=NULL;
1810     if (path) {
1811         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1812         g_assert(SP_OBJECT_PARENT(object) == root);
1813         if (desktop->isLayer(object)) {
1814             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1815         }
1816         iter = children = D::siblings_after(object);
1817     } else {
1818         iter = children = D::children(root);
1819     }
1821     while ( iter && !found ) {
1822         SPObject *object=D::object(iter);
1823         if (desktop->isLayer(object)) {
1824             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1825                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1826             }
1827         } else if ( SP_IS_ITEM(object) &&
1828                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1829                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1830                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1831                     !desktop->isLayer(SP_ITEM(object)) )
1832         {
1833             found = SP_ITEM(object);
1834         }
1835         iter = D::next(iter);
1836     }
1838     D::dispose(children);
1840     return found;
1845 /**
1846  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1847  * \a item.
1848  */
1849 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1851     NR::Rect dbox = desktop->get_display_area();
1852     boost::optional<NR::Rect> sbox = sp_item_bbox_desktop(item);
1854     if ( sbox && dbox.contains(*sbox) == false ) {
1855         NR::Point const s_dt = sbox->midpoint();
1856         NR::Point const s_w = desktop->d2w(s_dt);
1857         NR::Point const d_dt = dbox.midpoint();
1858         NR::Point const d_w = desktop->d2w(d_dt);
1859         NR::Point const moved_w( d_w - s_w );
1860         gint const dx = (gint) moved_w[X];
1861         gint const dy = (gint) moved_w[Y];
1862         desktop->scroll_world(dx, dy);
1863     }
1867 void
1868 sp_selection_clone()
1870     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1871     if (desktop == NULL)
1872         return;
1874     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1876     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1878     // check if something is selected
1879     if (selection->isEmpty()) {
1880         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1881         return;
1882     }
1884     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1886     selection->clear();
1888     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1889     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1891     GSList *newsel = NULL;
1893     while (reprs) {
1894         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1895         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1897         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1898         clone->setAttribute("x", "0", false);
1899         clone->setAttribute("y", "0", false);
1900         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1901         
1902         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1903         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1905         // add the new clone to the top of the original's parent
1906         parent->appendChild(clone);
1908         newsel = g_slist_prepend(newsel, clone);
1909         reprs = g_slist_remove(reprs, sel_repr);
1910         Inkscape::GC::release(clone);
1911     }
1913     // TRANSLATORS: only translate "string" in "context|string".
1914     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1915     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1916                      Q_("action|Clone"));
1918     selection->setReprList(newsel);
1920     g_slist_free(newsel);
1923 void
1924 sp_selection_relink()
1926     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1927     if (!desktop)
1928         return;
1930     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1932     if (selection->isEmpty()) {
1933         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1934         return;
1935     }
1937     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1938     const gchar *newid = cm->getFirstObjectID();
1939     if (!newid) {
1940         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1941         return;
1942     }
1943     gchar *newref = g_strdup_printf ("#%s", newid);
1945     // Get a copy of current selection.
1946     bool relinked = false;
1947     for (GSList *items = (GSList *) selection->itemList();
1948          items != NULL;
1949          items = items->next)
1950     {
1951         SPItem *item = (SPItem *) items->data;
1953         if (!SP_IS_USE(item))
1954             continue;
1956         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1957         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1958         relinked = true;
1959     }
1961     g_free(newref);
1963     if (!relinked) {
1964         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1965     } else {
1966         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1967                      _("Relink clone"));
1968     }
1972 void
1973 sp_selection_unlink()
1975     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1976     if (!desktop)
1977         return;
1979     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1981     if (selection->isEmpty()) {
1982         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1983         return;
1984     }
1986     // Get a copy of current selection.
1987     GSList *new_select = NULL;
1988     bool unlinked = false;
1989     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1990          items != NULL;
1991          items = items->next)
1992     {
1993         SPItem *item = (SPItem *) items->data;
1995         if (SP_IS_TEXT(item)) {
1996             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1998             if (tspan) {
1999                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2000             }
2002             // Set unlink to true, and fall into the next if which
2003             // will include this text item in the new selection
2004             unlinked = true;
2005         }
2007         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2008             // keep the non-use item in the new selection
2009             new_select = g_slist_prepend(new_select, item);
2010             continue;
2011         }
2013         SPItem *unlink;
2014         if (SP_IS_USE(item)) {
2015             unlink = sp_use_unlink(SP_USE(item));
2016         } else /*if (SP_IS_TREF(use))*/ {
2017             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2018         }
2020         unlinked = true;
2021         // Add ungrouped items to the new selection.
2022         new_select = g_slist_prepend(new_select, unlink);
2023     }
2025     if (new_select) { // set new selection
2026         selection->clear();
2027         selection->setList(new_select);
2028         g_slist_free(new_select);
2029     }
2030     if (!unlinked) {
2031         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2032     }
2034     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2035                      _("Unlink clone"));
2038 void
2039 sp_select_clone_original()
2041     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2042     if (desktop == NULL)
2043         return;
2045     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2047     SPItem *item = selection->singleItem();
2049     gchar const *error = _("Select a <b>clone</b> to go to its original. Select a <b>linked offset</b> to go to its source. Select a <b>text on path</b> to go to the path. Select a <b>flowed text</b> to go to its frame.");
2051     // Check if other than two objects are selected
2052     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2053         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2054         return;
2055     }
2057     SPItem *original = NULL;
2058     if (SP_IS_USE(item)) {
2059         original = sp_use_get_original (SP_USE(item));
2060     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2061         original = sp_offset_get_source (SP_OFFSET(item));
2062     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2063         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2064     } else if (SP_IS_FLOWTEXT(item)) {
2065         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2066     } else { // it's an object that we don't know what to do with
2067         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2068         return;
2069     }
2071     if (!original) {
2072         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2073         return;
2074     }
2076     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2077         if (SP_IS_DEFS (o)) {
2078             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2079             return;
2080         }
2081     }
2083     if (original) {
2085         bool highlight = prefs_get_int_attribute ("options.highlightoriginal", "value", 0);
2086         if (highlight) {
2087             boost::optional<NR::Rect> a = item->getBounds(sp_item_i2d_affine(item));
2088             boost::optional<NR::Rect> b = original->getBounds(sp_item_i2d_affine(original));
2089             if ( a && b ) {
2090                 // draw a flashing line between the objects
2091                 SPCurve *curve = new SPCurve();
2092                 curve->moveto(a->midpoint());
2093                 curve->lineto(b->midpoint());
2095                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2096                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2097                 sp_canvas_item_show(canvasitem);
2098                 curve->unref();
2099                 desktop->add_temporary_canvasitem (canvasitem, 1000);
2100             }
2101         }
2103         selection->clear();
2104         selection->set(original);
2105         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2106             scroll_to_show_item(desktop, original);
2107         }
2108     }
2112 void sp_selection_to_marker(bool apply)
2114     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2115     if (desktop == NULL)
2116         return;
2118     SPDocument *doc = sp_desktop_document(desktop);
2119     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2121     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2123     // check if something is selected
2124     if (selection->isEmpty()) {
2125         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2126         return;
2127     }
2129     sp_document_ensure_up_to_date(doc);
2130     boost::optional<NR::Rect> r = selection->bounds();
2131     boost::optional<NR::Point> c = selection->center();
2132     if ( !r || !c || r->isEmpty() ) {
2133         return;
2134     }
2136     // calculate the transform to be applied to objects to move them to 0,0
2137     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - *c;
2138     move_p[NR::Y] = -move_p[NR::Y];
2139     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2141     GSList *items = g_slist_copy((GSList *) selection->itemList());
2143     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2145     // bottommost object, after sorting
2146     SPObject *parent = SP_OBJECT_PARENT (items->data);
2148     NR::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2150     // remember the position of the first item
2151     gint pos = SP_OBJECT_REPR (items->data)->position();
2152     (void)pos; // TODO check why this was remembered
2154     // create a list of duplicates
2155     GSList *repr_copies = NULL;
2156     for (GSList *i = items; i != NULL; i = i->next) {
2157         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2158         repr_copies = g_slist_prepend (repr_copies, dup);
2159     }
2161     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2163     if (apply) {
2164         // delete objects so that their clones don't get alerted; this object will be restored shortly
2165         for (GSList *i = items; i != NULL; i = i->next) {
2166             SPObject *item = SP_OBJECT (i->data);
2167             item->deleteObject (false);
2168         }
2169     }
2171     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2172     // without disturbing clones.
2173     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2174     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2175     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2177     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2178                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2179                                                                                                 r->max()[NR::Y]))))
2180                                              * parent_transform.inverse() ),
2181                                            parent_transform * move);
2182     (void)mark_id;
2184     // restore compensation setting
2185     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2188     g_slist_free (items);
2190     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2191                       _("Objects to marker"));
2194 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2195     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2196         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2197             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2198         }
2199     } else {
2200         sp_item_convert_item_to_guides(item);
2202         if (deleteitem) {
2203             SP_OBJECT(item)->deleteObject(true);
2204         }
2205     }
2208 void sp_selection_to_guides()
2210     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2211     if (desktop == NULL)
2212         return;
2214     SPDocument *doc = sp_desktop_document(desktop);
2215     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2216     // we need to copy the list because it gets reset when objects are deleted
2217     GSList *items = g_slist_copy((GSList *) selection->itemList());
2219     if (!items) {
2220         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2221         return;
2222     }
2223  
2224     bool deleteitem = (prefs_get_int_attribute("tools", "cvg_keep_objects", 0) == 0);
2225     bool wholegroups = (prefs_get_int_attribute("tools", "cvg_convert_whole_groups", 0) != 0);
2227     for (GSList const *i = items; i != NULL; i = i->next) {
2228         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2229     }
2231     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2234 void
2235 sp_selection_tile(bool apply)
2237     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2238     if (desktop == NULL)
2239         return;
2241     SPDocument *doc = sp_desktop_document(desktop);
2242     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2244     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2246     // check if something is selected
2247     if (selection->isEmpty()) {
2248         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2249         return;
2250     }
2252     sp_document_ensure_up_to_date(doc);
2253     boost::optional<NR::Rect> r = selection->bounds();
2254     if ( !r || r->isEmpty() ) {
2255         return;
2256     }
2258     // calculate the transform to be applied to objects to move them to 0,0
2259     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2260     move_p[NR::Y] = -move_p[NR::Y];
2261     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2263     GSList *items = g_slist_copy((GSList *) selection->itemList());
2265     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2267     // bottommost object, after sorting
2268     SPObject *parent = SP_OBJECT_PARENT (items->data);
2270     NR::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2272     // remember the position of the first item
2273     gint pos = SP_OBJECT_REPR (items->data)->position();
2275     // create a list of duplicates
2276     GSList *repr_copies = NULL;
2277     for (GSList *i = items; i != NULL; i = i->next) {
2278         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2279         repr_copies = g_slist_prepend (repr_copies, dup);
2280     }
2281     // restore the z-order after prepends
2282     repr_copies = g_slist_reverse (repr_copies);
2284     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2286     if (apply) {
2287         // delete objects so that their clones don't get alerted; this object will be restored shortly
2288         for (GSList *i = items; i != NULL; i = i->next) {
2289             SPObject *item = SP_OBJECT (i->data);
2290             item->deleteObject (false);
2291         }
2292     }
2294     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2295     // without disturbing clones.
2296     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2297     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2298     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2300     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2301                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2302                                                                                             r->max()[NR::Y]))))
2303                                          * parent_transform.inverse() ),
2304                                        parent_transform * move);
2306     // restore compensation setting
2307     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2309     if (apply) {
2310         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2311         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2313         NR::Point min = bounds.min() * parent_transform.inverse();
2314         NR::Point max = bounds.max() * parent_transform.inverse();
2316         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2317         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2318         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2319         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2321         // restore parent and position
2322         SP_OBJECT_REPR (parent)->appendChild(rect);
2323         rect->setPosition(pos > 0 ? pos : 0);
2324         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2326         Inkscape::GC::release(rect);
2328         selection->clear();
2329         selection->set(rectangle);
2330     }
2332     g_slist_free (items);
2334     sp_document_done (doc, SP_VERB_EDIT_TILE,
2335                       _("Objects to pattern"));
2338 void
2339 sp_selection_untile()
2341     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2342     if (desktop == NULL)
2343         return;
2345     SPDocument *doc = sp_desktop_document(desktop);
2346     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2348     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2350     // check if something is selected
2351     if (selection->isEmpty()) {
2352         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2353         return;
2354     }
2356     GSList *new_select = NULL;
2358     bool did = false;
2360     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2361          items != NULL;
2362          items = items->next) {
2364         SPItem *item = (SPItem *) items->data;
2366         SPStyle *style = SP_OBJECT_STYLE (item);
2368         if (!style || !style->fill.isPaintserver())
2369             continue;
2371         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2373         if (!SP_IS_PATTERN(server))
2374             continue;
2376         did = true;
2378         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2380         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2381         pat_transform *= item->transform;
2383         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2384             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2385             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2387            // FIXME: relink clones to the new canvas objects
2388            // use SPObject::setid when mental finishes it to steal ids of
2390             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2391             sp_document_ensure_up_to_date (doc);
2393             NR::Matrix transform( i->transform * pat_transform );
2394             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2396             new_select = g_slist_prepend(new_select, i);
2397         }
2399         SPCSSAttr *css = sp_repr_css_attr_new ();
2400         sp_repr_css_set_property (css, "fill", "none");
2401         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2402     }
2404     if (!did) {
2405         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2406     } else {
2407         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2408                          _("Pattern to objects"));
2409         selection->setList(new_select);
2410     }
2413 void
2414 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2416     if (selection->isEmpty()) {
2417         return;
2418     }
2420     GSList const *reprlst = selection->reprList();
2421     bool filename_search = TRUE;
2422     bool xdpi_search = TRUE;
2423     bool ydpi_search = TRUE;
2425     for(; reprlst != NULL &&
2426             filename_search &&
2427             xdpi_search &&
2428             ydpi_search;
2429         reprlst = reprlst->next) {
2430         gchar const *dpi_string;
2431         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2433         if (filename_search) {
2434             *filename = repr->attribute("inkscape:export-filename");
2435             if (*filename != NULL)
2436                 filename_search = FALSE;
2437         }
2439         if (xdpi_search) {
2440             dpi_string = NULL;
2441             dpi_string = repr->attribute("inkscape:export-xdpi");
2442             if (dpi_string != NULL) {
2443                 *xdpi = atof(dpi_string);
2444                 xdpi_search = FALSE;
2445             }
2446         }
2448         if (ydpi_search) {
2449             dpi_string = NULL;
2450             dpi_string = repr->attribute("inkscape:export-ydpi");
2451             if (dpi_string != NULL) {
2452                 *ydpi = atof(dpi_string);
2453                 ydpi_search = FALSE;
2454             }
2455         }
2456     }
2459 void
2460 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2462     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2463     gchar const *dpi_string;
2465     *filename = repr->attribute("inkscape:export-filename");
2467     dpi_string = NULL;
2468     dpi_string = repr->attribute("inkscape:export-xdpi");
2469     if (dpi_string != NULL) {
2470         *xdpi = atof(dpi_string);
2471     }
2473     dpi_string = NULL;
2474     dpi_string = repr->attribute("inkscape:export-ydpi");
2475     if (dpi_string != NULL) {
2476         *ydpi = atof(dpi_string);
2477     }
2480 void
2481 sp_selection_create_bitmap_copy ()
2483     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2484     if (desktop == NULL)
2485         return;
2487     SPDocument *document = sp_desktop_document(desktop);
2488     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2490     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2492     // check if something is selected
2493     if (selection->isEmpty()) {
2494         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2495         return;
2496     }
2498     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2499     // set "busy" cursor
2500     desktop->setWaitingCursor();
2502     // Get the bounding box of the selection
2503     NRRect bbox;
2504     sp_document_ensure_up_to_date (document);
2505     selection->bounds(&bbox);
2506     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2507         desktop->clearWaitingCursor();
2508         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2509     }
2511     // List of the items to show; all others will be hidden
2512     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2514     // Sort items so that the topmost comes last
2515     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2517     // Generate a random value from the current time (you may create bitmap from the same object(s)
2518     // multiple times, and this is done so that they don't clash)
2519     GTimeVal cu;
2520     g_get_current_time (&cu);
2521     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2523     // Create the filename
2524     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2525     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2526     // digits, and a few other chars, with "_"
2527     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2528     // Build the complete path by adding document->base if set
2529     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2531     //g_print ("%s\n", filepath);
2533     // Remember parent and z-order of the topmost one
2534     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2535     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2536     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2538     // Calculate resolution
2539     double res;
2540     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2541     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2542     if (0 < prefs_res) {
2543         // If it's given explicitly in prefs, take it
2544         res = prefs_res;
2545     } else if (0 < prefs_min) {
2546         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2547         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2548     } else {
2549         float hint_xdpi = 0, hint_ydpi = 0;
2550         char const *hint_filename;
2551         // take resolution hint from the selected objects
2552         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2553         if (hint_xdpi != 0) {
2554             res = hint_xdpi;
2555         } else {
2556             // take resolution hint from the document
2557             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2558             if (hint_xdpi != 0) {
2559                 res = hint_xdpi;
2560             } else {
2561                 // if all else fails, take the default 90 dpi
2562                 res = PX_PER_IN;
2563             }
2564         }
2565     }
2567     // The width and height of the bitmap in pixels
2568     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2569     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2571     // Find out if we have to run an external filter
2572     gchar const *run = NULL;
2573     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2574     if (filter) {
2575         // filter command is given;
2576         // see if we have a parameter to pass to it
2577         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2578         if (param1) {
2579             if (param1[strlen(param1) - 1] == '%') {
2580                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2581                 gchar p1[256];
2582                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2583                 // the first param is always the image filename, the second is param1
2584                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2585             } else {
2586                 // otherwise pass the param1 unchanged
2587                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2588             }
2589         } else {
2590             // run without extra parameter
2591             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2592         }
2593     }
2595     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2596     NR::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2597     NR::Matrix t;
2599     double shift_x = bbox.x0;
2600     double shift_y = bbox.y1;
2601     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2602         shift_x = round (shift_x);
2603         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2604     }
2605     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2607     // Do the export
2608     sp_export_png_file(document, filepath,
2609                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2610                    width, height, res, res,
2611                    (guint32) 0xffffff00,
2612                    NULL, NULL,
2613                    true,  /*bool force_overwrite,*/
2614                    items);
2616     g_slist_free (items);
2618     // Run filter, if any
2619     if (run) {
2620         g_print ("Running external filter: %s\n", run);
2621         int retval;
2622         retval = system (run);
2623     }
2625     // Import the image back
2626     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2627     if (pb) {
2628         // Create the repr for the image
2629         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2630         repr->setAttribute("xlink:href", filename);
2631         repr->setAttribute("sodipodi:absref", filepath);
2632         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2633             sp_repr_set_svg_double(repr, "width", width);
2634             sp_repr_set_svg_double(repr, "height", height);
2635         } else {
2636             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2637             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2638         }
2640         // Write transform
2641         gchar *c=sp_svg_transform_write(t);
2642         repr->setAttribute("transform", c);
2643         g_free(c);
2645         // add the new repr to the parent
2646         parent->appendChild(repr);
2648         // move to the saved position
2649         repr->setPosition(pos > 0 ? pos + 1 : 1);
2651         // Set selection to the new image
2652         selection->clear();
2653         selection->add(repr);
2655         // Clean up
2656         Inkscape::GC::release(repr);
2657         gdk_pixbuf_unref (pb);
2659         // Complete undoable transaction
2660         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2661                           _("Create bitmap"));
2662     }
2664     desktop->clearWaitingCursor();
2666     g_free (filename);
2667     g_free (filepath);
2670 /**
2671  * \brief Creates a mask or clipPath from selection
2672  * Two different modes:
2673  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2674  *       and is applied to current layer
2675  *  otherwise, topmost object is used as mask for other objects
2676  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2677  *
2678  */
2679 void
2680 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2682     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2683     if (desktop == NULL)
2684         return;
2686     SPDocument *doc = sp_desktop_document(desktop);
2687     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2689     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2691     // check if something is selected
2692     bool is_empty = selection->isEmpty();
2693     if ( apply_to_layer && is_empty) {
2694         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2695         return;
2696     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2697         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2698         return;
2699     }
2701     // FIXME: temporary patch to prevent crash!
2702     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2703     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2704     if (clone_with_original) {
2705         return; // in this version, you cannot clip/mask an object with its own clone
2706     }
2707     // /END FIXME
2709     sp_document_ensure_up_to_date(doc);
2711     GSList *items = g_slist_copy((GSList *) selection->itemList());
2713     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2715     // create a list of duplicates
2716     GSList *mask_items = NULL;
2717     GSList *apply_to_items = NULL;
2718     GSList *items_to_delete = NULL;
2719     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2720     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2722     if (apply_to_layer) {
2723         // all selected items are used for mask, which is applied to a layer
2724         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2726         for (GSList *i = items; i != NULL; i = i->next) {
2727             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2728             mask_items = g_slist_prepend (mask_items, dup);
2730             if (remove_original) {
2731                 SPObject *item = SP_OBJECT (i->data);
2732                 items_to_delete = g_slist_prepend (items_to_delete, item);
2733             }
2734         }
2735     } else if (!topmost) {
2736         // topmost item is used as a mask, which is applied to other items in a selection
2737         GSList *i = items;
2738         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2739         mask_items = g_slist_prepend (mask_items, dup);
2741         if (remove_original) {
2742             SPObject *item = SP_OBJECT (i->data);
2743             items_to_delete = g_slist_prepend (items_to_delete, item);
2744         }
2746         for (i = i->next; i != NULL; i = i->next) {
2747             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2748         }
2749     } else {
2750         GSList *i = NULL;
2751         for (i = items; NULL != i->next; i = i->next) {
2752             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2753         }
2755         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2756         mask_items = g_slist_prepend (mask_items, dup);
2758         if (remove_original) {
2759             SPObject *item = SP_OBJECT (i->data);
2760             items_to_delete = g_slist_prepend (items_to_delete, item);
2761         }
2762     }
2764     g_slist_free (items);
2765     items = NULL;
2767     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2768     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2769         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2770         // inverted object transform should be applied to a mask object,
2771         // as mask is calculated in user space (after applying transform)
2772         NR::Matrix maskTransform (item->transform.inverse());
2774         GSList *mask_items_dup = NULL;
2775         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2776             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2777             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2778         }
2780         gchar const *mask_id = NULL;
2781         if (apply_clip_path) {
2782             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2783         } else {
2784             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2785         }
2787         g_slist_free (mask_items_dup);
2788         mask_items_dup = NULL;
2790         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2791     }
2793     g_slist_free (mask_items);
2794     g_slist_free (apply_to_items);
2796     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2797         SPObject *item = SP_OBJECT (i->data);
2798         item->deleteObject (false);
2799     }
2800     g_slist_free (items_to_delete);
2802     if (apply_clip_path)
2803         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2804     else
2805         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2808 void sp_selection_unset_mask(bool apply_clip_path) {
2809     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2810     if (desktop == NULL)
2811         return;
2813     SPDocument *doc = sp_desktop_document(desktop);
2814     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2815     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2817     // check if something is selected
2818     if (selection->isEmpty()) {
2819         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2820         return;
2821     }
2823     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2824     sp_document_ensure_up_to_date(doc);
2826     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2827     std::map<SPObject*,SPItem*> referenced_objects; 
2828     // SPObject* refers to a group containing the clipped path or mask itself, 
2829     // whereas SPItem* refers to the item being clipped or masked
2830     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2831         if (remove_original) {
2832             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2833             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2834             Inkscape::URIReference *uri_ref = NULL;
2836             if (apply_clip_path) {
2837                 uri_ref = item->clip_ref;
2838             } else {
2839                 uri_ref = item->mask_ref;
2840             }
2842             // collect distinct mask object (and associate with item to apply transform)
2843             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2844                 referenced_objects[uri_ref->getObject()] = item;
2845             }
2846         }
2848         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2849     }
2851     // restore mask objects into a document
2852     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2853         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2854         GSList *items_to_move = NULL;
2855         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2856             // Collect all clipped paths and masks within a single group 
2857             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2858             items_to_move = g_slist_prepend (items_to_move, copy);
2859         }
2861         if (!obj->isReferenced()) {
2862             // delete from defs if no other object references this mask
2863             obj->deleteObject(false);
2864         }
2866         // remember parent and position of the item to which the clippath/mask was applied
2867         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2868         gint pos = SP_OBJECT_REPR((*it).second)->position();
2870         // Iterate through all clipped paths / masks
2871         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2872             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2874             // insert into parent, restore pos
2875             parent->appendChild(repr);
2876             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2878             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2879             selection->add(repr);
2881             // transform mask, so it is moved the same spot where mask was applied
2882             NR::Matrix transform (mask_item->transform);
2883             transform *= (*it).second->transform;
2884             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2885         }
2887         g_slist_free (items_to_move);
2888     }
2890     if (apply_clip_path)
2891         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2892     else
2893         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2896 /**
2897  * Returns true if an undoable change should be recorded.
2898  */
2899 bool
2900 fit_canvas_to_selection(SPDesktop *desktop)
2902     g_return_val_if_fail(desktop != NULL, false);
2903     SPDocument *doc = sp_desktop_document(desktop);
2905     g_return_val_if_fail(doc != NULL, false);
2906     g_return_val_if_fail(desktop->selection != NULL, false);
2908     if (desktop->selection->isEmpty()) {
2909         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2910         return false;
2911     }
2912     boost::optional<NR::Rect> const bbox(desktop->selection->bounds());
2913     if (bbox && !bbox->isEmpty()) {
2914         doc->fitToRect(*bbox);
2915         return true;
2916     } else {
2917         return false;
2918     }
2921 /**
2922  * Fit canvas to the bounding box of the selection, as an undoable action.
2923  */
2924 void
2925 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2927     if (fit_canvas_to_selection(desktop)) {
2928         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2929                          _("Fit Page to Selection"));
2930     }
2933 bool
2934 fit_canvas_to_drawing(SPDocument *doc)
2936     g_return_val_if_fail(doc != NULL, false);
2938     sp_document_ensure_up_to_date(doc);
2939     SPItem const *const root = SP_ITEM(doc->root);
2940     boost::optional<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
2941     if (bbox && !bbox->isEmpty()) {
2942         doc->fitToRect(*bbox);
2943         return true;
2944     } else {
2945         return false;
2946     }
2949 void
2950 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2952     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2953         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2954                          _("Fit Page to Drawing"));
2955     }
2958 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2959     g_return_if_fail(desktop != NULL);
2960     SPDocument *doc = sp_desktop_document(desktop);
2962     g_return_if_fail(doc != NULL);
2963     g_return_if_fail(desktop->selection != NULL);
2965     bool const changed = ( desktop->selection->isEmpty()
2966                            ? fit_canvas_to_drawing(doc)
2967                            : fit_canvas_to_selection(desktop) );
2968     if (changed) {
2969         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2970                          _("Fit Page to Selection or Drawing"));
2971     }
2972 };
2974 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2975     // don't operate on layers
2976     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2977         f(SP_ITEM(root), desktop);
2978     }
2979     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2980         //don't recurse into locked layers
2981         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2982             itemtree_map(f, iter, desktop);
2983         }
2984     }
2987 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2988     if (item->isLocked()) {
2989         item->setLocked(FALSE);
2990     }
2993 static void unhide(SPItem *item, SPDesktop *desktop) {
2994     if (desktop->itemIsHidden(item)) {
2995         item->setExplicitlyHidden(FALSE);
2996     }
2999 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3000     if (!dt) return;
3002     SPObject *root;
3003     if (layer_only) {
3004         root = dt->currentLayer();
3005     } else {
3006         root = dt->currentRoot();
3007     }
3009     itemtree_map(f, root, dt);
3012 void unlock_all(SPDesktop *dt) {
3013     process_all(&unlock, dt, true);
3016 void unlock_all_in_all_layers(SPDesktop *dt) {
3017     process_all(&unlock, dt, false);
3020 void unhide_all(SPDesktop *dt) {
3021     process_all(&unhide, dt, true);
3024 void unhide_all_in_all_layers(SPDesktop *dt) {
3025     process_all(&unhide, dt, false);
3029 /*
3030   Local Variables:
3031   mode:c++
3032   c-file-style:"stroustrup"
3033   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3034   indent-tabs-mode:nil
3035   fill-column:99
3036   End:
3037 */
3038 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :