Code

fix crash when duplicating an orphaned clone
[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 "desktop.h"
29 #include "desktop-style.h"
30 #include "selection.h"
31 #include "tools-switch.h"
32 #include "desktop-handles.h"
33 #include "message-stack.h"
34 #include "sp-item-transform.h"
35 #include "marker.h"
36 #include "sp-use.h"
37 #include "sp-textpath.h"
38 #include "sp-tspan.h"
39 #include "sp-tref.h"
40 #include "sp-flowtext.h"
41 #include "sp-flowregion.h"
42 #include "text-editing.h"
43 #include "text-context.h"
44 #include "connector-context.h"
45 #include "sp-path.h"
46 #include "sp-conn-end.h"
47 #include "dropper-context.h"
48 #include <glibmm/i18n.h>
49 #include "libnr/nr-matrix-rotate-ops.h"
50 #include "libnr/nr-matrix-translate-ops.h"
51 #include "libnr/nr-scale-ops.h"
52 #include <libnr/nr-matrix-ops.h>
53 #include <2geom/transforms.h>
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "preferences.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include <cstring>
73 #include <string>
74 #include "helper/units.h"
75 #include "sp-item.h"
76 #include "box3d.h"
77 #include "unit-constants.h"
78 #include "xml/simple-document.h"
79 #include "sp-filter-reference.h"
80 #include "gradient-drag.h"
81 #include "uri-references.h"
82 #include "libnr/nr-convert2geom.h"
83 #include "display/curve.h"
84 #include "display/canvas-bpath.h"
85 #include "inkscape-private.h"
87 // For clippath editing
88 #include "tools-switch.h"
89 #include "shape-editor.h"
90 #include "node-context.h"
91 #include "nodepath.h"
93 #include "ui/clipboard.h"
95 using Geom::X;
96 using Geom::Y;
98 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
99 because the layer manipulation code uses them. It should be rewritten specifically
100 for that purpose. */
102 /**
103  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
104  * then prepends the copy to 'clip'.
105  */
106 void sp_selection_copy_one (Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
108     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
110     // copy complete inherited style
111     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
112     sp_repr_css_set(copy, css, "style");
113     sp_repr_css_attr_unref(css);
115     // write the complete accumulated transform passed to us
116     // (we're dealing with unattached repr, so we write to its attr
117     // instead of using sp_item_set_transform)
118     gchar *affinestr=sp_svg_transform_write(full_t);
119     copy->setAttribute("transform", affinestr);
120     g_free(affinestr);
122     *clip = g_slist_prepend(*clip, copy);
125 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
127     // Sort items:
128     GSList *sorted_items = g_slist_copy ((GSList *) items);
129     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
131     // Copy item reprs:
132     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
133         sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
134     }
136     *clip = g_slist_reverse(*clip);
137     g_slist_free ((GSList *) sorted_items);
140 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
142     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
144     GSList *copied = NULL;
145     // add objects to document
146     for (GSList *l = *clip; l != NULL; l = l->next) {
147         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
148         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
150         // premultiply the item transform by the accumulated parent transform in the paste layer
151         Geom::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
152         if (!local.isIdentity()) {
153             gchar const *t_str = copy->attribute("transform");
154             Geom::Matrix item_t (Geom::identity());
155             if (t_str)
156                 sp_svg_transform_read(t_str, &item_t);
157             item_t *= local.inverse();
158             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
159             gchar *affinestr=sp_svg_transform_write(item_t);
160             copy->setAttribute("transform", affinestr);
161             g_free(affinestr);
162         }
164         parent->appendChildRepr(copy);
165         copied = g_slist_prepend(copied, copy);
166         Inkscape::GC::release(copy);
167     }
168     return copied;
171 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
173     for (GSList const *i = items ; i ; i = i->next ) {
174         sp_object_ref((SPObject *)i->data, NULL);
175     }
176     for (GSList const *i = items; i != NULL; i = i->next) {
177         SPItem *item = (SPItem *) i->data;
178         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
179         sp_object_unref((SPObject *)item, NULL);
180     }
184 void sp_selection_delete(SPDesktop *desktop)
186     if (desktop == NULL) {
187         return;
188     }
190     if (tools_isactive (desktop, TOOLS_TEXT))
191         if (sp_text_delete_selection(desktop->event_context)) {
192             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
193                              _("Delete text"));
194             return;
195         }
197     Inkscape::Selection *selection = sp_desktop_selection(desktop);
199     // check if something is selected
200     if (selection->isEmpty()) {
201         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
202         return;
203     }
205     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
206     selection->clear();
207     sp_selection_delete_impl (selected);
208     g_slist_free ((GSList *) selected);
210     /* a tool may have set up private information in it's selection context
211      * that depends on desktop items.  I think the only sane way to deal with
212      * this currently is to reset the current tool, which will reset it's
213      * associated selection context.  For example: deleting an object
214      * while moving it around the canvas.
215      */
216     tools_switch ( desktop, tools_active ( desktop ) );
218     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
219                      _("Delete"));
222 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
224     if (!obj)
225         return;
227     ids.push_back(SP_OBJECT_ID(obj));
229     if (SP_IS_GROUP(obj)) {
230         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
231             add_ids_recursive (ids, child);
232         }
233     }
236 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
238     if (desktop == NULL)
239         return;
241     SPDocument *doc = desktop->doc();
242     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
243     Inkscape::Selection *selection = sp_desktop_selection(desktop);
245     // check if something is selected
246     if (selection->isEmpty()) {
247         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
248         return;
249     }
251     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
253     selection->clear();
255     // sorting items from different parents sorts each parent's subset without possibly mixing
256     // them, just what we need
257     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
259     GSList *newsel = NULL;
261     std::vector<const gchar *> old_ids;
262     std::vector<const gchar *> new_ids;
263     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
264     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
266     while (reprs) {
267         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
268         Inkscape::XML::Node *parent = old_repr->parent();
269         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
271         parent->appendChild(copy);
273         if (relink_clones) {
274             SPObject *old_obj = doc->getObjectByRepr(old_repr);
275             SPObject *new_obj = doc->getObjectByRepr(copy);
276             add_ids_recursive (old_ids, old_obj);
277             add_ids_recursive (new_ids, new_obj);
278         }
280         newsel = g_slist_prepend(newsel, copy);
281         reprs = g_slist_remove(reprs, reprs->data);
282         Inkscape::GC::release(copy);
283     }
285     if (relink_clones) {
287         g_assert (old_ids.size() == new_ids.size());
289         for(unsigned int i = 0; i < old_ids.size(); i++) {
290             const gchar *id = old_ids[i];
291             SPObject *old_clone = doc->getObjectById(id);
292             if (SP_IS_USE(old_clone)) {
293                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
294                 if (!orig) // orphaned
295                     continue;
296                 for(unsigned int j = 0; j < old_ids.size(); j++) {
297                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
298                         // we have both orig and clone in selection, relink
299                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
300                         gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
301                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
302                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
303                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
304                         g_free (newref);
305                     }
306                 }
307             }
308         }
309     }
312     if ( !suppressDone ) {
313         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
314                          _("Duplicate"));
315     }
317     selection->setReprList(newsel);
319     g_slist_free(newsel);
322 void sp_edit_clear_all(SPDesktop *dt)
324     if (!dt)
325         return;
327     SPDocument *doc = sp_desktop_document(dt);
328     sp_desktop_selection(dt)->clear();
330     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
331     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
333     while (items) {
334         SP_OBJECT (items->data)->deleteObject();
335         items = g_slist_remove(items, items->data);
336     }
338     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
339                      _("Delete all"));
342 GSList *
343 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
345     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
346         if (SP_IS_ITEM(child) &&
347             !desktop->isLayer(SP_ITEM(child)) &&
348             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
349             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
350             (!exclude || !g_slist_find ((GSList *) exclude, child))
351             )
352         {
353             list = g_slist_prepend (list, SP_ITEM(child));
354         }
356         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
357             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
358         }
359     }
361     return list;
364 void sp_edit_select_all_full (SPDesktop *dt, bool force_all_layers, bool invert)
366     if (!dt)
367         return;
369     Inkscape::Selection *selection = sp_desktop_selection(dt);
371     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
372     
373     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
374     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
375     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
376     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
378     GSList *items = NULL;
380     GSList const *exclude = NULL;
381     if (invert) {
382         exclude = selection->itemList();
383     }
385     if (force_all_layers)
386         inlayer = PREFS_SELECTION_ALL;
388     switch (inlayer) {
389         case PREFS_SELECTION_LAYER: {
390         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
391              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
392         return;
394         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
396         for (GSList *i = all_items; i; i = i->next) {
397             SPItem *item = SP_ITEM (i->data);
399             if (item && (!onlysensitive || !item->isLocked())) {
400                 if (!onlyvisible || !dt->itemIsHidden(item)) {
401                     if (!dt->isLayer(item)) {
402                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
403                             items = g_slist_prepend (items, item); // leave it in the list
404                         }
405                     }
406                 }
407             }
408         }
410         g_slist_free (all_items);
411             break;
412         }
413         case PREFS_SELECTION_LAYER_RECURSIVE: {
414             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
415             break;
416         }
417         default: {
418         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
419             break;
420     }
421     }
423     selection->setList (items);
425     if (items) {
426         g_slist_free (items);
427     }
430 void sp_edit_select_all (SPDesktop *desktop)
432     sp_edit_select_all_full (desktop, false, false);
435 void sp_edit_select_all_in_all_layers (SPDesktop *desktop)
437     sp_edit_select_all_full (desktop, true, false);
440 void sp_edit_invert (SPDesktop *desktop)
442     sp_edit_select_all_full (desktop, false, true);
445 void sp_edit_invert_in_all_layers (SPDesktop *desktop)
447     sp_edit_select_all_full (desktop, true, true);
450 void sp_selection_group(SPDesktop *desktop)
452     if (desktop == NULL)
453         return;
455     SPDocument *doc = sp_desktop_document (desktop);
456     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
458     Inkscape::Selection *selection = sp_desktop_selection(desktop);
460     // Check if something is selected.
461     if (selection->isEmpty()) {
462         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
463         return;
464     }
466     GSList const *l = (GSList *) selection->reprList();
468     GSList *p = g_slist_copy((GSList *) l);
470     selection->clear();
472     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
474     // Remember the position and parent of the topmost object.
475     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
476     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
478     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
480     while (p) {
481         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
483         if (current->parent() == topmost_parent) {
484             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
485             sp_repr_unparent(current);
486             group->appendChild(spnew);
487             Inkscape::GC::release(spnew);
488             topmost --; // only reduce count for those items deleted from topmost_parent
489         } else { // move it to topmost_parent first
490                 GSList *temp_clip = NULL;
492                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
493                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
494                 gchar const *t_str = current->attribute("transform");
495                 Geom::Matrix item_t (Geom::identity());
496                 if (t_str)
497                     sp_svg_transform_read(t_str, &item_t);
498                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
499                 //FIXME: when moving both clone and original from a transformed group (either by
500                 //grouping into another parent, or by cut/paste) the transform from the original's
501                 //parent becomes embedded into original itself, and this affects its clones. Fix
502                 //this by remembering the transform diffs we write to each item into an array and
503                 //then, if this is clone, looking up its original in that array and pre-multiplying
504                 //it by the inverse of that original's transform diff.
506                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
507                 sp_repr_unparent(current);
509                 // paste into topmost_parent (temporarily)
510                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
511                 if (temp_clip) g_slist_free (temp_clip);
512                 if (copied) { // if success,
513                     // take pasted object (now in topmost_parent)
514                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
515                     // make a copy
516                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
517                     // remove pasted
518                     sp_repr_unparent(in_topmost);
519                     // put its copy into group
520                     group->appendChild(spnew);
521                     Inkscape::GC::release(spnew);
522                     g_slist_free (copied);
523                 }
524         }
525         p = g_slist_remove(p, current);
526     }
528     // Add the new group to the topmost members' parent
529     topmost_parent->appendChild(group);
531     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
532     group->setPosition(topmost + 1);
534     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
535                      _("Group"));
537     selection->set(group);
538     Inkscape::GC::release(group);
541 void sp_selection_ungroup(SPDesktop *desktop)
543     if (desktop == NULL)
544         return;
546     Inkscape::Selection *selection = sp_desktop_selection(desktop);
548     if (selection->isEmpty()) {
549         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
550         return;
551     }
553     GSList *items = g_slist_copy((GSList *) selection->itemList());
554     selection->clear();
556     // Get a copy of current selection.
557     GSList *new_select = NULL;
558     bool ungrouped = false;
559     for (GSList *i = items;
560          i != NULL;
561          i = i->next)
562     {
563         SPItem *group = (SPItem *) i->data;
565         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
566         if (!SP_IS_OBJECT(group)) {
567             continue;
568         }
570         /* We do not allow ungrouping <svg> etc. (lauris) */
571         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
572             // keep the non-group item in the new selection
573             selection->add(group);
574             continue;
575         }
577         GSList *children = NULL;
578         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
579         sp_item_group_ungroup(SP_GROUP(group), &children, false);
580         ungrouped = true;
581         // Add ungrouped items to the new selection.
582         new_select = g_slist_concat(new_select, children);
583     }
585     if (new_select) { // Set new selection.
586         selection->addList(new_select);
587         g_slist_free(new_select);
588     }
589     if (!ungrouped) {
590         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
591     }
593     g_slist_free(items);
595     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
596                      _("Ungroup"));
599 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
600 GSList *
601 sp_degroup_list (GSList *items)
603     GSList *out = NULL;
604     bool has_groups = false;
605     for (GSList *item = items; item; item = item->next) {
606         if (!SP_IS_GROUP(item->data)) {
607             out = g_slist_prepend(out, item->data);
608         } else {
609             has_groups = true;
610             GSList *members = sp_item_group_item_list (SP_GROUP(item->data));
611             for (GSList *member = members; member; member = member->next) {
612                 out = g_slist_prepend(out, member->data);
613             }
614             g_slist_free (members);
615         }
616     }
617     out = g_slist_reverse (out);
618     g_slist_free (items);
620     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
621         out = sp_degroup_list (out);
622     }
624     return out;
626  
628 /** If items in the list have a common parent, return it, otherwise return NULL */
629 static SPGroup *
630 sp_item_list_common_parent_group(GSList const *items)
632     if (!items) {
633         return NULL;
634     }
635     SPObject *parent = SP_OBJECT_PARENT(items->data);
636     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
637     if (!SP_IS_GROUP(parent)) {
638         return NULL;
639     }
640     for (items = items->next; items; items = items->next) {
641         if (SP_OBJECT_PARENT(items->data) != parent) {
642             return NULL;
643         }
644     }
646     return SP_GROUP(parent);
649 /** Finds out the minimum common bbox of the selected items. */
650 static Geom::OptRect
651 enclose_items(GSList const *items)
653     g_assert(items != NULL);
655     Geom::OptRect r;
656     for (GSList const *i = items; i; i = i->next) {
657         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
658     }
659     return r;
662 SPObject *
663 prev_sibling(SPObject *child)
665     SPObject *parent = SP_OBJECT_PARENT(child);
666     if (!SP_IS_GROUP(parent)) {
667         return NULL;
668     }
669     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
670         if (i->next == child)
671             return i;
672     }
673     return NULL;
676 void
677 sp_selection_raise(SPDesktop *desktop)
679     if (!desktop)
680         return;
682     Inkscape::Selection *selection = sp_desktop_selection(desktop);
684     GSList const *items = (GSList *) selection->itemList();
685     if (!items) {
686         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
687         return;
688     }
690     SPGroup const *group = sp_item_list_common_parent_group(items);
691     if (!group) {
692         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
693         return;
694     }
696     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
698     /* Construct reverse-ordered list of selected children. */
699     GSList *rev = g_slist_copy((GSList *) items);
700     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
702     // Determine the common bbox of the selected items.
703     Geom::OptRect selected = enclose_items(items);
705     // Iterate over all objects in the selection (starting from top).
706     if (selected) {
707         while (rev) {
708             SPObject *child = SP_OBJECT(rev->data);
709             // for each selected object, find the next sibling
710             for (SPObject *newref = child->next; newref; newref = newref->next) {
711                 // if the sibling is an item AND overlaps our selection,
712                 if (SP_IS_ITEM(newref)) {
713                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
714                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
715                         // AND if it's not one of our selected objects,
716                         if (!g_slist_find((GSList *) items, newref)) {
717                             // move the selected object after that sibling
718                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
719                         }
720                         break;
721                     }
722                 }
723             }
724             rev = g_slist_remove(rev, child);
725         }
726     } else {
727         g_slist_free(rev);
728     }
730     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
731                      //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
732                      Q_("undo_action|Raise"));
735 void sp_selection_raise_to_top(SPDesktop *desktop)
737     if (desktop == NULL)
738         return;
740     SPDocument *document = sp_desktop_document(desktop);
741     Inkscape::Selection *selection = sp_desktop_selection(desktop);
743     if (selection->isEmpty()) {
744         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
745         return;
746     }
748     GSList const *items = (GSList *) selection->itemList();
750     SPGroup const *group = sp_item_list_common_parent_group(items);
751     if (!group) {
752         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
753         return;
754     }
756     GSList *rl = g_slist_copy((GSList *) selection->reprList());
757     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
759     for (GSList *l = rl; l != NULL; l = l->next) {
760         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
761         repr->setPosition(-1);
762     }
764     g_slist_free(rl);
766     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
767                      _("Raise to top"));
770 void
771 sp_selection_lower(SPDesktop *desktop)
773     if (desktop == NULL)
774         return;
776     Inkscape::Selection *selection = sp_desktop_selection(desktop);
778     GSList const *items = (GSList *) selection->itemList();
779     if (!items) {
780         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
781         return;
782     }
784     SPGroup const *group = sp_item_list_common_parent_group(items);
785     if (!group) {
786         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
787         return;
788     }
790     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
792     // Determine the common bbox of the selected items.
793     Geom::OptRect selected = enclose_items(items);
795     /* Construct direct-ordered list of selected children. */
796     GSList *rev = g_slist_copy((GSList *) items);
797     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
798     rev = g_slist_reverse(rev);
800     // Iterate over all objects in the selection (starting from top).
801     if (selected) {
802         while (rev) {
803             SPObject *child = SP_OBJECT(rev->data);
804             // for each selected object, find the prev sibling
805             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
806                 // if the sibling is an item AND overlaps our selection,
807                 if (SP_IS_ITEM(newref)) {
808                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
809                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
810                         // AND if it's not one of our selected objects,
811                         if (!g_slist_find((GSList *) items, newref)) {
812                             // move the selected object before that sibling
813                             SPObject *put_after = prev_sibling(newref);
814                             if (put_after)
815                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
816                             else
817                                 SP_OBJECT_REPR(child)->setPosition(0);
818                         }
819                         break;
820                     }
821                 }
822             }
823             rev = g_slist_remove(rev, child);
824         }
825     } else {
826         g_slist_free(rev);
827     }
829     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
830                      _("Lower"));
833 void sp_selection_lower_to_bottom(SPDesktop *desktop)
835     if (desktop == NULL)
836         return;
838     SPDocument *document = sp_desktop_document(desktop);
839     Inkscape::Selection *selection = sp_desktop_selection(desktop);
841     if (selection->isEmpty()) {
842         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
843         return;
844     }
846     GSList const *items = (GSList *) selection->itemList();
848     SPGroup const *group = sp_item_list_common_parent_group(items);
849     if (!group) {
850         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
851         return;
852     }
854     GSList *rl;
855     rl = g_slist_copy((GSList *) selection->reprList());
856     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
857     rl = g_slist_reverse(rl);
859     for (GSList *l = rl; l != NULL; l = l->next) {
860         gint minpos;
861         SPObject *pp, *pc;
862         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
863         pp = document->getObjectByRepr(sp_repr_parent(repr));
864         minpos = 0;
865         g_assert(SP_IS_GROUP(pp));
866         pc = sp_object_first_child(pp);
867         while (!SP_IS_ITEM(pc)) {
868             minpos += 1;
869             pc = pc->next;
870         }
871         repr->setPosition(minpos);
872     }
874     g_slist_free(rl);
876     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
877                      _("Lower to bottom"));
880 void
881 sp_undo(SPDesktop *desktop, SPDocument *)
883         if (!sp_document_undo(sp_desktop_document(desktop)))
884             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
887 void
888 sp_redo(SPDesktop *desktop, SPDocument *)
890         if (!sp_document_redo(sp_desktop_document(desktop)))
891             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
894 void sp_selection_cut(SPDesktop *desktop)
896     sp_selection_copy();
897     sp_selection_delete(desktop);
900 /**
901  * \pre item != NULL
902  */
903 SPCSSAttr *
904 take_style_from_item (SPItem *item)
906     // write the complete cascaded style, context-free
907     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
908     if (css == NULL)
909         return NULL;
911     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
912         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
913         // if this is a text with exactly one tspan child, merge the style of that tspan as well
914         // If this is a group, merge the style of its topmost (last) child with style
915         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
916             if (SP_OBJECT_STYLE (last_element) != NULL) {
917                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
918                 if (temp) {
919                     sp_repr_css_merge (css, temp);
920                     sp_repr_css_attr_unref (temp);
921                 }
922                 break;
923             }
924         }
925     }
926     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
927         // do not copy text properties from non-text objects, it's confusing
928         css = sp_css_attr_unset_text (css);
929     }
931     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
932     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
933     if (ex != 1.0) {
934         css = sp_css_attr_scale (css, ex);
935     }
937     return css;
941 void sp_selection_copy()
943     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
944     cm->copy();
947 void sp_selection_paste(SPDesktop *desktop, bool in_place)
949     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
950     if(cm->paste(in_place))
951         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
954 void sp_selection_paste_style(SPDesktop *desktop)
956     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
957     if(cm->pasteStyle())
958         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
962 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
964     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
965     if(cm->pastePathEffect())
966         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
967                      _("Paste live path effect"));
971 void sp_selection_remove_livepatheffect_impl(SPItem *item)
973     if ( item && SP_IS_LPE_ITEM(item) ) {
974         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
975     }
978 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
980     if (desktop == NULL) return;
982     Inkscape::Selection *selection = sp_desktop_selection(desktop);
984     // check if something is selected
985     if (selection->isEmpty()) {
986         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
987         return;
988     }
990     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
991         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
993         sp_selection_remove_livepatheffect_impl(item);
995     }
997     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
998                      _("Remove live path effect"));
1001 void sp_selection_remove_filter (SPDesktop *desktop)
1003     if (desktop == NULL) return;
1005     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1007     // check if something is selected
1008     if (selection->isEmpty()) {
1009         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1010         return;
1011     }
1013     SPCSSAttr *css = sp_repr_css_attr_new();
1014     sp_repr_css_unset_property(css, "filter");
1015     sp_desktop_set_style(desktop, css);
1016     sp_repr_css_attr_unref(css);
1018     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
1019                      _("Remove filter"));
1023 void sp_selection_paste_size (SPDesktop *desktop, bool apply_x, bool apply_y)
1025     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1026     if(cm->pasteSize(false, apply_x, apply_y))
1027         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1028                      _("Paste size"));
1031 void sp_selection_paste_size_separately (SPDesktop *desktop, bool apply_x, bool apply_y)
1033     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1034     if(cm->pasteSize(true, apply_x, apply_y))
1035         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1036                      _("Paste size separately"));
1039 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1041     Inkscape::Selection *selection = sp_desktop_selection(dt);
1043     // check if something is selected
1044     if (selection->isEmpty()) {
1045         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1046         return;
1047     }
1049     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1051     bool no_more = false; // Set to true, if no more layers above
1052     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1053     if (next) {
1054         GSList *temp_clip = NULL;
1055         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1056         sp_selection_delete_impl (items, false, false);
1057         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1058         GSList *copied;
1059         if(next) {
1060             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1061         } else {
1062             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1063             no_more = true;
1064         }
1065         selection->setReprList((GSList const *) copied);
1066         g_slist_free (copied);
1067         if (temp_clip) g_slist_free (temp_clip);
1068         if (next) dt->setCurrentLayer(next);
1069         if ( !suppressDone ) {
1070             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1071                              _("Raise to next layer"));
1072         }
1073     } else {
1074         no_more = true;
1075     }
1077     if (no_more) {
1078         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1079     }
1081     g_slist_free ((GSList *) items);
1084 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1086     Inkscape::Selection *selection = sp_desktop_selection(dt);
1088     // check if something is selected
1089     if (selection->isEmpty()) {
1090         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1091         return;
1092     }
1094     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1096     bool no_more = false; // Set to true, if no more layers below
1097     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1098     if (next) {
1099         GSList *temp_clip = NULL;
1100         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
1101         sp_selection_delete_impl (items, false, false);
1102         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1103         GSList *copied;
1104         if(next) {
1105             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1106         } else {
1107             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1108             no_more = true;
1109         }
1110         selection->setReprList((GSList const *) copied);
1111         g_slist_free (copied);
1112         if (temp_clip) g_slist_free (temp_clip);
1113         if (next) dt->setCurrentLayer(next);
1114         if ( !suppressDone ) {
1115             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1116                              _("Lower to previous layer"));
1117         }
1118     } else {
1119         no_more = true;
1120     }
1122     if (no_more) {
1123         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1124     }
1126     g_slist_free ((GSList *) items);
1129 bool
1130 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1132     bool contains_original = false;
1134     bool is_use = SP_IS_USE(item);
1135     SPItem *item_use = item;
1136     SPItem *item_use_first = item;
1137     while (is_use && item_use && !contains_original)
1138     {
1139         item_use = sp_use_get_original (SP_USE(item_use));
1140         contains_original |= selection->includes(item_use);
1141         if (item_use == item_use_first)
1142             break;
1143         is_use = SP_IS_USE(item_use);
1144     }
1146     // If it's a tref, check whether the object containing the character
1147     // data is part of the selection
1148     if (!contains_original && SP_IS_TREF(item)) {
1149         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1150     }
1152     return contains_original;
1156 bool
1157 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1159     bool clone_with_original = false;
1160     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1161         SPItem *item = SP_ITEM(l->data);
1162         clone_with_original |= selection_contains_original(item, selection);
1163         if (clone_with_original)
1164             break;
1165     }
1166     return clone_with_original;
1170 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1171 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1172 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1173 that case, items are already in the new position, but the repr is in the old, and this function
1174 then simply updates the repr from item->transform.
1175  */
1176 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1178     if (selection->isEmpty())
1179         return;
1181     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1182         SPItem *item = SP_ITEM(l->data);
1184         Geom::Point old_center(0,0);
1185         if (set_i2d && item->isCenterSet())
1186             old_center = item->getCenter();
1188 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1189          At the time of writing, this is the only place to re-enable. */
1190         sp_item_update_cns(*item, selection->desktop());
1191 #endif
1193         // we're moving both a clone and its original or any ancestor in clone chain?
1194         bool transform_clone_with_original = selection_contains_original(item, selection);
1195         // ...both a text-on-path and its path?
1196         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)))) ));
1197         // ...both a flowtext and its frame?
1198         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)
1199         // ...both an offset and its source?
1200         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1202         // If we're moving a connector, we want to detach it
1203         // from shapes that aren't part of the selection, but
1204         // leave it attached if they are
1205         if (cc_item_is_connector(item)) {
1206             SPItem *attItem[2];
1207             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1209             for (int n = 0; n < 2; ++n) {
1210                 if (!selection->includes(attItem[n])) {
1211                     sp_conn_end_detach(item, n);
1212                 }
1213             }
1214         }
1216         // "clones are unmoved when original is moved" preference
1217         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1218         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1219         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1220         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1222         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1223         // transform of its original and respond to it itself. Without this, a clone is doubly
1224         // transformed, very unintuitive.
1225       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1226       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1227       // Same for linked offset if we are also moving its source: do not move it.
1228         if (transform_textpath_with_path || transform_offset_with_source) {
1229                 // restore item->transform field from the repr, in case it was changed by seltrans
1230             sp_object_read_attr (SP_OBJECT (item), "transform");
1232         } else if (transform_flowtext_with_frame) {
1233             // apply the inverse of the region's transform to the <use> so that the flow remains
1234             // the same (even though the output itself gets transformed)
1235             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1236                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1237                     continue;
1238                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1239                     if (!SP_IS_USE(use)) continue;
1240                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1241                 }
1242             }
1243         } else if (transform_clone_with_original) {
1244             // We are transforming a clone along with its original. The below matrix juggling is
1245             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1246             // transform and its move compensation are both cancelled out.
1248             // restore item->transform field from the repr, in case it was changed by seltrans
1249             sp_object_read_attr (SP_OBJECT (item), "transform");
1251             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1252             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1253             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1254             Geom::Matrix t_inv = t.inverse();
1255             Geom::Matrix result = t_inv * item->transform * t;
1257             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1258                 // we need to cancel out the move compensation, too
1260                 // find out the clone move, same as in sp_use_move_compensate
1261                 Geom::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1262                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1264                 if (prefs_parallel) {
1265                     Geom::Matrix move = result * clone_move * t_inv;
1266                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1268                 } else if (prefs_unmoved) {
1269                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1270                     //    clone_move = Geom::identity();
1271                     Geom::Matrix move = result * clone_move;
1272                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1273                 }
1275             } else {
1276                 // just apply the result
1277                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1278             }
1280         } else {
1281             if (set_i2d) {
1282                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1283             }
1284             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1285         }
1287         // if we're moving the actual object, not just updating the repr, we can transform the
1288         // center by the same matrix (only necessary for non-translations)
1289         if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1290             item->setCenter(old_center * affine);
1291             SP_OBJECT(item)->updateRepr();
1292         }
1293     }
1296 void sp_selection_remove_transform(SPDesktop *desktop)
1298     if (desktop == NULL)
1299         return;
1301     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1303     GSList const *l = (GSList *) selection->reprList();
1304     while (l != NULL) {
1305         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1306         l = l->next;
1307     }
1309     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1310                      _("Remove transform"));
1313 void
1314 sp_selection_scale_absolute(Inkscape::Selection *selection,
1315                             double const x0, double const x1,
1316                             double const y0, double const y1)
1318     if (selection->isEmpty())
1319         return;
1321     Geom::OptRect const bbox(selection->bounds());
1322     if ( !bbox ) {
1323         return;
1324     }
1326     Geom::Translate const p2o(-bbox->min());
1328     Geom::Scale const newSize(x1 - x0,
1329                             y1 - y0);
1330     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1331     Geom::Translate const o2n(x0, y0);
1332     Geom::Matrix const final( p2o * scale * o2n );
1334     sp_selection_apply_affine(selection, final);
1338 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1340     if (selection->isEmpty())
1341         return;
1343     Geom::OptRect const bbox(selection->bounds());
1345     if ( !bbox ) {
1346         return;
1347     }
1349     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1350     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1351          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1352     {
1353         return;
1354     }
1356     Geom::Translate const n2d(-align);
1357     Geom::Translate const d2n(align);
1358     Geom::Matrix const final( n2d * scale * d2n );
1359     sp_selection_apply_affine(selection, final);
1362 void
1363 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1365     Geom::Translate const d2n(center);
1366     Geom::Translate const n2d(-center);
1367     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1368     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1369     sp_selection_apply_affine(selection, final);
1372 void
1373 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1375     Geom::Translate const d2n(align);
1376     Geom::Translate const n2d(-align);
1377     Geom::Matrix const skew(1, dy,
1378                             dx, 1,
1379                             0, 0);
1380     Geom::Matrix const final( n2d * skew * d2n );
1381     sp_selection_apply_affine(selection, final);
1384 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1386     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)));
1389 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1391     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1394 /**
1395  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1396  */
1397 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1399     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1401     if (selection->isEmpty())
1402         return;
1404     GSList const *l = selection->itemList();
1405     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1406     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1407         SPItem *item = SP_ITEM(l2->data);
1408         sp_item_rotate_rel(item, rot_90);
1409     }
1411     sp_document_done(sp_desktop_document(desktop),
1412                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1413                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1416 void
1417 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1419     if (selection->isEmpty())
1420         return;
1422     boost::optional<Geom::Point> center = selection->center();
1423     if (!center) {
1424         return;
1425     }
1427     sp_selection_rotate_relative(selection, *center, angle_degrees);
1429     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1430                            ( ( angle_degrees > 0 )
1431                              ? "selector:rotate:ccw"
1432                              : "selector:rotate:cw" ),
1433                            SP_VERB_CONTEXT_SELECT,
1434                            _("Rotate"));
1437 // helper function:
1438 static
1439 Geom::Point
1440 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1441     Geom::Point m = r.midpoint();
1442     unsigned i = 0;
1443     if (p[X] < m[X]) {
1444         i = 1;
1445     }
1446     if (p[Y] < m[Y]) {
1447         i = 3 - i;
1448     }
1449     return r.corner(i);
1452 /**
1453 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1454 */
1455 void
1456 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1458     if (selection->isEmpty())
1459         return;
1461     Geom::OptRect const bbox(selection->bounds());
1462     boost::optional<Geom::Point> center = selection->center();
1464     if ( !bbox || !center ) {
1465         return;
1466     }
1468     gdouble const zoom = selection->desktop()->current_zoom();
1469     gdouble const zmove = angle / zoom;
1470     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1472     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1474     sp_selection_rotate_relative(selection, *center, zangle);
1476     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1477                            ( (angle > 0)
1478                              ? "selector:rotate:ccw"
1479                              : "selector:rotate:cw" ),
1480                            SP_VERB_CONTEXT_SELECT,
1481                            _("Rotate by pixels"));
1484 void
1485 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1487     if (selection->isEmpty())
1488         return;
1490     Geom::OptRect const bbox(selection->bounds());
1491     if (!bbox) {
1492         return;
1493     }
1495     Geom::Point const center(bbox->midpoint());
1497     // you can't scale "do nizhe pola" (below zero)
1498     double const max_len = bbox->maxExtent();
1499     if ( max_len + grow <= 1e-3 ) {
1500         return;
1501     }
1503     double const times = 1.0 + grow / max_len;
1504     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1506     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1507                            ( (grow > 0)
1508                              ? "selector:scale:larger"
1509                              : "selector:scale:smaller" ),
1510                            SP_VERB_CONTEXT_SELECT,
1511                            _("Scale"));
1514 void
1515 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1517     sp_selection_scale(selection,
1518                        grow_pixels / selection->desktop()->current_zoom());
1521 void
1522 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1524     if (selection->isEmpty())
1525         return;
1527     Geom::OptRect sel_bbox = selection->bounds();
1529     if (!sel_bbox) {
1530         return;
1531     }
1533     Geom::Point const center(sel_bbox->midpoint());
1534     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1535     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1536                      _("Scale by whole factor"));
1539 void
1540 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
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(SPDesktop *desktop, gdouble dx, gdouble dy)
1564     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1565     if (selection->isEmpty()) {
1566         return;
1567     }
1569     // same as sp_selection_move but divide deltas by zoom factor
1570     gdouble const zoom = desktop->current_zoom();
1571     gdouble const zdx = dx / zoom;
1572     gdouble const zdy = dy / zoom;
1573     sp_selection_move_relative(selection, zdx, zdy);
1575     if (dx == 0) {
1576         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1577                                _("Move vertically by pixels"));
1578     } else if (dy == 0) {
1579         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1580                                _("Move horizontally by pixels"));
1581     } else {
1582         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1583                          _("Move"));
1584     }
1587 namespace {
1589 template <typename D>
1590 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1591                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1593 template <typename D>
1594 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1595                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1597 struct Forward {
1598     typedef SPObject *Iterator;
1600     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1601     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1602     static void dispose(Iterator /*i*/) {}
1604     static SPObject *object(Iterator i) { return i; }
1605     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1606 };
1608 struct Reverse {
1609     typedef GSList *Iterator;
1611     static Iterator children(SPObject *o) {
1612         return make_list(o->firstChild(), NULL);
1613     }
1614     static Iterator siblings_after(SPObject *o) {
1615         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1616     }
1617     static void dispose(Iterator i) {
1618         g_slist_free(i);
1619     }
1621     static SPObject *object(Iterator i) {
1622         return reinterpret_cast<SPObject *>(i->data);
1623     }
1624     static Iterator next(Iterator i) { return i->next; }
1626 private:
1627     static GSList *make_list(SPObject *object, SPObject *limit) {
1628         GSList *list=NULL;
1629         while ( object != limit ) {
1630             list = g_slist_prepend(list, object);
1631             object = SP_OBJECT_NEXT(object);
1632         }
1633         return list;
1634     }
1635 };
1639 void
1640 sp_selection_item_next(SPDesktop *desktop)
1642     g_return_if_fail(desktop != NULL);
1643     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1645     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1646     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1647     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1648     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1650     SPObject *root;
1651     if (PREFS_SELECTION_ALL != inlayer) {
1652         root = selection->activeContext();
1653     } else {
1654         root = desktop->currentRoot();
1655     }
1657     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1659     if (item) {
1660         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1661         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1662             scroll_to_show_item(desktop, item);
1663         }
1664     }
1667 void
1668 sp_selection_item_prev(SPDesktop *desktop)
1670     SPDocument *document = sp_desktop_document(desktop);
1671     g_return_if_fail(document != NULL);
1672     g_return_if_fail(desktop != NULL);
1673     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1675     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1676     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1677     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1678     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1680     SPObject *root;
1681     if (PREFS_SELECTION_ALL != inlayer) {
1682         root = selection->activeContext();
1683     } else {
1684         root = desktop->currentRoot();
1685     }
1687     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1689     if (item) {
1690         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1691         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1692             scroll_to_show_item(desktop, item);
1693         }
1694     }
1697 void sp_selection_next_patheffect_param(SPDesktop * dt)
1699     if (!dt) return;
1701     Inkscape::Selection *selection = sp_desktop_selection(dt);
1702     if ( selection && !selection->isEmpty() ) {
1703         SPItem *item = selection->singleItem();
1704         if ( item && SP_IS_SHAPE(item)) {
1705             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1706                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1707             } else {
1708                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1709             }
1710         }
1711     }
1714 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1716     if (!dt) return;
1718     Inkscape::Selection *selection = sp_desktop_selection(dt);
1719     if ( selection && !selection->isEmpty() ) {
1720         SPItem *item = selection->singleItem();
1721         if ( item ) {
1722             SPObject *obj = NULL;
1723             if (clip)
1724                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1725             else
1726                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1728             if (obj) {
1729                 // obj is a group object, the children are the actual clippers
1730                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1731                     if ( SP_IS_ITEM(child) ) {
1732                         // If not already in nodecontext, goto it!
1733                         if (!tools_isactive(dt, TOOLS_NODES)) {
1734                             tools_switch(dt, TOOLS_NODES);
1735                         }
1737                         ShapeEditor * shape_editor = dt->event_context->shape_editor;
1738                         // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1739                         shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1740                         shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1741                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1742                         if (np) {
1743                             // take colors from prefs (same as used in outline mode)
1744                             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1745                             np->helperpath_rgba = clip ? 
1746                                 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) : 
1747                                 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1748                             np->helperpath_width = 1.0;
1749                             sp_nodepath_show_helperpath(np, true);
1750                         }
1751                         break; // break out of for loop after 1st encountered item
1752                     }
1753                 }
1754             } else if (clip) {
1755                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1756             } else {
1757                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1758             }
1759         }
1760     }
1764 namespace {
1766 template <typename D>
1767 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1768                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1770     SPObject *current=root;
1771     while (items) {
1772         SPItem *item=SP_ITEM(items->data);
1773         if ( root->isAncestorOf(item) &&
1774              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1775         {
1776             current = item;
1777             break;
1778         }
1779         items = items->next;
1780     }
1782     GSList *path=NULL;
1783     while ( current != root ) {
1784         path = g_slist_prepend(path, current);
1785         current = SP_OBJECT_PARENT(current);
1786     }
1788     SPItem *next;
1789     // first, try from the current object
1790     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1791     g_slist_free(path);
1793     if (!next) { // if we ran out of objects, start over at the root
1794         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1795     }
1797     return next;
1800 template <typename D>
1801 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1802                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1804     typename D::Iterator children;
1805     typename D::Iterator iter;
1807     SPItem *found=NULL;
1809     if (path) {
1810         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1811         g_assert(SP_OBJECT_PARENT(object) == root);
1812         if (desktop->isLayer(object)) {
1813             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1814         }
1815         iter = children = D::siblings_after(object);
1816     } else {
1817         iter = children = D::children(root);
1818     }
1820     while ( iter && !found ) {
1821         SPObject *object=D::object(iter);
1822         if (desktop->isLayer(object)) {
1823             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1824                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1825             }
1826         } else if ( SP_IS_ITEM(object) &&
1827                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1828                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1829                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1830                     !desktop->isLayer(SP_ITEM(object)) )
1831         {
1832             found = SP_ITEM(object);
1833         }
1834         iter = D::next(iter);
1835     }
1837     D::dispose(children);
1839     return found;
1844 /**
1845  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1846  * \a item.
1847  */
1848 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1850     Geom::Rect dbox = desktop->get_display_area();
1851     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1853     if ( sbox && dbox.contains(*sbox) == false ) {
1854         Geom::Point const s_dt = sbox->midpoint();
1855         Geom::Point const s_w = desktop->d2w(s_dt);
1856         Geom::Point const d_dt = dbox.midpoint();
1857         Geom::Point const d_w = desktop->d2w(d_dt);
1858         Geom::Point const moved_w( d_w - s_w );
1859         gint const dx = (gint) moved_w[X];
1860         gint const dy = (gint) moved_w[Y];
1861         desktop->scroll_world(dx, dy);
1862     }
1866 void
1867 sp_selection_clone(SPDesktop *desktop)
1869     if (desktop == NULL)
1870         return;
1872     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1874     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1876     // check if something is selected
1877     if (selection->isEmpty()) {
1878         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1879         return;
1880     }
1882     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1884     selection->clear();
1886     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1887     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1889     GSList *newsel = NULL;
1891     while (reprs) {
1892         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1893         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1895         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1896         clone->setAttribute("x", "0", false);
1897         clone->setAttribute("y", "0", false);
1898         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1899         
1900         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1901         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1903         // add the new clone to the top of the original's parent
1904         parent->appendChild(clone);
1906         newsel = g_slist_prepend(newsel, clone);
1907         reprs = g_slist_remove(reprs, sel_repr);
1908         Inkscape::GC::release(clone);
1909     }
1911     // TRANSLATORS: only translate "string" in "context|string".
1912     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1913     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1914                      Q_("action|Clone"));
1916     selection->setReprList(newsel);
1918     g_slist_free(newsel);
1921 void
1922 sp_selection_relink(SPDesktop *desktop)
1924     if (!desktop)
1925         return;
1927     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1929     if (selection->isEmpty()) {
1930         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1931         return;
1932     }
1934     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1935     const gchar *newid = cm->getFirstObjectID();
1936     if (!newid) {
1937         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1938         return;
1939     }
1940     gchar *newref = g_strdup_printf ("#%s", newid);
1942     // Get a copy of current selection.
1943     bool relinked = false;
1944     for (GSList *items = (GSList *) selection->itemList();
1945          items != NULL;
1946          items = items->next)
1947     {
1948         SPItem *item = (SPItem *) items->data;
1950         if (!SP_IS_USE(item))
1951             continue;
1953         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1954         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1955         relinked = true;
1956     }
1958     g_free(newref);
1960     if (!relinked) {
1961         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1962     } else {
1963         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1964                      _("Relink clone"));
1965     }
1969 void
1970 sp_selection_unlink(SPDesktop *desktop)
1972     if (!desktop)
1973         return;
1975     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1977     if (selection->isEmpty()) {
1978         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1979         return;
1980     }
1982     // Get a copy of current selection.
1983     GSList *new_select = NULL;
1984     bool unlinked = false;
1985     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1986          items != NULL;
1987          items = items->next)
1988     {
1989         SPItem *item = (SPItem *) items->data;
1991         if (SP_IS_TEXT(item)) {
1992             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1994             if (tspan) {
1995                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1996             }
1998             // Set unlink to true, and fall into the next if which
1999             // will include this text item in the new selection
2000             unlinked = true;
2001         }
2003         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2004             // keep the non-use item in the new selection
2005             new_select = g_slist_prepend(new_select, item);
2006             continue;
2007         }
2009         SPItem *unlink;
2010         if (SP_IS_USE(item)) {
2011             unlink = sp_use_unlink(SP_USE(item));
2012         } else /*if (SP_IS_TREF(use))*/ {
2013             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2014         }
2016         unlinked = true;
2017         // Add ungrouped items to the new selection.
2018         new_select = g_slist_prepend(new_select, unlink);
2019     }
2021     if (new_select) { // set new selection
2022         selection->clear();
2023         selection->setList(new_select);
2024         g_slist_free(new_select);
2025     }
2026     if (!unlinked) {
2027         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2028     }
2030     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2031                      _("Unlink clone"));
2034 void
2035 sp_select_clone_original(SPDesktop *desktop)
2037     if (desktop == NULL)
2038         return;
2040     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2042     SPItem *item = selection->singleItem();
2044     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.");
2046     // Check if other than two objects are selected
2047     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2048         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2049         return;
2050     }
2052     SPItem *original = NULL;
2053     if (SP_IS_USE(item)) {
2054         original = sp_use_get_original (SP_USE(item));
2055     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2056         original = sp_offset_get_source (SP_OFFSET(item));
2057     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2058         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2059     } else if (SP_IS_FLOWTEXT(item)) {
2060         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2061     } else { // it's an object that we don't know what to do with
2062         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2063         return;
2064     }
2066     if (!original) {
2067         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2068         return;
2069     }
2071     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2072         if (SP_IS_DEFS (o)) {
2073             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2074             return;
2075         }
2076     }
2078     if (original) {
2079         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2080         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2081         if (highlight) {
2082             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2083             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2084             if ( a && b ) {
2085                 // draw a flashing line between the objects
2086                 SPCurve *curve = new SPCurve();
2087                 curve->moveto(a->midpoint());
2088                 curve->lineto(b->midpoint());
2090                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2091                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2092                 sp_canvas_item_show(canvasitem);
2093                 curve->unref();
2094                 desktop->add_temporary_canvasitem (canvasitem, 1000);
2095             }
2096         }
2098         selection->clear();
2099         selection->set(original);
2100         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2101             scroll_to_show_item(desktop, original);
2102         }
2103     }
2107 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2109     if (desktop == NULL)
2110         return;
2112     SPDocument *doc = sp_desktop_document(desktop);
2113     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2115     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2117     // check if something is selected
2118     if (selection->isEmpty()) {
2119         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2120         return;
2121     }
2123     sp_document_ensure_up_to_date(doc);
2124     Geom::OptRect r = selection->bounds();
2125     boost::optional<Geom::Point> c = selection->center();
2126     if ( !r || !c ) {
2127         return;
2128     }
2130     // calculate the transform to be applied to objects to move them to 0,0
2131     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2132     move_p[Geom::Y] = -move_p[Geom::Y];
2133     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2135     GSList *items = g_slist_copy((GSList *) selection->itemList());
2137     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2139     // bottommost object, after sorting
2140     SPObject *parent = SP_OBJECT_PARENT (items->data);
2142     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2144     // remember the position of the first item
2145     gint pos = SP_OBJECT_REPR (items->data)->position();
2146     (void)pos; // TODO check why this was remembered
2148     // create a list of duplicates
2149     GSList *repr_copies = NULL;
2150     for (GSList *i = items; i != NULL; i = i->next) {
2151         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2152         repr_copies = g_slist_prepend (repr_copies, dup);
2153     }
2155     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2157     if (apply) {
2158         // delete objects so that their clones don't get alerted; this object will be restored shortly
2159         for (GSList *i = items; i != NULL; i = i->next) {
2160             SPObject *item = SP_OBJECT (i->data);
2161             item->deleteObject (false);
2162         }
2163     }
2165     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2166     // without disturbing clones.
2167     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2168     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2169     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2170     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2172     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2173                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2174                                                                               Geom::Point(r->min()[Geom::X],
2175                                                                                           r->max()[Geom::Y]))))
2176                                              * parent_transform.inverse() ),
2177                                            parent_transform * move);
2178     (void)mark_id;
2180     // restore compensation setting
2181     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2184     g_slist_free (items);
2186     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2187                       _("Objects to marker"));
2190 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2191     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2192         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2193             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2194         }
2195     } else {
2196         sp_item_convert_item_to_guides(item);
2198         if (deleteitem) {
2199             SP_OBJECT(item)->deleteObject(true);
2200         }
2201     }
2204 void sp_selection_to_guides(SPDesktop *desktop)
2206     if (desktop == NULL)
2207         return;
2209     SPDocument *doc = sp_desktop_document(desktop);
2210     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2211     // we need to copy the list because it gets reset when objects are deleted
2212     GSList *items = g_slist_copy((GSList *) selection->itemList());
2214     if (!items) {
2215         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2216         return;
2217     }
2218     
2219     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2220     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2221     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2223     for (GSList const *i = items; i != NULL; i = i->next) {
2224         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2225     }
2227     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2230 void
2231 sp_selection_tile(SPDesktop *desktop, bool apply)
2233     if (desktop == NULL)
2234         return;
2236     SPDocument *doc = sp_desktop_document(desktop);
2237     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2239     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2241     // check if something is selected
2242     if (selection->isEmpty()) {
2243         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2244         return;
2245     }
2247     sp_document_ensure_up_to_date(doc);
2248     Geom::OptRect r = selection->bounds();
2249     if ( !r ) {
2250         return;
2251     }
2253     // calculate the transform to be applied to objects to move them to 0,0
2254     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point (0, r->dimensions()[Geom::Y]));
2255     move_p[Geom::Y] = -move_p[Geom::Y];
2256     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2258     GSList *items = g_slist_copy((GSList *) selection->itemList());
2260     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2262     // bottommost object, after sorting
2263     SPObject *parent = SP_OBJECT_PARENT (items->data);
2265     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2267     // remember the position of the first item
2268     gint pos = SP_OBJECT_REPR (items->data)->position();
2270     // create a list of duplicates
2271     GSList *repr_copies = NULL;
2272     for (GSList *i = items; i != NULL; i = i->next) {
2273         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2274         repr_copies = g_slist_prepend (repr_copies, dup);
2275     }
2276     // restore the z-order after prepends
2277     repr_copies = g_slist_reverse (repr_copies);
2279     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2281     if (apply) {
2282         // delete objects so that their clones don't get alerted; this object will be restored shortly
2283         for (GSList *i = items; i != NULL; i = i->next) {
2284             SPObject *item = SP_OBJECT (i->data);
2285             item->deleteObject (false);
2286         }
2287     }
2289     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2290     // without disturbing clones.
2291     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2292     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2293     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2294     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2296     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2297                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2298                                                                                             r->max()[Geom::Y]))))
2299                                          * to_2geom(parent_transform.inverse()) ),
2300                                        parent_transform * move);
2302     // restore compensation setting
2303     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2305     if (apply) {
2306         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2307         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2309         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2310         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2312         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2313         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2314         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2315         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2317         // restore parent and position
2318         SP_OBJECT_REPR (parent)->appendChild(rect);
2319         rect->setPosition(pos > 0 ? pos : 0);
2320         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2322         Inkscape::GC::release(rect);
2324         selection->clear();
2325         selection->set(rectangle);
2326     }
2328     g_slist_free (items);
2330     sp_document_done (doc, SP_VERB_EDIT_TILE,
2331                       _("Objects to pattern"));
2334 void
2335 sp_selection_untile(SPDesktop *desktop)
2337     if (desktop == NULL)
2338         return;
2340     SPDocument *doc = sp_desktop_document(desktop);
2341     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2343     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2345     // check if something is selected
2346     if (selection->isEmpty()) {
2347         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2348         return;
2349     }
2351     GSList *new_select = NULL;
2353     bool did = false;
2355     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2356          items != NULL;
2357          items = items->next) {
2359         SPItem *item = (SPItem *) items->data;
2361         SPStyle *style = SP_OBJECT_STYLE (item);
2363         if (!style || !style->fill.isPaintserver())
2364             continue;
2366         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2368         if (!SP_IS_PATTERN(server))
2369             continue;
2371         did = true;
2373         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2375         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform (SP_PATTERN (server)));
2376         pat_transform *= item->transform;
2378         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2379             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2380             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2382            // FIXME: relink clones to the new canvas objects
2383            // use SPObject::setid when mental finishes it to steal ids of
2385             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2386             sp_document_ensure_up_to_date (doc);
2388             Geom::Matrix transform( i->transform * pat_transform );
2389             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2391             new_select = g_slist_prepend(new_select, i);
2392         }
2394         SPCSSAttr *css = sp_repr_css_attr_new ();
2395         sp_repr_css_set_property (css, "fill", "none");
2396         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2397     }
2399     if (!did) {
2400         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2401     } else {
2402         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2403                          _("Pattern to objects"));
2404         selection->setList(new_select);
2405     }
2408 void
2409 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2411     if (selection->isEmpty()) {
2412         return;
2413     }
2415     GSList const *reprlst = selection->reprList();
2416     bool filename_search = TRUE;
2417     bool xdpi_search = TRUE;
2418     bool ydpi_search = TRUE;
2420     for(; reprlst != NULL &&
2421             filename_search &&
2422             xdpi_search &&
2423             ydpi_search;
2424         reprlst = reprlst->next) {
2425         gchar const *dpi_string;
2426         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2428         if (filename_search) {
2429             *filename = repr->attribute("inkscape:export-filename");
2430             if (*filename != NULL)
2431                 filename_search = FALSE;
2432         }
2434         if (xdpi_search) {
2435             dpi_string = NULL;
2436             dpi_string = repr->attribute("inkscape:export-xdpi");
2437             if (dpi_string != NULL) {
2438                 *xdpi = atof(dpi_string);
2439                 xdpi_search = FALSE;
2440             }
2441         }
2443         if (ydpi_search) {
2444             dpi_string = NULL;
2445             dpi_string = repr->attribute("inkscape:export-ydpi");
2446             if (dpi_string != NULL) {
2447                 *ydpi = atof(dpi_string);
2448                 ydpi_search = FALSE;
2449             }
2450         }
2451     }
2454 void
2455 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2457     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2458     gchar const *dpi_string;
2460     *filename = repr->attribute("inkscape:export-filename");
2462     dpi_string = NULL;
2463     dpi_string = repr->attribute("inkscape:export-xdpi");
2464     if (dpi_string != NULL) {
2465         *xdpi = atof(dpi_string);
2466     }
2468     dpi_string = NULL;
2469     dpi_string = repr->attribute("inkscape:export-ydpi");
2470     if (dpi_string != NULL) {
2471         *ydpi = atof(dpi_string);
2472     }
2475 void
2476 sp_selection_create_bitmap_copy (SPDesktop *desktop)
2478     if (desktop == NULL)
2479         return;
2481     SPDocument *document = sp_desktop_document(desktop);
2482     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2484     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2486     // check if something is selected
2487     if (selection->isEmpty()) {
2488         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2489         return;
2490     }
2492     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2493     // set "busy" cursor
2494     desktop->setWaitingCursor();
2496     // Get the bounding box of the selection
2497     NRRect bbox;
2498     sp_document_ensure_up_to_date (document);
2499     selection->bounds(&bbox);
2500     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2501         desktop->clearWaitingCursor();
2502         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2503     }
2505     // List of the items to show; all others will be hidden
2506     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2508     // Sort items so that the topmost comes last
2509     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2511     // Generate a random value from the current time (you may create bitmap from the same object(s)
2512     // multiple times, and this is done so that they don't clash)
2513     GTimeVal cu;
2514     g_get_current_time (&cu);
2515     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2517     // Create the filename
2518     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2519     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2520     // digits, and a few other chars, with "_"
2521     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2523     // Build the complete path by adding document base dir, if set, otherwise home dir
2524     gchar * directory = NULL;
2525     if (SP_DOCUMENT_URI(document)) {
2526         directory = g_dirname(SP_DOCUMENT_URI(document));
2527     }
2528     if (directory == NULL) {
2529         directory = homedir_path(NULL);
2530     }
2531     gchar *filepath = g_build_filename (directory, filename, NULL);
2533     //g_print ("%s\n", filepath);
2535     // Remember parent and z-order of the topmost one
2536     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2537     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2538     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2540     // Calculate resolution
2541     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2542     double res;
2543     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2544     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2545     if (0 < prefs_res) {
2546         // If it's given explicitly in prefs, take it
2547         res = prefs_res;
2548     } else if (0 < prefs_min) {
2549         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2550         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2551     } else {
2552         float hint_xdpi = 0, hint_ydpi = 0;
2553         char const *hint_filename;
2554         // take resolution hint from the selected objects
2555         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2556         if (hint_xdpi != 0) {
2557             res = hint_xdpi;
2558         } else {
2559             // take resolution hint from the document
2560             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2561             if (hint_xdpi != 0) {
2562                 res = hint_xdpi;
2563             } else {
2564                 // if all else fails, take the default 90 dpi
2565                 res = PX_PER_IN;
2566             }
2567         }
2568     }
2570     // The width and height of the bitmap in pixels
2571     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2572     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2574     // Find out if we have to run an external filter
2575     gchar const *run = NULL;
2576     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2577     if (!filter.empty()) {
2578         // filter command is given;
2579         // see if we have a parameter to pass to it
2580         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2581         if (!param1.empty()) {
2582             if (param1[param1.length() - 1] == '%') {
2583                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2584                 gchar p1[256];
2585                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1.data(), NULL) * MAX(width, height) / 100));
2586                 // the first param is always the image filename, the second is param1
2587                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, p1);
2588             } else {
2589                 // otherwise pass the param1 unchanged
2590                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, param1.data());
2591             }
2592         } else {
2593             // run without extra parameter
2594             run = g_strdup_printf ("%s \"%s\"", filter.data(), filepath);
2595         }
2596     }
2598     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2599     Geom::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2600     Geom::Matrix t;
2602     double shift_x = bbox.x0;
2603     double shift_y = bbox.y1;
2604     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2605         shift_x = round (shift_x);
2606         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2607     }
2608     t = Geom::Scale(1, -1) * Geom::Translate (shift_x, shift_y) * eek.inverse();
2610     // Do the export
2611     sp_export_png_file(document, filepath,
2612                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2613                    width, height, res, res,
2614                    (guint32) 0xffffff00,
2615                    NULL, NULL,
2616                    true,  /*bool force_overwrite,*/
2617                    items);
2619     g_slist_free (items);
2621     // Run filter, if any
2622     if (run) {
2623         g_print ("Running external filter: %s\n", run);
2624         int retval;
2625         retval = system (run);
2626     }
2628     // Import the image back
2629     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2630     if (pb) {
2631         // Create the repr for the image
2632         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2633         repr->setAttribute("xlink:href", filename);
2634         repr->setAttribute("sodipodi:absref", filepath);
2635         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2636             sp_repr_set_svg_double(repr, "width", width);
2637             sp_repr_set_svg_double(repr, "height", height);
2638         } else {
2639             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2640             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2641         }
2643         // Write transform
2644         gchar *c=sp_svg_transform_write(t);
2645         repr->setAttribute("transform", c);
2646         g_free(c);
2648         // add the new repr to the parent
2649         parent->appendChild(repr);
2651         // move to the saved position
2652         repr->setPosition(pos > 0 ? pos + 1 : 1);
2654         // Set selection to the new image
2655         selection->clear();
2656         selection->add(repr);
2658         // Clean up
2659         Inkscape::GC::release(repr);
2660         gdk_pixbuf_unref (pb);
2662         // Complete undoable transaction
2663         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2664                           _("Create bitmap"));
2665     }
2667     desktop->clearWaitingCursor();
2669     g_free (filename);
2670     g_free (filepath);
2673 /**
2674  * \brief Creates a mask or clipPath from selection
2675  * Two different modes:
2676  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2677  *       and is applied to current layer
2678  *  otherwise, topmost object is used as mask for other objects
2679  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2680  *
2681  */
2682 void
2683 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2685     if (desktop == NULL)
2686         return;
2688     SPDocument *doc = sp_desktop_document(desktop);
2689     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2691     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2693     // check if something is selected
2694     bool is_empty = selection->isEmpty();
2695     if ( apply_to_layer && is_empty) {
2696         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2697         return;
2698     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2699         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2700         return;
2701     }
2703     // FIXME: temporary patch to prevent crash!
2704     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2705     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2706     if (clone_with_original) {
2707         return; // in this version, you cannot clip/mask an object with its own clone
2708     }
2709     // /END FIXME
2711     sp_document_ensure_up_to_date(doc);
2713     GSList *items = g_slist_copy((GSList *) selection->itemList());
2715     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2717     // create a list of duplicates
2718     GSList *mask_items = NULL;
2719     GSList *apply_to_items = NULL;
2720     GSList *items_to_delete = NULL;
2721     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2722     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2723     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2725     if (apply_to_layer) {
2726         // all selected items are used for mask, which is applied to a layer
2727         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2729         for (GSList *i = items; i != NULL; i = i->next) {
2730             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2731             mask_items = g_slist_prepend (mask_items, dup);
2733             if (remove_original) {
2734                 SPObject *item = SP_OBJECT (i->data);
2735                 items_to_delete = g_slist_prepend (items_to_delete, item);
2736             }
2737         }
2738     } else if (!topmost) {
2739         // topmost item is used as a mask, which is applied to other items in a selection
2740         GSList *i = items;
2741         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2742         mask_items = g_slist_prepend (mask_items, dup);
2744         if (remove_original) {
2745             SPObject *item = SP_OBJECT (i->data);
2746             items_to_delete = g_slist_prepend (items_to_delete, item);
2747         }
2749         for (i = i->next; i != NULL; i = i->next) {
2750             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2751         }
2752     } else {
2753         GSList *i = NULL;
2754         for (i = items; NULL != i->next; i = i->next) {
2755             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2756         }
2758         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2759         mask_items = g_slist_prepend (mask_items, dup);
2761         if (remove_original) {
2762             SPObject *item = SP_OBJECT (i->data);
2763             items_to_delete = g_slist_prepend (items_to_delete, item);
2764         }
2765     }
2767     g_slist_free (items);
2768     items = NULL;
2770     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2771     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2772         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2773         // inverted object transform should be applied to a mask object,
2774         // as mask is calculated in user space (after applying transform)
2775         Geom::Matrix maskTransform (item->transform.inverse());
2777         GSList *mask_items_dup = NULL;
2778         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2779             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2780             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2781         }
2783         gchar const *mask_id = NULL;
2784         if (apply_clip_path) {
2785             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2786         } else {
2787             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2788         }
2790         g_slist_free (mask_items_dup);
2791         mask_items_dup = NULL;
2793         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2794     }
2796     g_slist_free (mask_items);
2797     g_slist_free (apply_to_items);
2799     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2800         SPObject *item = SP_OBJECT (i->data);
2801         item->deleteObject (false);
2802     }
2803     g_slist_free (items_to_delete);
2805     if (apply_clip_path)
2806         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2807     else
2808         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2811 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2812     if (desktop == NULL)
2813         return;
2815     SPDocument *doc = sp_desktop_document(desktop);
2816     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2817     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2819     // check if something is selected
2820     if (selection->isEmpty()) {
2821         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2822         return;
2823     }
2825     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2826     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2827     sp_document_ensure_up_to_date(doc);
2829     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2830     std::map<SPObject*,SPItem*> referenced_objects; 
2831     // SPObject* refers to a group containing the clipped path or mask itself, 
2832     // whereas SPItem* refers to the item being clipped or masked
2833     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2834         if (remove_original) {
2835             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2836             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2837             Inkscape::URIReference *uri_ref = NULL;
2839             if (apply_clip_path) {
2840                 uri_ref = item->clip_ref;
2841             } else {
2842                 uri_ref = item->mask_ref;
2843             }
2845             // collect distinct mask object (and associate with item to apply transform)
2846             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2847                 referenced_objects[uri_ref->getObject()] = item;
2848             }
2849         }
2851         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2852     }
2854     // restore mask objects into a document
2855     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2856         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2857         GSList *items_to_move = NULL;
2858         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2859             // Collect all clipped paths and masks within a single group 
2860             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2861             items_to_move = g_slist_prepend (items_to_move, copy);
2862         }
2864         if (!obj->isReferenced()) {
2865             // delete from defs if no other object references this mask
2866             obj->deleteObject(false);
2867         }
2869         // remember parent and position of the item to which the clippath/mask was applied
2870         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2871         gint pos = SP_OBJECT_REPR((*it).second)->position();
2873         // Iterate through all clipped paths / masks
2874         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2875             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2877             // insert into parent, restore pos
2878             parent->appendChild(repr);
2879             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2881             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2882             selection->add(repr);
2884             // transform mask, so it is moved the same spot where mask was applied
2885             Geom::Matrix transform (mask_item->transform);
2886             transform *= (*it).second->transform;
2887             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2888         }
2890         g_slist_free (items_to_move);
2891     }
2893     if (apply_clip_path)
2894         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2895     else
2896         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2899 /**
2900  * Returns true if an undoable change should be recorded.
2901  */
2902 bool
2903 fit_canvas_to_selection(SPDesktop *desktop)
2905     g_return_val_if_fail(desktop != NULL, false);
2906     SPDocument *doc = sp_desktop_document(desktop);
2908     g_return_val_if_fail(doc != NULL, false);
2909     g_return_val_if_fail(desktop->selection != NULL, false);
2911     if (desktop->selection->isEmpty()) {
2912         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2913         return false;
2914     }
2915     Geom::OptRect const bbox(desktop->selection->bounds());
2916     if (bbox) {
2917         doc->fitToRect(*bbox);
2918         return true;
2919     } else {
2920         return false;
2921     }
2924 /**
2925  * Fit canvas to the bounding box of the selection, as an undoable action.
2926  */
2927 void
2928 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2930     if (fit_canvas_to_selection(desktop)) {
2931         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2932                          _("Fit Page to Selection"));
2933     }
2936 bool
2937 fit_canvas_to_drawing(SPDocument *doc)
2939     g_return_val_if_fail(doc != NULL, false);
2941     sp_document_ensure_up_to_date(doc);
2942     SPItem const *const root = SP_ITEM(doc->root);
2943     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2944     if (bbox) {
2945         doc->fitToRect(*bbox);
2946         return true;
2947     } else {
2948         return false;
2949     }
2952 void
2953 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2955     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2956         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2957                          _("Fit Page to Drawing"));
2958     }
2961 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2962     g_return_if_fail(desktop != NULL);
2963     SPDocument *doc = sp_desktop_document(desktop);
2965     g_return_if_fail(doc != NULL);
2966     g_return_if_fail(desktop->selection != NULL);
2968     bool const changed = ( desktop->selection->isEmpty()
2969                            ? fit_canvas_to_drawing(doc)
2970                            : fit_canvas_to_selection(desktop) );
2971     if (changed) {
2972         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2973                          _("Fit Page to Selection or Drawing"));
2974     }
2975 };
2977 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2978     // don't operate on layers
2979     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2980         f(SP_ITEM(root), desktop);
2981     }
2982     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2983         //don't recurse into locked layers
2984         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2985             itemtree_map(f, iter, desktop);
2986         }
2987     }
2990 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2991     if (item->isLocked()) {
2992         item->setLocked(FALSE);
2993     }
2996 static void unhide(SPItem *item, SPDesktop *desktop) {
2997     if (desktop->itemIsHidden(item)) {
2998         item->setExplicitlyHidden(FALSE);
2999     }
3002 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3003     if (!dt) return;
3005     SPObject *root;
3006     if (layer_only) {
3007         root = dt->currentLayer();
3008     } else {
3009         root = dt->currentRoot();
3010     }
3012     itemtree_map(f, root, dt);
3015 void unlock_all(SPDesktop *dt) {
3016     process_all(&unlock, dt, true);
3019 void unlock_all_in_all_layers(SPDesktop *dt) {
3020     process_all(&unlock, dt, false);
3023 void unhide_all(SPDesktop *dt) {
3024     process_all(&unhide, dt, true);
3027 void unhide_all_in_all_layers(SPDesktop *dt) {
3028     process_all(&unhide, dt, false);
3032 /*
3033   Local Variables:
3034   mode:c++
3035   c-file-style:"stroustrup"
3036   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3037   indent-tabs-mode:nil
3038   fill-column:99
3039   End:
3040 */
3041 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :