Code

Add option to treat grups as single objects when converting to guides.
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "inkscape.h"
29 #include "desktop.h"
30 #include "desktop-style.h"
31 #include "selection.h"
32 #include "tools-switch.h"
33 #include "desktop-handles.h"
34 #include "message-stack.h"
35 #include "sp-item-transform.h"
36 #include "marker.h"
37 #include "sp-use.h"
38 #include "sp-textpath.h"
39 #include "sp-tspan.h"
40 #include "sp-tref.h"
41 #include "sp-flowtext.h"
42 #include "sp-flowregion.h"
43 #include "text-editing.h"
44 #include "text-context.h"
45 #include "connector-context.h"
46 #include "sp-path.h"
47 #include "sp-conn-end.h"
48 #include "dropper-context.h"
49 #include <glibmm/i18n.h>
50 #include "libnr/nr-matrix-rotate-ops.h"
51 #include "libnr/nr-matrix-translate-ops.h"
52 #include "libnr/nr-rotate-fns.h"
53 #include "libnr/nr-scale-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-translate-matrix-ops.h"
56 #include "libnr/nr-translate-scale-ops.h"
57 #include "xml/repr.h"
58 #include "style.h"
59 #include "document-private.h"
60 #include "sp-gradient.h"
61 #include "sp-gradient-reference.h"
62 #include "sp-linear-gradient-fns.h"
63 #include "sp-pattern.h"
64 #include "sp-radial-gradient-fns.h"
65 #include "sp-namedview.h"
66 #include "prefs-utils.h"
67 #include "sp-offset.h"
68 #include "sp-clippath.h"
69 #include "sp-mask.h"
70 #include "file.h"
71 #include "helper/png-write.h"
72 #include "layer-fns.h"
73 #include "context-fns.h"
74 #include <map>
75 #include <cstring>
76 #include <string>
77 #include "helper/units.h"
78 #include "sp-item.h"
79 #include "box3d.h"
80 #include "unit-constants.h"
81 #include "xml/simple-document.h"
82 #include "sp-filter-reference.h"
83 #include "gradient-drag.h"
84 #include "uri-references.h"
85 #include "live_effects/lpeobject.h"
86 #include "live_effects/parameter/path.h"
87 #include "libnr/nr-convert2geom.h"
89 // For clippath editing
90 #include "tools-switch.h"
91 #include "shape-editor.h"
92 #include "node-context.h"
93 #include "nodepath.h"
95 using NR::X;
96 using NR::Y;
98 /* fixme: find a better place */
99 Inkscape::XML::Document *clipboard_document = NULL;
100 GSList *clipboard = NULL;
101 GSList *defs_clipboard = NULL;
102 SPCSSAttr *style_clipboard = NULL;
103 NR::Maybe<NR::Rect> size_clipboard;
105 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc);
107 /**
108  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
109  * then prepends the copy to 'clip'.
110  */
111 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
113     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
115     // copy complete inherited style
116     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
117     sp_repr_css_set(copy, css, "style");
118     sp_repr_css_attr_unref(css);
120     // write the complete accumulated transform passed to us
121     // (we're dealing with unattached repr, so we write to its attr
122     // instead of using sp_item_set_transform)
123     gchar *affinestr=sp_svg_transform_write(full_t);
124     copy->setAttribute("transform", affinestr);
125     g_free(affinestr);
127     *clip = g_slist_prepend(*clip, copy);
130 void sp_selection_copy_impl (GSList const *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
133     // Copy stuff referenced by all items to defs_clip:
134     if (defs_clip) {
135         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
136             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
137         }
138         *defs_clip = g_slist_reverse(*defs_clip);
139     }
141     // Store style:
142     if (style_clip) {
143         SPItem *item = SP_ITEM (items->data); // take from the first selected item
144         *style_clip = take_style_from_item (item);
145     }
147     if (clip) {
148         // Sort items:
149         GSList *sorted_items = g_slist_copy ((GSList *) items);
150         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
152         // Copy item reprs:
153         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
154             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
155         }
157         *clip = g_slist_reverse(*clip);
158         g_slist_free ((GSList *) sorted_items);
159     }
162 /**
163  * Add gradients/patterns/markers referenced by copied objects to defs.
164  * Iterates through 'defs_clip', and for each item it adds the data
165  * repr into the global defs.
166  */
167 void
168 paste_defs (GSList **defs_clip, SPDocument *doc)
170     if (!defs_clip)
171         return;
173     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
174         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
175         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
176         gchar const *id = repr->attribute("id");
177         if (!id || !doc->getObjectById(id)) {
178             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
179             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
180             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
181             Inkscape::GC::release(copy);
182         }
183     }
186 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
188     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
189     paste_defs (defs_clip, doc);
191     GSList *copied = NULL;
192     // add objects to document
193     for (GSList *l = *clip; l != NULL; l = l->next) {
194         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
195         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
197         // premultiply the item transform by the accumulated parent transform in the paste layer
198         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
199         if (!local.test_identity()) {
200             gchar const *t_str = copy->attribute("transform");
201             NR::Matrix item_t (NR::identity());
202             if (t_str)
203                 sp_svg_transform_read(t_str, &item_t);
204             item_t *= local.inverse();
205             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
206             gchar *affinestr=sp_svg_transform_write(item_t);
207             copy->setAttribute("transform", affinestr);
208             g_free(affinestr);
209         }
211         parent->appendChildRepr(copy);
212         copied = g_slist_prepend(copied, copy);
213         Inkscape::GC::release(copy);
214     }
215     return copied;
218 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
220     for (GSList const *i = items ; i ; i = i->next ) {
221         sp_object_ref((SPObject *)i->data, NULL);
222     }
223     for (GSList const *i = items; i != NULL; i = i->next) {
224         SPItem *item = (SPItem *) i->data;
225         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
226         sp_object_unref((SPObject *)item, NULL);
227     }
231 void sp_selection_delete()
233     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
234     if (desktop == NULL) {
235         return;
236     }
238     if (tools_isactive (desktop, TOOLS_TEXT))
239         if (sp_text_delete_selection(desktop->event_context)) {
240             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
241                              _("Delete text"));
242             return;
243         }
245     Inkscape::Selection *selection = sp_desktop_selection(desktop);
247     // check if something is selected
248     if (selection->isEmpty()) {
249         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
250         return;
251     }
253     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
254     selection->clear();
255     sp_selection_delete_impl (selected);
256     g_slist_free ((GSList *) selected);
258     /* a tool may have set up private information in it's selection context
259      * that depends on desktop items.  I think the only sane way to deal with
260      * this currently is to reset the current tool, which will reset it's
261      * associated selection context.  For example: deleting an object
262      * while moving it around the canvas.
263      */
264     tools_switch ( desktop, tools_active ( desktop ) );
266     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
267                      _("Delete"));
270 /* fixme: sequencing */
271 void sp_selection_duplicate()
273     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
274     if (desktop == NULL)
275         return;
277     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
278     Inkscape::Selection *selection = sp_desktop_selection(desktop);
280     // check if something is selected
281     if (selection->isEmpty()) {
282         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
283         return;
284     }
286     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
288     selection->clear();
290     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
291     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
293     GSList *newsel = NULL;
295     while (reprs) {
296         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
297         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
299         parent->appendChild(copy);
301         newsel = g_slist_prepend(newsel, copy);
302         reprs = g_slist_remove(reprs, reprs->data);
303         Inkscape::GC::release(copy);
304     }
306     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
307                      _("Duplicate"));
309     selection->setReprList(newsel);
311     g_slist_free(newsel);
314 void sp_edit_clear_all()
316     SPDesktop *dt = SP_ACTIVE_DESKTOP;
317     if (!dt)
318         return;
320     SPDocument *doc = sp_desktop_document(dt);
321     sp_desktop_selection(dt)->clear();
323     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
324     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
326     while (items) {
327         SP_OBJECT (items->data)->deleteObject();
328         items = g_slist_remove(items, items->data);
329     }
331     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
332                      _("Delete all"));
335 GSList *
336 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
338     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
339         if (SP_IS_ITEM(child) &&
340             !desktop->isLayer(SP_ITEM(child)) &&
341             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
342             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
343             (!exclude || !g_slist_find ((GSList *) exclude, child))
344             )
345         {
346             list = g_slist_prepend (list, SP_ITEM(child));
347         }
349         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
350             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
351         }
352     }
354     return list;
357 void sp_edit_select_all_full (bool force_all_layers, bool invert)
359     SPDesktop *dt = SP_ACTIVE_DESKTOP;
360     if (!dt)
361         return;
363     Inkscape::Selection *selection = sp_desktop_selection(dt);
365     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
367     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
368     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
369     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
371     GSList *items = NULL;
373     GSList const *exclude = NULL;
374     if (invert) {
375         exclude = selection->itemList();
376     }
378     if (force_all_layers)
379         inlayer = PREFS_SELECTION_ALL;
381     switch (inlayer) {
382         case PREFS_SELECTION_LAYER: {
383         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
384              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
385         return;
387         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
389         for (GSList *i = all_items; i; i = i->next) {
390             SPItem *item = SP_ITEM (i->data);
392             if (item && (!onlysensitive || !item->isLocked())) {
393                 if (!onlyvisible || !dt->itemIsHidden(item)) {
394                     if (!dt->isLayer(item)) {
395                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
396                             items = g_slist_prepend (items, item); // leave it in the list
397                         }
398                     }
399                 }
400             }
401         }
403         g_slist_free (all_items);
404             break;
405         }
406         case PREFS_SELECTION_LAYER_RECURSIVE: {
407             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
408             break;
409         }
410         default: {
411         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
412             break;
413     }
414     }
416     selection->setList (items);
418     if (items) {
419         g_slist_free (items);
420     }
423 void sp_edit_select_all ()
425     sp_edit_select_all_full (false, false);
428 void sp_edit_select_all_in_all_layers ()
430     sp_edit_select_all_full (true, false);
433 void sp_edit_invert ()
435     sp_edit_select_all_full (false, true);
438 void sp_edit_invert_in_all_layers ()
440     sp_edit_select_all_full (true, true);
443 void sp_selection_group()
445     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
446     if (desktop == NULL)
447         return;
449     SPDocument *doc = sp_desktop_document (desktop);
450     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
452     Inkscape::Selection *selection = sp_desktop_selection(desktop);
454     // Check if something is selected.
455     if (selection->isEmpty()) {
456         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
457         return;
458     }
460     GSList const *l = (GSList *) selection->reprList();
462     GSList *p = g_slist_copy((GSList *) l);
464     selection->clear();
466     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
468     // Remember the position and parent of the topmost object.
469     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
470     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
472     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
474     while (p) {
475         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
477         if (current->parent() == topmost_parent) {
478             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
479             sp_repr_unparent(current);
480             group->appendChild(spnew);
481             Inkscape::GC::release(spnew);
482             topmost --; // only reduce count for those items deleted from topmost_parent
483         } else { // move it to topmost_parent first
484                 GSList *temp_clip = NULL;
486                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
487                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
488                 gchar const *t_str = current->attribute("transform");
489                 NR::Matrix item_t (NR::identity());
490                 if (t_str)
491                     sp_svg_transform_read(t_str, &item_t);
492                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
493                 //FIXME: when moving both clone and original from a transformed group (either by
494                 //grouping into another parent, or by cut/paste) the transform from the original's
495                 //parent becomes embedded into original itself, and this affects its clones. Fix
496                 //this by remembering the transform diffs we write to each item into an array and
497                 //then, if this is clone, looking up its original in that array and pre-multiplying
498                 //it by the inverse of that original's transform diff.
500                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
501                 sp_repr_unparent(current);
503                 // paste into topmost_parent (temporarily)
504                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
505                 if (temp_clip) g_slist_free (temp_clip);
506                 if (copied) { // if success,
507                     // take pasted object (now in topmost_parent)
508                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
509                     // make a copy
510                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
511                     // remove pasted
512                     sp_repr_unparent(in_topmost);
513                     // put its copy into group
514                     group->appendChild(spnew);
515                     Inkscape::GC::release(spnew);
516                     g_slist_free (copied);
517                 }
518         }
519         p = g_slist_remove(p, current);
520     }
522     // Add the new group to the topmost members' parent
523     topmost_parent->appendChild(group);
525     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
526     group->setPosition(topmost + 1);
528     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
529                      _("Group"));
531     selection->set(group);
532     Inkscape::GC::release(group);
535 void sp_selection_ungroup()
537     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
538     if (desktop == NULL)
539         return;
541     Inkscape::Selection *selection = sp_desktop_selection(desktop);
543     if (selection->isEmpty()) {
544         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
545         return;
546     }
548     GSList *items = g_slist_copy((GSList *) selection->itemList());
549     selection->clear();
551     // Get a copy of current selection.
552     GSList *new_select = NULL;
553     bool ungrouped = false;
554     for (GSList *i = items;
555          i != NULL;
556          i = i->next)
557     {
558         SPItem *group = (SPItem *) i->data;
560         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
561         if (!SP_IS_OBJECT(group)) {
562             continue;
563         }
565         /* We do not allow ungrouping <svg> etc. (lauris) */
566         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
567             // keep the non-group item in the new selection
568             selection->add(group);
569             continue;
570         }
572         GSList *children = NULL;
573         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
574         sp_item_group_ungroup(SP_GROUP(group), &children, false);
575         ungrouped = true;
576         // Add ungrouped items to the new selection.
577         new_select = g_slist_concat(new_select, children);
578     }
580     if (new_select) { // Set new selection.
581         selection->addList(new_select);
582         g_slist_free(new_select);
583     }
584     if (!ungrouped) {
585         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
586     }
588     g_slist_free(items);
590     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
591                      _("Ungroup"));
594 static SPGroup *
595 sp_item_list_common_parent_group(GSList const *items)
597     if (!items) {
598         return NULL;
599     }
600     SPObject *parent = SP_OBJECT_PARENT(items->data);
601     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
602     if (!SP_IS_GROUP(parent)) {
603         return NULL;
604     }
605     for (items = items->next; items; items = items->next) {
606         if (SP_OBJECT_PARENT(items->data) != parent) {
607             return NULL;
608         }
609     }
611     return SP_GROUP(parent);
614 /** Finds out the minimum common bbox of the selected items. */
615 static NR::Maybe<NR::Rect>
616 enclose_items(GSList const *items)
618     g_assert(items != NULL);
620     NR::Maybe<NR::Rect> r = NR::Nothing();
621     for (GSList const *i = items; i; i = i->next) {
622         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
623     }
624     return r;
627 SPObject *
628 prev_sibling(SPObject *child)
630     SPObject *parent = SP_OBJECT_PARENT(child);
631     if (!SP_IS_GROUP(parent)) {
632         return NULL;
633     }
634     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
635         if (i->next == child)
636             return i;
637     }
638     return NULL;
641 void
642 sp_selection_raise()
644     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
645     if (!desktop)
646         return;
648     Inkscape::Selection *selection = sp_desktop_selection(desktop);
650     GSList const *items = (GSList *) selection->itemList();
651     if (!items) {
652         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
653         return;
654     }
656     SPGroup const *group = sp_item_list_common_parent_group(items);
657     if (!group) {
658         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
659         return;
660     }
662     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
664     /* Construct reverse-ordered list of selected children. */
665     GSList *rev = g_slist_copy((GSList *) items);
666     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
668     // Determine the common bbox of the selected items.
669     NR::Maybe<NR::Rect> selected = enclose_items(items);
671     // Iterate over all objects in the selection (starting from top).
672     if (selected) {
673         while (rev) {
674             SPObject *child = SP_OBJECT(rev->data);
675             // for each selected object, find the next sibling
676             for (SPObject *newref = child->next; newref; newref = newref->next) {
677                 // if the sibling is an item AND overlaps our selection,
678                 if (SP_IS_ITEM(newref)) {
679                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
680                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
681                         // AND if it's not one of our selected objects,
682                         if (!g_slist_find((GSList *) items, newref)) {
683                             // move the selected object after that sibling
684                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
685                         }
686                         break;
687                     }
688                 }
689             }
690             rev = g_slist_remove(rev, child);
691         }
692     } else {
693         g_slist_free(rev);
694     }
696     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
697                      _("Raise"));
700 void sp_selection_raise_to_top()
702     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
703     if (desktop == NULL)
704         return;
706     SPDocument *document = sp_desktop_document(desktop);
707     Inkscape::Selection *selection = sp_desktop_selection(desktop);
709     if (selection->isEmpty()) {
710         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
711         return;
712     }
714     GSList const *items = (GSList *) selection->itemList();
716     SPGroup const *group = sp_item_list_common_parent_group(items);
717     if (!group) {
718         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
719         return;
720     }
722     GSList *rl = g_slist_copy((GSList *) selection->reprList());
723     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
725     for (GSList *l = rl; l != NULL; l = l->next) {
726         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
727         repr->setPosition(-1);
728     }
730     g_slist_free(rl);
732     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
733                      _("Raise to top"));
736 void
737 sp_selection_lower()
739     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
740     if (desktop == NULL)
741         return;
743     Inkscape::Selection *selection = sp_desktop_selection(desktop);
745     GSList const *items = (GSList *) selection->itemList();
746     if (!items) {
747         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
748         return;
749     }
751     SPGroup const *group = sp_item_list_common_parent_group(items);
752     if (!group) {
753         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
754         return;
755     }
757     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
759     // Determine the common bbox of the selected items.
760     NR::Maybe<NR::Rect> selected = enclose_items(items);
762     /* Construct direct-ordered list of selected children. */
763     GSList *rev = g_slist_copy((GSList *) items);
764     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
765     rev = g_slist_reverse(rev);
767     // Iterate over all objects in the selection (starting from top).
768     if (selected) {
769         while (rev) {
770             SPObject *child = SP_OBJECT(rev->data);
771             // for each selected object, find the prev sibling
772             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
773                 // if the sibling is an item AND overlaps our selection,
774                 if (SP_IS_ITEM(newref)) {
775                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
776                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
777                         // AND if it's not one of our selected objects,
778                         if (!g_slist_find((GSList *) items, newref)) {
779                             // move the selected object before that sibling
780                             SPObject *put_after = prev_sibling(newref);
781                             if (put_after)
782                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
783                             else
784                                 SP_OBJECT_REPR(child)->setPosition(0);
785                         }
786                         break;
787                     }
788                 }
789             }
790             rev = g_slist_remove(rev, child);
791         }
792     } else {
793         g_slist_free(rev);
794     }
796     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
797                      _("Lower"));
800 void sp_selection_lower_to_bottom()
802     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
803     if (desktop == NULL)
804         return;
806     SPDocument *document = sp_desktop_document(desktop);
807     Inkscape::Selection *selection = sp_desktop_selection(desktop);
809     if (selection->isEmpty()) {
810         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
811         return;
812     }
814     GSList const *items = (GSList *) selection->itemList();
816     SPGroup const *group = sp_item_list_common_parent_group(items);
817     if (!group) {
818         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
819         return;
820     }
822     GSList *rl;
823     rl = g_slist_copy((GSList *) selection->reprList());
824     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
825     rl = g_slist_reverse(rl);
827     for (GSList *l = rl; l != NULL; l = l->next) {
828         gint minpos;
829         SPObject *pp, *pc;
830         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
831         pp = document->getObjectByRepr(sp_repr_parent(repr));
832         minpos = 0;
833         g_assert(SP_IS_GROUP(pp));
834         pc = sp_object_first_child(pp);
835         while (!SP_IS_ITEM(pc)) {
836             minpos += 1;
837             pc = pc->next;
838         }
839         repr->setPosition(minpos);
840     }
842     g_slist_free(rl);
844     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
845                      _("Lower to bottom"));
848 void
849 sp_undo(SPDesktop *desktop, SPDocument *)
851         if (!sp_document_undo(sp_desktop_document(desktop)))
852             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
855 void
856 sp_redo(SPDesktop *desktop, SPDocument *)
858         if (!sp_document_redo(sp_desktop_document(desktop)))
859             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
862 void sp_selection_cut()
864     sp_selection_copy();
865     sp_selection_delete();
868 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
870     SPGradient *ref = gradient;
872     while (ref) {
873         // climb up the refs, copying each one in the chain
874         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
875         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
877         ref = ref->ref->getObject();
878     }
881 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
883     SPPattern *ref = pattern;
885     while (ref) {
886         // climb up the refs, copying each one in the chain
887         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
888         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
890         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
891         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
892             if (!SP_IS_ITEM (child))
893                 continue;
894             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
895         }
897         ref = ref->ref->getObject();
898     }
901 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
903     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
904     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
908 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, GSList const *items, Inkscape::XML::Document* xml_doc)
910     SPItem *path = sp_textpath_get_path_item (tp);
911     if (!path)
912         return;
913     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
914         return;
915     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
916     *defs_clip = g_slist_prepend (*defs_clip, repr);
919 /**
920  * Copies things like patterns, markers, gradients, etc.
921  */
922 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc)
924     SPStyle *style = SP_OBJECT_STYLE (item);
926     if (style && (style->fill.isPaintserver())) {
927         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
928         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
929             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
930         if (SP_IS_PATTERN (server))
931             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
932     }
934     if (style && (style->stroke.isPaintserver())) {
935         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
936         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
937             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
938         if (SP_IS_PATTERN (server))
939             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
940     }
942     // For shapes, copy all of the shape's markers into defs_clip
943     if (SP_IS_SHAPE (item)) {
944         SPShape *shape = SP_SHAPE (item);
945         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
946             if (shape->marker[i]) {
947                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
948             }
949         }
951         // For shapes, also copy liveeffect if applicable
952         if (sp_shape_has_path_effect(shape)) {
953             sp_copy_single (defs_clip, SP_OBJECT(sp_shape_get_livepatheffectobject(shape)), xml_doc);
954         }
955     }
957     // For 3D boxes copy perspectives
958     if (SP_IS_BOX3D(item)) {
959         sp_copy_single (defs_clip, SP_OBJECT(box3d_get_perspective(SP_BOX3D(item))), xml_doc);
960     }
962     if (SP_IS_TEXT_TEXTPATH (item)) {
963         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
964     }
966     if (item->clip_ref->getObject()) {
967         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
968     }
970     if (item->mask_ref->getObject()) {
971         SPObject *mask = item->mask_ref->getObject();
972         sp_copy_single (defs_clip, mask, xml_doc);
973         // recurse into the mask for its gradients etc.
974         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
975             if (SP_IS_ITEM(o))
976                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
977         }
978     }
980     if (style->getFilter()) {
981         SPObject *filter = style->getFilter();
982         if (SP_IS_FILTER(filter)) {
983             sp_copy_single (defs_clip, filter, xml_doc);
984         }
985     }
987     // recurse
988     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
989         if (SP_IS_ITEM(o))
990             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
991     }
994 void
995 sp_set_style_clipboard (SPCSSAttr *css)
997     if (css != NULL) {
998         // clear style clipboard
999         if (style_clipboard) {
1000             sp_repr_css_attr_unref (style_clipboard);
1001             style_clipboard = NULL;
1002         }
1003         //sp_repr_css_print (css);
1004         style_clipboard = css;
1005     }
1008 /**
1009  * \pre item != NULL
1010  */
1011 SPCSSAttr *
1012 take_style_from_item (SPItem *item)
1014     // write the complete cascaded style, context-free
1015     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1016     if (css == NULL)
1017         return NULL;
1019     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1020         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1021         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1022         // If this is a group, merge the style of its topmost (last) child with style
1023         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
1024             if (SP_OBJECT_STYLE (last_element) != NULL) {
1025                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
1026                 if (temp) {
1027                     sp_repr_css_merge (css, temp);
1028                     sp_repr_css_attr_unref (temp);
1029                 }
1030                 break;
1031             }
1032         }
1033     }
1034     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
1035         // do not copy text properties from non-text objects, it's confusing
1036         css = sp_css_attr_unset_text (css);
1037     }
1039     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1040     double ex = NR::expansion(sp_item_i2doc_affine(item));
1041     if (ex != 1.0) {
1042         css = sp_css_attr_scale (css, ex);
1043     }
1045     return css;
1049 void sp_selection_copy()
1051     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1052     if (desktop == NULL)
1053         return;
1055     if (!clipboard_document) {
1056         clipboard_document = new Inkscape::XML::SimpleDocument();
1057     }
1059     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1061     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1062         sp_dropper_context_copy(desktop->event_context);
1063         return; // copied color under cursor, nothing else to do
1064     }
1066     if (desktop->event_context->get_drag() && desktop->event_context->get_drag()->copy()) {
1067         return; // copied selected stop(s), nothing else to do
1068     }
1070     // check if something is selected
1071     if (selection->isEmpty()) {
1072         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1073         return;
1074     }
1076     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1078     // 0. Copy text to system clipboard
1079     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1080     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1081     Glib::ustring text;
1082     if (tools_isactive (desktop, TOOLS_TEXT)) {
1083         text = sp_text_get_selected_text(desktop->event_context);
1084     }
1086     if (text.empty()) {
1087         guint texts = 0;
1088         for (GSList *i = (GSList *) items; i; i = i->next) {
1089             SPItem *item = SP_ITEM (i->data);
1090             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1091                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1092                     text += " ";
1093                 gchar *this_text = sp_te_get_string_multiline (item);
1094                 if (this_text) {
1095                     text += this_text;
1096                     g_free(this_text);
1097                 }
1098                 texts++;
1099             }
1100         }
1101     }
1102     if (!text.empty()) {
1103         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1104         refClipboard->set_text(text);
1105     }
1107     // clear old defs clipboard
1108     while (defs_clipboard) {
1109         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1110         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1111     }
1113     // clear style clipboard
1114     if (style_clipboard) {
1115         sp_repr_css_attr_unref (style_clipboard);
1116         style_clipboard = NULL;
1117     }
1119     //clear main clipboard
1120     while (clipboard) {
1121         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1122         clipboard = g_slist_remove(clipboard, clipboard->data);
1123     }
1125     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1127     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1128         SPStyle *const query = sp_style_new(SP_ACTIVE_DOCUMENT);
1129         if (sp_desktop_query_style_all (desktop, query)) {
1130             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1131             sp_set_style_clipboard (css);
1132         }
1133         sp_style_unref(query);
1134     }
1136     size_clipboard = selection->bounds();
1138     g_slist_free ((GSList *) items);
1142 void sp_selection_copy_lpe_pathparam(Inkscape::LivePathEffect::PathParam * pathparam)
1144     if (pathparam == NULL)
1145         return;
1147     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1148     if (desktop == NULL)
1149         return;
1151     if (!clipboard_document) {
1152         clipboard_document = new Inkscape::XML::SimpleDocument();
1153     }
1155     // clear old defs clipboard
1156     while (defs_clipboard) {
1157         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1158         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1159     }
1161     // clear style clipboard
1162     if (style_clipboard) {
1163         sp_repr_css_attr_unref (style_clipboard);
1164         style_clipboard = NULL;
1165     }
1167     //clear main clipboard
1168     while (clipboard) {
1169         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1170         clipboard = g_slist_remove(clipboard, clipboard->data);
1171     }
1173     // make new path node and put svgd as 'd' attribute
1174     Inkscape::XML::Node *newnode = clipboard_document->createElement("svg:path");
1175     gchar * svgd = pathparam->param_writeSVGValue();
1176     newnode->setAttribute("d", svgd);
1177     g_free(svgd);
1179     clipboard = g_slist_prepend(clipboard, newnode);
1181     Geom::Rect bnds = Geom::bounds_exact(*pathparam);
1182     size_clipboard = from_2geom(bnds);
1186 //____________________________________________________________________________
1188 /** Paste the bitmap in the clipboard if one is in there.
1189         The bitmap is saved to a PNG file then imported into the document
1191         @return true if a bitmap was detected and pasted; false if no bitmap
1192 */
1193 static bool pastedPicFromClipboard()
1195         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1196         SPDocument *doc = SP_ACTIVE_DOCUMENT;
1197         if ( desktop == NULL || doc == NULL)
1198                 return false;
1200         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1201         Glib::RefPtr<Gdk::Pixbuf> pic = refClipboard->wait_for_image();
1203         // Stop if the system clipboard doesn't have a bitmap.
1204         if ( pic == 0 )
1205         {
1206                 return false;
1207         } //if
1208         else
1209         {
1210                 // Write into a file, then import the file into the document.
1211                 // Make a file name based on current time; use the current working dir.
1212                 time_t rawtime;
1213                 char filename[50];
1214                 const char* path;
1216                 time ( &rawtime );
1217                 strftime (filename,50,"pastedpic_%m%d%Y_%H%M%S.png",localtime( &rawtime ));
1218                 path = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1219                 Glib::ustring finalPath = path;
1220                 finalPath.append(G_DIR_SEPARATOR_S).append(filename);
1221                 pic->save( finalPath, "png" );
1222                 file_import(doc, finalPath, NULL);
1224                 // Clear the clipboard so that the bitmap in there won't always over
1225                 // ride the normal inkscape clipboard.This isn't the ideal solution.
1226                 refClipboard->set_text("");
1227                 return true;
1228         } //else
1230         return false;
1231 } //pastedPicFromClipboard
1233 //____________________________________________________________________________
1235 void sp_selection_paste(bool in_place)
1237     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1239     if (desktop == NULL) {
1240         return;
1241     }
1243     SPDocument *document = sp_desktop_document(desktop);
1245     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1246         return;
1247     }
1249     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1251     if (tools_isactive (desktop, TOOLS_TEXT)) {
1252         if (sp_text_paste_inline(desktop->event_context))
1253             return; // pasted from system clipboard into text, nothing else to do
1254     }
1256     // check if something is in the clipboard
1258     // Stop if successfully pasted a clipboard bitmap.
1259     if ( pastedPicFromClipboard() )
1260         return;
1263     if (clipboard == NULL) {
1264         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing in the clipboard."));
1265         return;
1266     }
1268     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1269     // add pasted objects to selection
1270     selection->setReprList((GSList const *) copied);
1271     g_slist_free (copied);
1273     if (!in_place) {
1274         sp_document_ensure_up_to_date(document);
1276         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1277         NR::Point m( desktop->point() );
1278         if (sel_bbox) {
1279             m -= sel_bbox->midpoint();
1280         }
1282         sp_selection_move_relative(selection, m);
1283     }
1285     sp_document_done(document, SP_VERB_EDIT_PASTE, _("Paste"));
1288 void sp_selection_paste_style()
1290     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1291     if (desktop == NULL) return;
1293     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1295     // check if something is in the clipboard
1296     if (style_clipboard == NULL) {
1297         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the style clipboard."));
1298         return;
1299     }
1301     // check if something is selected
1302     if (selection->isEmpty()) {
1303         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1304         return;
1305     }
1307     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1309     sp_desktop_set_style (desktop, style_clipboard);
1311     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1312                      _("Paste style"));
1315 void sp_selection_paste_livepatheffect_impl(SPDocument *doc, SPItem *item, char const *effecturi)
1317     if ( item && SP_IS_SHAPE(item) ) {
1318         SPShape * shape = SP_SHAPE(item);
1320         // create a private LPE object!
1321         SPObject * obj = sp_uri_reference_resolve(doc, effecturi);
1322         if (!obj)
1323             return;
1324         LivePathEffectObject * lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(0);
1325             
1326         sp_shape_set_path_effect(shape, lpeobj);
1328         // set inkscape:original-d for paths. the other shapes don't need this.
1329         if ( SP_IS_PATH(item) ) {
1330             Inkscape::XML::Node *pathrepr = SP_OBJECT_REPR(item);
1331             if ( ! pathrepr->attribute("inkscape:original-d") ) {
1332                 pathrepr->setAttribute("inkscape:original-d", pathrepr->attribute("d"));
1333             }
1334         }
1335     } else if (item && SP_IS_GROUP (item)) {
1336         for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
1337             if (!SP_IS_ITEM (child))
1338                 continue;
1339             sp_selection_paste_livepatheffect_impl (doc, SP_ITEM(child), effecturi);
1340         }
1341     }
1345 void sp_selection_paste_livepatheffect()
1347     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1348     if (desktop == NULL) return;
1350     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1352     // check if something is in the clipboard
1353     if (clipboard == NULL) {
1354         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1355         return;
1356     }
1358     // check if something is selected
1359     if (selection->isEmpty()) {
1360         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste live path effect to."));
1361         return;
1362     }
1364     SPDocument *doc = sp_desktop_document(desktop);
1365     paste_defs (&defs_clipboard, doc);
1367     Inkscape::XML::Node *repr = (Inkscape::XML::Node *) clipboard->data;
1368     char const *effecturi = repr->attribute("inkscape:path-effect");
1369     if (!effecturi) {
1370         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Clipboard does not contain a live path effect."));
1371         return;
1372     }
1374     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1375         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1377         sp_selection_paste_livepatheffect_impl(doc, item, effecturi);
1379     }
1381     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1382                      _("Paste live path effect"));
1386 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1388     if ( item && SP_IS_SHAPE(item) ) {
1389         sp_shape_remove_path_effect(SP_SHAPE(item));
1390    } else if (item && SP_IS_GROUP (item)) {
1391         for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
1392             if (!SP_IS_ITEM (child))
1393                 continue;
1394             sp_selection_remove_livepatheffect_impl (SP_ITEM(child));
1395         }
1396     }
1399 void sp_selection_remove_livepatheffect()
1401     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1402     if (desktop == NULL) return;
1404     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1406     // check if something is selected
1407     if (selection->isEmpty()) {
1408         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1409         return;
1410     }
1412     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1413         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1415         sp_selection_remove_livepatheffect_impl(item);
1417     }
1419     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1420                      _("Remove live path effect"));
1423 void sp_selection_paste_size (bool apply_x, bool apply_y)
1425     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1426     if (desktop == NULL) return;
1428     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1430     // check if something is in the clipboard
1431     if (!size_clipboard) {
1432         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1433         return;
1434     }
1436     // check if something is selected
1437     if (selection->isEmpty()) {
1438         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1439         return;
1440     }
1442     NR::Maybe<NR::Rect> current = selection->bounds();
1443     if ( !current || current->isEmpty() ) {
1444         return;
1445     }
1447     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1448     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1450     sp_selection_scale_relative (selection, current->midpoint(),
1451                                  NR::scale(
1452                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1453                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1455     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1456                      _("Paste size"));
1459 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1461     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1462     if (desktop == NULL) return;
1464     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1466     // check if something is in the clipboard
1467     if ( !size_clipboard ) {
1468         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1469         return;
1470     }
1472     // check if something is selected
1473     if (selection->isEmpty()) {
1474         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1475         return;
1476     }
1478     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1479         SPItem *item = SP_ITEM(l->data);
1481         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1482         if ( !current || current->isEmpty() ) {
1483             continue;
1484         }
1486         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1487         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1489         sp_item_scale_rel (item,
1490                                  NR::scale(
1491                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1492                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1494     }
1496     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1497                      _("Paste size separately"));
1500 void sp_selection_to_next_layer ()
1502     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1504     Inkscape::Selection *selection = sp_desktop_selection(dt);
1506     // check if something is selected
1507     if (selection->isEmpty()) {
1508         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1509         return;
1510     }
1512     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1514     bool no_more = false; // Set to true, if no more layers above
1515     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1516     if (next) {
1517         GSList *temp_clip = NULL;
1518         sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1519         sp_selection_delete_impl (items, false, false);
1520         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1521         GSList *copied;
1522         if(next) {
1523             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1524         } else {
1525             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1526             no_more = true;
1527         }
1528         selection->setReprList((GSList const *) copied);
1529         g_slist_free (copied);
1530         if (temp_clip) g_slist_free (temp_clip);
1531         if (next) dt->setCurrentLayer(next);
1532         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1533                          _("Raise to next layer"));
1534     } else {
1535         no_more = true;
1536     }
1538     if (no_more) {
1539         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1540     }
1542     g_slist_free ((GSList *) items);
1545 void sp_selection_to_prev_layer ()
1547     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1549     Inkscape::Selection *selection = sp_desktop_selection(dt);
1551     // check if something is selected
1552     if (selection->isEmpty()) {
1553         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1554         return;
1555     }
1557     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1559     bool no_more = false; // Set to true, if no more layers below
1560     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1561     if (next) {
1562         GSList *temp_clip = NULL;
1563         sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1564         sp_selection_delete_impl (items, false, false);
1565         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1566         GSList *copied;
1567         if(next) {
1568             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1569         } else {
1570             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1571             no_more = true;
1572         }
1573         selection->setReprList((GSList const *) copied);
1574         g_slist_free (copied);
1575         if (temp_clip) g_slist_free (temp_clip);
1576         if (next) dt->setCurrentLayer(next);
1577         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1578                          _("Lower to previous layer"));
1579     } else {
1580         no_more = true;
1581     }
1583     if (no_more) {
1584         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1585     }
1587     g_slist_free ((GSList *) items);
1590 bool
1591 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1593     bool contains_original = false;
1595     bool is_use = SP_IS_USE(item);
1596     SPItem *item_use = item;
1597     SPItem *item_use_first = item;
1598     while (is_use && item_use && !contains_original)
1599     {
1600         item_use = sp_use_get_original (SP_USE(item_use));
1601         contains_original |= selection->includes(item_use);
1602         if (item_use == item_use_first)
1603             break;
1604         is_use = SP_IS_USE(item_use);
1605     }
1607     // If it's a tref, check whether the object containing the character
1608     // data is part of the selection
1609     if (!contains_original && SP_IS_TREF(item)) {
1610         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1611     }
1613     return contains_original;
1617 bool
1618 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1620     bool clone_with_original = false;
1621     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1622         SPItem *item = SP_ITEM(l->data);
1623         clone_with_original |= selection_contains_original(item, selection);
1624         if (clone_with_original)
1625             break;
1626     }
1627     return clone_with_original;
1631 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1632 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1633 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1634 that case, items are already in the new position, but the repr is in the old, and this function
1635 then simply updates the repr from item->transform.
1636  */
1637 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1639     if (selection->isEmpty())
1640         return;
1642     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1643         SPItem *item = SP_ITEM(l->data);
1645         NR::Point old_center(0,0);
1646         if (set_i2d && item->isCenterSet())
1647             old_center = item->getCenter();
1649 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1650          At the time of writing, this is the only place to re-enable. */
1651         sp_item_update_cns(*item, selection->desktop());
1652 #endif
1654         // we're moving both a clone and its original or any ancestor in clone chain?
1655         bool transform_clone_with_original = selection_contains_original(item, selection);
1656         // ...both a text-on-path and its path?
1657         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)))) ));
1658         // ...both a flowtext and its frame?
1659         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)
1660         // ...both an offset and its source?
1661         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1663         // If we're moving a connector, we want to detach it
1664         // from shapes that aren't part of the selection, but
1665         // leave it attached if they are
1666         if (cc_item_is_connector(item)) {
1667             SPItem *attItem[2];
1668             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1670             for (int n = 0; n < 2; ++n) {
1671                 if (!selection->includes(attItem[n])) {
1672                     sp_conn_end_detach(item, n);
1673                 }
1674             }
1675         }
1677         // "clones are unmoved when original is moved" preference
1678         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1679         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1680         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1682         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1683         // transform of its original and respond to it itself. Without this, a clone is doubly
1684         // transformed, very unintuitive.
1685       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1686       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1687       // Same for linked offset if we are also moving its source: do not move it.
1688         if (transform_textpath_with_path || transform_offset_with_source) {
1689                 // restore item->transform field from the repr, in case it was changed by seltrans
1690             sp_object_read_attr (SP_OBJECT (item), "transform");
1692         } else if (transform_flowtext_with_frame) {
1693             // apply the inverse of the region's transform to the <use> so that the flow remains
1694             // the same (even though the output itself gets transformed)
1695             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1696                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1697                     continue;
1698                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1699                     if (!SP_IS_USE(use)) continue;
1700                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1701                 }
1702             }
1703         } else if (transform_clone_with_original) {
1704             // We are transforming a clone along with its original. The below matrix juggling is
1705             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1706             // transform and its move compensation are both cancelled out.
1708             // restore item->transform field from the repr, in case it was changed by seltrans
1709             sp_object_read_attr (SP_OBJECT (item), "transform");
1711             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1712             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1713             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1714             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1715             NR::Matrix result = t_inv * item->transform * t;
1717             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1718                 // we need to cancel out the move compensation, too
1720                 // find out the clone move, same as in sp_use_move_compensate
1721                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1722                 NR::Matrix clone_move = parent.inverse() * t * parent;
1724                 if (prefs_parallel) {
1725                     NR::Matrix move = result * clone_move * t_inv;
1726                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1728                 } else if (prefs_unmoved) {
1729                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1730                     //    clone_move = NR::identity();
1731                     NR::Matrix move = result * clone_move;
1732                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1733                 }
1735             } else {
1736                 // just apply the result
1737                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1738             }
1740         } else {
1741             if (set_i2d) {
1742                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1743             }
1744             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1745         }
1747         // if we're moving the actual object, not just updating the repr, we can transform the
1748         // center by the same matrix (only necessary for non-translations)
1749         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1750             item->setCenter(old_center * affine);
1751             SP_OBJECT(item)->updateRepr();
1752         }
1753     }
1756 void sp_selection_remove_transform()
1758     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1759     if (desktop == NULL)
1760         return;
1762     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1764     GSList const *l = (GSList *) selection->reprList();
1765     while (l != NULL) {
1766         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1767         l = l->next;
1768     }
1770     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1771                      _("Remove transform"));
1774 void
1775 sp_selection_scale_absolute(Inkscape::Selection *selection,
1776                             double const x0, double const x1,
1777                             double const y0, double const y1)
1779     if (selection->isEmpty())
1780         return;
1782     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1783     if ( !bbox || bbox->isEmpty() ) {
1784         return;
1785     }
1787     NR::translate const p2o(-bbox->min());
1789     NR::scale const newSize(x1 - x0,
1790                             y1 - y0);
1791     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1792     NR::translate const o2n(x0, y0);
1793     NR::Matrix const final( p2o * scale * o2n );
1795     sp_selection_apply_affine(selection, final);
1799 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1801     if (selection->isEmpty())
1802         return;
1804     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1806     if ( !bbox || bbox->isEmpty() ) {
1807         return;
1808     }
1810     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1811     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1812          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1813     {
1814         return;
1815     }
1817     NR::translate const n2d(-align);
1818     NR::translate const d2n(align);
1819     NR::Matrix const final( n2d * scale * d2n );
1820     sp_selection_apply_affine(selection, final);
1823 void
1824 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1826     NR::translate const d2n(center);
1827     NR::translate const n2d(-center);
1828     NR::rotate const rotate(rotate_degrees(angle_degrees));
1829     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1830     sp_selection_apply_affine(selection, final);
1833 void
1834 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1836     NR::translate const d2n(align);
1837     NR::translate const n2d(-align);
1838     NR::Matrix const skew(1, dy,
1839                           dx, 1,
1840                           0, 0);
1841     NR::Matrix const final( n2d * skew * d2n );
1842     sp_selection_apply_affine(selection, final);
1845 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1847     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1850 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1852     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1856 /**
1857  * \brief sp_selection_rotate_90
1858  *
1859  * This function rotates selected objects 90 degrees clockwise.
1860  *
1861  */
1863 void sp_selection_rotate_90_cw()
1865     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1867     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1869     if (selection->isEmpty())
1870         return;
1872     GSList const *l = selection->itemList();
1873     NR::rotate const rot_neg_90(NR::Point(0, -1));
1874     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1875         SPItem *item = SP_ITEM(l2->data);
1876         sp_item_rotate_rel(item, rot_neg_90);
1877     }
1879     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1880                      _("Rotate 90&#176; CW"));
1884 /**
1885  * \brief sp_selection_rotate_90_ccw
1886  *
1887  * This function rotates selected objects 90 degrees counter-clockwise.
1888  *
1889  */
1891 void sp_selection_rotate_90_ccw()
1893     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1895     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1897     if (selection->isEmpty())
1898         return;
1900     GSList const *l = selection->itemList();
1901     NR::rotate const rot_neg_90(NR::Point(0, 1));
1902     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1903         SPItem *item = SP_ITEM(l2->data);
1904         sp_item_rotate_rel(item, rot_neg_90);
1905     }
1907     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1908                      _("Rotate 90&#176; CCW"));
1911 void
1912 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1914     if (selection->isEmpty())
1915         return;
1917     NR::Maybe<NR::Point> center = selection->center();
1918     if (!center) {
1919         return;
1920     }
1922     sp_selection_rotate_relative(selection, *center, angle_degrees);
1924     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1925                            ( ( angle_degrees > 0 )
1926                              ? "selector:rotate:ccw"
1927                              : "selector:rotate:cw" ),
1928                            SP_VERB_CONTEXT_SELECT,
1929                            _("Rotate"));
1932 /**
1933 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1934 */
1935 void
1936 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1938     if (selection->isEmpty())
1939         return;
1941     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1942     NR::Maybe<NR::Point> center = selection->center();
1944     if ( !bbox || !center ) {
1945         return;
1946     }
1948     gdouble const zoom = selection->desktop()->current_zoom();
1949     gdouble const zmove = angle / zoom;
1950     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1952     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1954     sp_selection_rotate_relative(selection, *center, zangle);
1956     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1957                            ( (angle > 0)
1958                              ? "selector:rotate:ccw"
1959                              : "selector:rotate:cw" ),
1960                            SP_VERB_CONTEXT_SELECT,
1961                            _("Rotate by pixels"));
1964 void
1965 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1967     if (selection->isEmpty())
1968         return;
1970     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1971     if (!bbox) {
1972         return;
1973     }
1975     NR::Point const center(bbox->midpoint());
1977     // you can't scale "do nizhe pola" (below zero)
1978     double const max_len = bbox->maxExtent();
1979     if ( max_len + grow <= 1e-3 ) {
1980         return;
1981     }
1983     double const times = 1.0 + grow / max_len;
1984     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1986     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1987                            ( (grow > 0)
1988                              ? "selector:scale:larger"
1989                              : "selector:scale:smaller" ),
1990                            SP_VERB_CONTEXT_SELECT,
1991                            _("Scale"));
1994 void
1995 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1997     sp_selection_scale(selection,
1998                        grow_pixels / selection->desktop()->current_zoom());
2001 void
2002 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
2004     if (selection->isEmpty())
2005         return;
2007     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
2009     if (!sel_bbox) {
2010         return;
2011     }
2013     NR::Point const center(sel_bbox->midpoint());
2014     sp_selection_scale_relative(selection, center, NR::scale(times, times));
2015     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
2016                      _("Scale by whole factor"));
2019 void
2020 sp_selection_move(gdouble dx, gdouble dy)
2022     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2023     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2024     if (selection->isEmpty()) {
2025         return;
2026     }
2028     sp_selection_move_relative(selection, dx, dy);
2030     if (dx == 0) {
2031         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
2032                                _("Move vertically"));
2033     } else if (dy == 0) {
2034         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
2035                                _("Move horizontally"));
2036     } else {
2037         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
2038                          _("Move"));
2039     }
2042 void
2043 sp_selection_move_screen(gdouble dx, gdouble dy)
2045     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2047     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2048     if (selection->isEmpty()) {
2049         return;
2050     }
2052     // same as sp_selection_move but divide deltas by zoom factor
2053     gdouble const zoom = desktop->current_zoom();
2054     gdouble const zdx = dx / zoom;
2055     gdouble const zdy = dy / zoom;
2056     sp_selection_move_relative(selection, zdx, zdy);
2058     if (dx == 0) {
2059         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
2060                                _("Move vertically by pixels"));
2061     } else if (dy == 0) {
2062         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
2063                                _("Move horizontally by pixels"));
2064     } else {
2065         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
2066                          _("Move"));
2067     }
2070 namespace {
2072 template <typename D>
2073 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2074                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
2076 template <typename D>
2077 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
2078                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
2080 struct Forward {
2081     typedef SPObject *Iterator;
2083     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
2084     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
2085     static void dispose(Iterator /*i*/) {}
2087     static SPObject *object(Iterator i) { return i; }
2088     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
2089 };
2091 struct Reverse {
2092     typedef GSList *Iterator;
2094     static Iterator children(SPObject *o) {
2095         return make_list(o->firstChild(), NULL);
2096     }
2097     static Iterator siblings_after(SPObject *o) {
2098         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
2099     }
2100     static void dispose(Iterator i) {
2101         g_slist_free(i);
2102     }
2104     static SPObject *object(Iterator i) {
2105         return reinterpret_cast<SPObject *>(i->data);
2106     }
2107     static Iterator next(Iterator i) { return i->next; }
2109 private:
2110     static GSList *make_list(SPObject *object, SPObject *limit) {
2111         GSList *list=NULL;
2112         while ( object != limit ) {
2113             list = g_slist_prepend(list, object);
2114             object = SP_OBJECT_NEXT(object);
2115         }
2116         return list;
2117     }
2118 };
2122 void
2123 sp_selection_item_next(void)
2125     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2126     g_return_if_fail(desktop != NULL);
2127     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2129     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2130     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2131     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2133     SPObject *root;
2134     if (PREFS_SELECTION_ALL != inlayer) {
2135         root = selection->activeContext();
2136     } else {
2137         root = desktop->currentRoot();
2138     }
2140     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2142     if (item) {
2143         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2144         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2145             scroll_to_show_item(desktop, item);
2146         }
2147     }
2150 void
2151 sp_selection_item_prev(void)
2153     SPDocument *document = SP_ACTIVE_DOCUMENT;
2154     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2155     g_return_if_fail(document != NULL);
2156     g_return_if_fail(desktop != NULL);
2157     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2159     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2160     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2161     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2163     SPObject *root;
2164     if (PREFS_SELECTION_ALL != inlayer) {
2165         root = selection->activeContext();
2166     } else {
2167         root = desktop->currentRoot();
2168     }
2170     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2172     if (item) {
2173         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2174         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2175             scroll_to_show_item(desktop, item);
2176         }
2177     }
2180 void sp_selection_next_patheffect_param(SPDesktop * dt)
2182     if (!dt) return;
2184     Inkscape::Selection *selection = sp_desktop_selection(dt);
2185     if ( selection && !selection->isEmpty() ) {
2186         SPItem *item = selection->singleItem();
2187         if ( item && SP_IS_SHAPE(item)) {
2188             SPShape *shape = SP_SHAPE(item);
2189             if (sp_shape_has_path_effect(shape)) {
2190                 sp_shape_edit_next_param_oncanvas(shape, dt);
2191             } else {
2192                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
2193             }
2194         }
2195     }
2198 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
2200     if (!dt) return;
2202     Inkscape::Selection *selection = sp_desktop_selection(dt);
2203     if ( selection && !selection->isEmpty() ) {
2204         SPItem *item = selection->singleItem();
2205         if ( item ) {
2206             SPObject *obj = NULL;
2207             if (clip)
2208                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
2209             else
2210                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
2212             if (obj) {
2213                 // obj is a group object, the children are the actual clippers
2214                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
2215                     if ( SP_IS_ITEM(child) ) {
2216                         // If not already in nodecontext, goto it!
2217                         if (!tools_isactive(dt, TOOLS_NODES)) {
2218                             tools_switch_current(TOOLS_NODES);
2219                         }
2221                         ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
2222                         shape_editor->set_item(SP_ITEM(child));
2223                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
2224                         if (np) {
2225                             // take colors from prefs (same as used in outline mode)
2226                             np->helperpath_rgba = clip ? 
2227                                 prefs_get_int_attribute("options.wireframecolors", "clips", 0x00ff00ff) : 
2228                                 prefs_get_int_attribute("options.wireframecolors", "masks", 0x0000ffff);
2229                             np->helperpath_width = 1.0;
2230                             sp_nodepath_show_helperpath(np, true);
2231                         }
2232                         break; // break out of for loop after 1st encountered item
2233                     }
2234                 }
2235             } else if (clip) {
2236                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
2237             } else {
2238                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
2239             }
2240         }
2241     }
2245 namespace {
2247 template <typename D>
2248 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
2249                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2251     SPObject *current=root;
2252     while (items) {
2253         SPItem *item=SP_ITEM(items->data);
2254         if ( root->isAncestorOf(item) &&
2255              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
2256         {
2257             current = item;
2258             break;
2259         }
2260         items = items->next;
2261     }
2263     GSList *path=NULL;
2264     while ( current != root ) {
2265         path = g_slist_prepend(path, current);
2266         current = SP_OBJECT_PARENT(current);
2267     }
2269     SPItem *next;
2270     // first, try from the current object
2271     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2272     g_slist_free(path);
2274     if (!next) { // if we ran out of objects, start over at the root
2275         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2276     }
2278     return next;
2281 template <typename D>
2282 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2283                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2285     typename D::Iterator children;
2286     typename D::Iterator iter;
2288     SPItem *found=NULL;
2290     if (path) {
2291         SPObject *object=reinterpret_cast<SPObject *>(path->data);
2292         g_assert(SP_OBJECT_PARENT(object) == root);
2293         if (desktop->isLayer(object)) {
2294             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2295         }
2296         iter = children = D::siblings_after(object);
2297     } else {
2298         iter = children = D::children(root);
2299     }
2301     while ( iter && !found ) {
2302         SPObject *object=D::object(iter);
2303         if (desktop->isLayer(object)) {
2304             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
2305                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2306             }
2307         } else if ( SP_IS_ITEM(object) &&
2308                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2309                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2310                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2311                     !desktop->isLayer(SP_ITEM(object)) )
2312         {
2313             found = SP_ITEM(object);
2314         }
2315         iter = D::next(iter);
2316     }
2318     D::dispose(children);
2320     return found;
2325 /**
2326  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2327  * \a item.
2328  */
2329 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2331     NR::Rect dbox = desktop->get_display_area();
2332     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2334     if ( sbox && dbox.contains(*sbox) == false ) {
2335         NR::Point const s_dt = sbox->midpoint();
2336         NR::Point const s_w = desktop->d2w(s_dt);
2337         NR::Point const d_dt = dbox.midpoint();
2338         NR::Point const d_w = desktop->d2w(d_dt);
2339         NR::Point const moved_w( d_w - s_w );
2340         gint const dx = (gint) moved_w[X];
2341         gint const dy = (gint) moved_w[Y];
2342         desktop->scroll_world(dx, dy);
2343     }
2347 void
2348 sp_selection_clone()
2350     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2351     if (desktop == NULL)
2352         return;
2354     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2356     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2358     // check if something is selected
2359     if (selection->isEmpty()) {
2360         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2361         return;
2362     }
2364     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2366     selection->clear();
2368     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2369     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2371     GSList *newsel = NULL;
2373     while (reprs) {
2374         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2375         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2377         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2378         sp_repr_set_attr(clone, "x", "0");
2379         sp_repr_set_attr(clone, "y", "0");
2380         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2382         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2383         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2385         // add the new clone to the top of the original's parent
2386         parent->appendChild(clone);
2388         newsel = g_slist_prepend(newsel, clone);
2389         reprs = g_slist_remove(reprs, sel_repr);
2390         Inkscape::GC::release(clone);
2391     }
2393     // TRANSLATORS: only translate "string" in "context|string".
2394     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2395     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2396                      Q_("action|Clone"));
2398     selection->setReprList(newsel);
2400     g_slist_free(newsel);
2403 void
2404 sp_selection_unlink()
2406     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2407     if (!desktop)
2408         return;
2410     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2412     if (selection->isEmpty()) {
2413         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2414         return;
2415     }
2417     // Get a copy of current selection.
2418     GSList *new_select = NULL;
2419     bool unlinked = false;
2420     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2421          items != NULL;
2422          items = items->next)
2423     {
2424         SPItem *item = (SPItem *) items->data;
2426         if (SP_IS_TEXT(item)) {
2427             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2429             if (tspan) {
2430                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2431             }
2433             // Set unlink to true, and fall into the next if which
2434             // will include this text item in the new selection
2435             unlinked = true;
2436         }
2438         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2439             // keep the non-use item in the new selection
2440             new_select = g_slist_prepend(new_select, item);
2441             continue;
2442         }
2444         SPItem *unlink;
2445         if (SP_IS_USE(item)) {
2446             unlink = sp_use_unlink(SP_USE(item));
2447         } else /*if (SP_IS_TREF(use))*/ {
2448             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2449         }
2451         unlinked = true;
2452         // Add ungrouped items to the new selection.
2453         new_select = g_slist_prepend(new_select, unlink);
2454     }
2456     if (new_select) { // set new selection
2457         selection->clear();
2458         selection->setList(new_select);
2459         g_slist_free(new_select);
2460     }
2461     if (!unlinked) {
2462         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2463     }
2465     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2466                      _("Unlink clone"));
2469 void
2470 sp_select_clone_original()
2472     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2473     if (desktop == NULL)
2474         return;
2476     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2478     SPItem *item = selection->singleItem();
2480     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.");
2482     // Check if other than two objects are selected
2483     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2484         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2485         return;
2486     }
2488     SPItem *original = NULL;
2489     if (SP_IS_USE(item)) {
2490         original = sp_use_get_original (SP_USE(item));
2491     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2492         original = sp_offset_get_source (SP_OFFSET(item));
2493     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2494         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2495     } else if (SP_IS_FLOWTEXT(item)) {
2496         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2497     } else { // it's an object that we don't know what to do with
2498         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2499         return;
2500     }
2502     if (!original) {
2503         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2504         return;
2505     }
2507     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2508         if (SP_IS_DEFS (o)) {
2509             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2510             return;
2511         }
2512     }
2514     if (original) {
2515         selection->clear();
2516         selection->set(original);
2517         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2518             scroll_to_show_item(desktop, original);
2519         }
2520     }
2524 void sp_selection_to_marker(bool apply)
2526     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2527     if (desktop == NULL)
2528         return;
2530     SPDocument *doc = sp_desktop_document(desktop);
2531     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2533     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2535     // check if something is selected
2536     if (selection->isEmpty()) {
2537         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2538         return;
2539     }
2541     sp_document_ensure_up_to_date(doc);
2542     NR::Maybe<NR::Rect> r = selection->bounds();
2543     NR::Maybe<NR::Point> c = selection->center();
2544     if ( !r || !c || r->isEmpty() ) {
2545         return;
2546     }
2548     // calculate the transform to be applied to objects to move them to 0,0
2549     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - *c;
2550     move_p[NR::Y] = -move_p[NR::Y];
2551     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2553     GSList *items = g_slist_copy((GSList *) selection->itemList());
2555     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2557     // bottommost object, after sorting
2558     SPObject *parent = SP_OBJECT_PARENT (items->data);
2560     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2562     // remember the position of the first item
2563     gint pos = SP_OBJECT_REPR (items->data)->position();
2564     (void)pos; // TODO check why this was remembered
2566     // create a list of duplicates
2567     GSList *repr_copies = NULL;
2568     for (GSList *i = items; i != NULL; i = i->next) {
2569         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2570         repr_copies = g_slist_prepend (repr_copies, dup);
2571     }
2573     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2575     if (apply) {
2576         // delete objects so that their clones don't get alerted; this object will be restored shortly
2577         for (GSList *i = items; i != NULL; i = i->next) {
2578             SPObject *item = SP_OBJECT (i->data);
2579             item->deleteObject (false);
2580         }
2581     }
2583     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2584     // without disturbing clones.
2585     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2586     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2587     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2589     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2590                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2591                                                                                                 r->max()[NR::Y]))))
2592                                              * parent_transform.inverse() ),
2593                                            parent_transform * move);
2594     (void)mark_id;
2596     // restore compensation setting
2597     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2600     g_slist_free (items);
2602     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2603                       _("Objects to marker"));
2606 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2607     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2608         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2609             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2610         }
2611     } else {
2612         sp_item_convert_item_to_guides(item);
2614         if (deleteitem) {
2615             SP_OBJECT(item)->deleteObject(true);
2616         }
2617     }
2620 void sp_selection_to_guides()
2622     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2623     if (desktop == NULL)
2624         return;
2626     SPDocument *doc = sp_desktop_document(desktop);
2627     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2628     // we need to copy the list because it gets reset when objects are deleted
2629     GSList *items = g_slist_copy((GSList *) selection->itemList());
2631     if (!items) {
2632         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2633         return;
2634     }
2635  
2636     bool deleteitem = (prefs_get_int_attribute("tools", "cvg_keep_objects", 0) == 0);
2637     bool wholegroups = (prefs_get_int_attribute("tools", "cvg_convert_whole_groups", 0) != 0);
2639     for (GSList const *i = items; i != NULL; i = i->next) {
2640         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2641     }
2643     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2646 void
2647 sp_selection_tile(bool apply)
2649     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2650     if (desktop == NULL)
2651         return;
2653     SPDocument *doc = sp_desktop_document(desktop);
2654     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2656     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2658     // check if something is selected
2659     if (selection->isEmpty()) {
2660         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2661         return;
2662     }
2664     sp_document_ensure_up_to_date(doc);
2665     NR::Maybe<NR::Rect> r = selection->bounds();
2666     if ( !r || r->isEmpty() ) {
2667         return;
2668     }
2670     // calculate the transform to be applied to objects to move them to 0,0
2671     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2672     move_p[NR::Y] = -move_p[NR::Y];
2673     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2675     GSList *items = g_slist_copy((GSList *) selection->itemList());
2677     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2679     // bottommost object, after sorting
2680     SPObject *parent = SP_OBJECT_PARENT (items->data);
2682     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2684     // remember the position of the first item
2685     gint pos = SP_OBJECT_REPR (items->data)->position();
2687     // create a list of duplicates
2688     GSList *repr_copies = NULL;
2689     for (GSList *i = items; i != NULL; i = i->next) {
2690         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2691         repr_copies = g_slist_prepend (repr_copies, dup);
2692     }
2693     // restore the z-order after prepends
2694     repr_copies = g_slist_reverse (repr_copies);
2696     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2698     if (apply) {
2699         // delete objects so that their clones don't get alerted; this object will be restored shortly
2700         for (GSList *i = items; i != NULL; i = i->next) {
2701             SPObject *item = SP_OBJECT (i->data);
2702             item->deleteObject (false);
2703         }
2704     }
2706     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2707     // without disturbing clones.
2708     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2709     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2710     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2712     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2713                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2714                                                                                             r->max()[NR::Y]))))
2715                                          * parent_transform.inverse() ),
2716                                        parent_transform * move);
2718     // restore compensation setting
2719     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2721     if (apply) {
2722         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2723         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2725         NR::Point min = bounds.min() * parent_transform.inverse();
2726         NR::Point max = bounds.max() * parent_transform.inverse();
2728         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2729         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2730         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2731         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2733         // restore parent and position
2734         SP_OBJECT_REPR (parent)->appendChild(rect);
2735         rect->setPosition(pos > 0 ? pos : 0);
2736         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2738         Inkscape::GC::release(rect);
2740         selection->clear();
2741         selection->set(rectangle);
2742     }
2744     g_slist_free (items);
2746     sp_document_done (doc, SP_VERB_EDIT_TILE,
2747                       _("Objects to pattern"));
2750 void
2751 sp_selection_untile()
2753     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2754     if (desktop == NULL)
2755         return;
2757     SPDocument *doc = sp_desktop_document(desktop);
2758     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2760     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2762     // check if something is selected
2763     if (selection->isEmpty()) {
2764         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2765         return;
2766     }
2768     GSList *new_select = NULL;
2770     bool did = false;
2772     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2773          items != NULL;
2774          items = items->next) {
2776         SPItem *item = (SPItem *) items->data;
2778         SPStyle *style = SP_OBJECT_STYLE (item);
2780         if (!style || !style->fill.isPaintserver())
2781             continue;
2783         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2785         if (!SP_IS_PATTERN(server))
2786             continue;
2788         did = true;
2790         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2792         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2793         pat_transform *= item->transform;
2795         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2796             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2797             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2799            // FIXME: relink clones to the new canvas objects
2800            // use SPObject::setid when mental finishes it to steal ids of
2802             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2803             sp_document_ensure_up_to_date (doc);
2805             NR::Matrix transform( i->transform * pat_transform );
2806             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2808             new_select = g_slist_prepend(new_select, i);
2809         }
2811         SPCSSAttr *css = sp_repr_css_attr_new ();
2812         sp_repr_css_set_property (css, "fill", "none");
2813         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2814     }
2816     if (!did) {
2817         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2818     } else {
2819         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2820                          _("Pattern to objects"));
2821         selection->setList(new_select);
2822     }
2825 void
2826 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2828     if (selection->isEmpty()) {
2829         return;
2830     }
2832     GSList const *reprlst = selection->reprList();
2833     bool filename_search = TRUE;
2834     bool xdpi_search = TRUE;
2835     bool ydpi_search = TRUE;
2837     for(; reprlst != NULL &&
2838             filename_search &&
2839             xdpi_search &&
2840             ydpi_search;
2841         reprlst = reprlst->next) {
2842         gchar const *dpi_string;
2843         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2845         if (filename_search) {
2846             *filename = repr->attribute("inkscape:export-filename");
2847             if (*filename != NULL)
2848                 filename_search = FALSE;
2849         }
2851         if (xdpi_search) {
2852             dpi_string = NULL;
2853             dpi_string = repr->attribute("inkscape:export-xdpi");
2854             if (dpi_string != NULL) {
2855                 *xdpi = atof(dpi_string);
2856                 xdpi_search = FALSE;
2857             }
2858         }
2860         if (ydpi_search) {
2861             dpi_string = NULL;
2862             dpi_string = repr->attribute("inkscape:export-ydpi");
2863             if (dpi_string != NULL) {
2864                 *ydpi = atof(dpi_string);
2865                 ydpi_search = FALSE;
2866             }
2867         }
2868     }
2871 void
2872 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2874     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2875     gchar const *dpi_string;
2877     *filename = repr->attribute("inkscape:export-filename");
2879     dpi_string = NULL;
2880     dpi_string = repr->attribute("inkscape:export-xdpi");
2881     if (dpi_string != NULL) {
2882         *xdpi = atof(dpi_string);
2883     }
2885     dpi_string = NULL;
2886     dpi_string = repr->attribute("inkscape:export-ydpi");
2887     if (dpi_string != NULL) {
2888         *ydpi = atof(dpi_string);
2889     }
2892 void
2893 sp_selection_create_bitmap_copy ()
2895     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2896     if (desktop == NULL)
2897         return;
2899     SPDocument *document = sp_desktop_document(desktop);
2900     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2902     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2904     // check if something is selected
2905     if (selection->isEmpty()) {
2906         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2907         return;
2908     }
2910     // Get the bounding box of the selection
2911     NRRect bbox;
2912     sp_document_ensure_up_to_date (document);
2913     selection->bounds(&bbox);
2914     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2915         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2916     }
2918     // List of the items to show; all others will be hidden
2919     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2921     // Sort items so that the topmost comes last
2922     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2924     // Generate a random value from the current time (you may create bitmap from the same object(s)
2925     // multiple times, and this is done so that they don't clash)
2926     GTimeVal cu;
2927     g_get_current_time (&cu);
2928     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2930     // Create the filename
2931     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2932     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2933     // digits, and a few other chars, with "_"
2934     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2935     // Build the complete path by adding document->base if set
2936     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2938     //g_print ("%s\n", filepath);
2940     // Remember parent and z-order of the topmost one
2941     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2942     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2943     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2945     // Calculate resolution
2946     double res;
2947     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2948     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2949     if (0 < prefs_res) {
2950         // If it's given explicitly in prefs, take it
2951         res = prefs_res;
2952     } else if (0 < prefs_min) {
2953         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2954         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2955     } else {
2956         float hint_xdpi = 0, hint_ydpi = 0;
2957         char const *hint_filename;
2958         // take resolution hint from the selected objects
2959         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2960         if (hint_xdpi != 0) {
2961             res = hint_xdpi;
2962         } else {
2963             // take resolution hint from the document
2964             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2965             if (hint_xdpi != 0) {
2966                 res = hint_xdpi;
2967             } else {
2968                 // if all else fails, take the default 90 dpi
2969                 res = PX_PER_IN;
2970             }
2971         }
2972     }
2974     // The width and height of the bitmap in pixels
2975     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2976     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2978     // Find out if we have to run a filter
2979     gchar const *run = NULL;
2980     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2981     if (filter) {
2982         // filter command is given;
2983         // see if we have a parameter to pass to it
2984         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2985         if (param1) {
2986             if (param1[strlen(param1) - 1] == '%') {
2987                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2988                 gchar p1[256];
2989                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2990                 // the first param is always the image filename, the second is param1
2991                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2992             } else {
2993                 // otherwise pass the param1 unchanged
2994                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2995             }
2996         } else {
2997             // run without extra parameter
2998             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2999         }
3000     }
3002     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
3003     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
3004     NR::Matrix t;
3006     double shift_x = bbox.x0;
3007     double shift_y = bbox.y1;
3008     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
3009         shift_x = round (shift_x);
3010         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
3011     }
3012     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
3014     // Do the export
3015     sp_export_png_file(document, filepath,
3016                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
3017                    width, height, res, res,
3018                    (guint32) 0xffffff00,
3019                    NULL, NULL,
3020                    true,  /*bool force_overwrite,*/
3021                    items);
3023     g_slist_free (items);
3025     // Run filter, if any
3026     if (run) {
3027         g_print ("Running external filter: %s\n", run);
3028         system (run);
3029     }
3031     // Import the image back
3032     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
3033     if (pb) {
3034         // Create the repr for the image
3035         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
3036         repr->setAttribute("xlink:href", filename);
3037         repr->setAttribute("sodipodi:absref", filepath);
3038         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
3039             sp_repr_set_svg_double(repr, "width", width);
3040             sp_repr_set_svg_double(repr, "height", height);
3041         } else {
3042             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
3043             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
3044         }
3046         // Write transform
3047         gchar *c=sp_svg_transform_write(t);
3048         repr->setAttribute("transform", c);
3049         g_free(c);
3051         // add the new repr to the parent
3052         parent->appendChild(repr);
3054         // move to the saved position
3055         repr->setPosition(pos > 0 ? pos + 1 : 1);
3057         // Set selection to the new image
3058         selection->clear();
3059         selection->add(repr);
3061         // Clean up
3062         Inkscape::GC::release(repr);
3063         gdk_pixbuf_unref (pb);
3065         // Complete undoable transaction
3066         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
3067                           _("Create bitmap"));
3068     }
3070     g_free (filename);
3071     g_free (filepath);
3074 /**
3075  * \brief sp_selection_set_mask
3076  *
3077  * This function creates a mask or clipPath from selection
3078  * Two different modes:
3079  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
3080  *       and is applied to current layer
3081  *  otherwise, topmost object is used as mask for other objects
3082  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
3083  *
3084  */
3085 void
3086 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
3088     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3089     if (desktop == NULL)
3090         return;
3092     SPDocument *doc = sp_desktop_document(desktop);
3093     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3095     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3097     // check if something is selected
3098     bool is_empty = selection->isEmpty();
3099     if ( apply_to_layer && is_empty) {
3100         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
3101         return;
3102     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
3103         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
3104         return;
3105     }
3107     // FIXME: temporary patch to prevent crash!
3108     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
3109     bool clone_with_original = selection_contains_both_clone_and_original (selection);
3110     if (clone_with_original) {
3111         return; // in this version, you cannot clip/mask an object with its own clone
3112     }
3113     // /END FIXME
3115     sp_document_ensure_up_to_date(doc);
3117     GSList *items = g_slist_copy((GSList *) selection->itemList());
3119     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
3121     // create a list of duplicates
3122     GSList *mask_items = NULL;
3123     GSList *apply_to_items = NULL;
3124     GSList *items_to_delete = NULL;
3125     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
3126     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3128     if (apply_to_layer) {
3129         // all selected items are used for mask, which is applied to a layer
3130         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
3132         for (GSList *i = items; i != NULL; i = i->next) {
3133             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3134             mask_items = g_slist_prepend (mask_items, dup);
3136             if (remove_original) {
3137                 SPObject *item = SP_OBJECT (i->data);
3138                 items_to_delete = g_slist_prepend (items_to_delete, item);
3139             }
3140         }
3141     } else if (!topmost) {
3142         // topmost item is used as a mask, which is applied to other items in a selection
3143         GSList *i = items;
3144         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3145         mask_items = g_slist_prepend (mask_items, dup);
3147         if (remove_original) {
3148             SPObject *item = SP_OBJECT (i->data);
3149             items_to_delete = g_slist_prepend (items_to_delete, item);
3150         }
3152         for (i = i->next; i != NULL; i = i->next) {
3153             apply_to_items = g_slist_prepend (apply_to_items, i->data);
3154         }
3155     } else {
3156         GSList *i = NULL;
3157         for (i = items; NULL != i->next; i = i->next) {
3158             apply_to_items = g_slist_prepend (apply_to_items, i->data);
3159         }
3161         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3162         mask_items = g_slist_prepend (mask_items, dup);
3164         if (remove_original) {
3165             SPObject *item = SP_OBJECT (i->data);
3166             items_to_delete = g_slist_prepend (items_to_delete, item);
3167         }
3168     }
3170     g_slist_free (items);
3171     items = NULL;
3173     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3174     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
3175         SPItem *item = reinterpret_cast<SPItem *>(i->data);
3176         // inverted object transform should be applied to a mask object,
3177         // as mask is calculated in user space (after applying transform)
3178         NR::Matrix maskTransform (item->transform.inverse());
3180         GSList *mask_items_dup = NULL;
3181         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
3182             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
3183             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
3184         }
3186         gchar const *mask_id = NULL;
3187         if (apply_clip_path) {
3188             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
3189         } else {
3190             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
3191         }
3193         g_slist_free (mask_items_dup);
3194         mask_items_dup = NULL;
3196         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3197     }
3199     g_slist_free (mask_items);
3200     g_slist_free (apply_to_items);
3202     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3203         SPObject *item = SP_OBJECT (i->data);
3204         item->deleteObject (false);
3205     }
3206     g_slist_free (items_to_delete);
3208     if (apply_clip_path)
3209         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3210     else
3211         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3214 void sp_selection_unset_mask(bool apply_clip_path) {
3215     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3216     if (desktop == NULL)
3217         return;
3219     SPDocument *doc = sp_desktop_document(desktop);
3220     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3221     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3223     // check if something is selected
3224     if (selection->isEmpty()) {
3225         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3226         return;
3227     }
3229     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3230     sp_document_ensure_up_to_date(doc);
3232     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3233     std::map<SPObject*,SPItem*> referenced_objects;
3234     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3235         if (remove_original) {
3236             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3237             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3238             Inkscape::URIReference *uri_ref = NULL;
3240             if (apply_clip_path) {
3241                 uri_ref = item->clip_ref;
3242             } else {
3243                 uri_ref = item->mask_ref;
3244             }
3246             // collect distinct mask object (and associate with item to apply transform)
3247             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3248                 referenced_objects[uri_ref->getObject()] = item;
3249             }
3250         }
3252         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3253     }
3255     // restore mask objects into a document
3256     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3257         SPObject *obj = (*it).first;
3258         GSList *items_to_move = NULL;
3259         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3260             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3261             items_to_move = g_slist_prepend (items_to_move, copy);
3262         }
3264         if (!obj->isReferenced()) {
3265             // delete from defs if no other object references this mask
3266             obj->deleteObject(false);
3267         }
3269         // remember parent and position of the item to which the clippath/mask was applied
3270         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3271         gint pos = SP_OBJECT_REPR((*it).second)->position();
3273         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3274             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3276             // insert into parent, restore pos
3277             parent->appendChild(repr);
3278             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3280             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
3281             selection->add(repr);
3283             // transform mask, so it is moved the same spot where mask was applied
3284             NR::Matrix transform (mask_item->transform);
3285             transform *= (*it).second->transform;
3286             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3287         }
3289         g_slist_free (items_to_move);
3290     }
3292     if (apply_clip_path)
3293         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3294     else
3295         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3298 void fit_canvas_to_selection(SPDesktop *desktop) {
3299     g_return_if_fail(desktop != NULL);
3300     SPDocument *doc = sp_desktop_document(desktop);
3302     g_return_if_fail(doc != NULL);
3303     g_return_if_fail(desktop->selection != NULL);
3305     if (desktop->selection->isEmpty()) {
3306         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3307         return;
3308     }
3309     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
3310     if (bbox && !bbox->isEmpty()) {
3311         doc->fitToRect(*bbox);
3312     }
3313 };
3315 void fit_canvas_to_drawing(SPDocument *doc) {
3316     g_return_if_fail(doc != NULL);
3318     sp_document_ensure_up_to_date(doc);
3319     SPItem const *const root = SP_ITEM(doc->root);
3320     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
3321     if (bbox && !bbox->isEmpty()) {
3322         doc->fitToRect(*bbox);
3323     }
3324 };
3326 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3327     g_return_if_fail(desktop != NULL);
3328     SPDocument *doc = sp_desktop_document(desktop);
3330     g_return_if_fail(doc != NULL);
3331     g_return_if_fail(desktop->selection != NULL);
3333     if (desktop->selection->isEmpty()) {
3334         fit_canvas_to_drawing(doc);
3335     } else {
3336         fit_canvas_to_selection(desktop);
3337     }
3339     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
3340                      _("Fit page to selection"));
3341 };
3343 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3344     // don't operate on layers
3345     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3346         f(SP_ITEM(root), desktop);
3347     }
3348     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3349         //don't recurse into locked layers
3350         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3351             itemtree_map(f, iter, desktop);
3352         }
3353     }
3356 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3357     if (item->isLocked()) {
3358         item->setLocked(FALSE);
3359     }
3362 static void unhide(SPItem *item, SPDesktop *desktop) {
3363     if (desktop->itemIsHidden(item)) {
3364         item->setExplicitlyHidden(FALSE);
3365     }
3368 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3369     if (!dt) return;
3371     SPObject *root;
3372     if (layer_only) {
3373         root = dt->currentLayer();
3374     } else {
3375         root = dt->currentRoot();
3376     }
3378     itemtree_map(f, root, dt);
3381 void unlock_all(SPDesktop *dt) {
3382     process_all(&unlock, dt, true);
3385 void unlock_all_in_all_layers(SPDesktop *dt) {
3386     process_all(&unlock, dt, false);
3389 void unhide_all(SPDesktop *dt) {
3390     process_all(&unhide, dt, true);
3393 void unhide_all_in_all_layers(SPDesktop *dt) {
3394     process_all(&unhide, dt, false);
3398 GSList * sp_selection_get_clipboard() {
3399     return clipboard;
3403 /*
3404   Local Variables:
3405   mode:c++
3406   c-file-style:"stroustrup"
3407   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3408   indent-tabs-mode:nil
3409   fill-column:99
3410   End:
3411 */
3412 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :