Code

recurse into groups when pasting lpe
[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"));
1385 void sp_selection_paste_size (bool apply_x, bool apply_y)
1387     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1388     if (desktop == NULL) return;
1390     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1392     // check if something is in the clipboard
1393     if (!size_clipboard) {
1394         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1395         return;
1396     }
1398     // check if something is selected
1399     if (selection->isEmpty()) {
1400         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1401         return;
1402     }
1404     NR::Maybe<NR::Rect> current = selection->bounds();
1405     if ( !current || current->isEmpty() ) {
1406         return;
1407     }
1409     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1410     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1412     sp_selection_scale_relative (selection, current->midpoint(),
1413                                  NR::scale(
1414                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1415                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1417     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1418                      _("Paste size"));
1421 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1423     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1424     if (desktop == NULL) return;
1426     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1428     // check if something is in the clipboard
1429     if ( !size_clipboard ) {
1430         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1431         return;
1432     }
1434     // check if something is selected
1435     if (selection->isEmpty()) {
1436         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1437         return;
1438     }
1440     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1441         SPItem *item = SP_ITEM(l->data);
1443         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1444         if ( !current || current->isEmpty() ) {
1445             continue;
1446         }
1448         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1449         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1451         sp_item_scale_rel (item,
1452                                  NR::scale(
1453                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1454                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1456     }
1458     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1459                      _("Paste size separately"));
1462 void sp_selection_to_next_layer ()
1464     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1466     Inkscape::Selection *selection = sp_desktop_selection(dt);
1468     // check if something is selected
1469     if (selection->isEmpty()) {
1470         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1471         return;
1472     }
1474     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1476     bool no_more = false; // Set to true, if no more layers above
1477     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1478     if (next) {
1479         GSList *temp_clip = NULL;
1480         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
1481         sp_selection_delete_impl (items, false, false);
1482         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1483         GSList *copied;
1484         if(next) {
1485             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1486         } else {
1487             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1488             no_more = true;
1489         }
1490         selection->setReprList((GSList const *) copied);
1491         g_slist_free (copied);
1492         if (temp_clip) g_slist_free (temp_clip);
1493         if (next) dt->setCurrentLayer(next);
1494         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1495                          _("Raise to next layer"));
1496     } else {
1497         no_more = true;
1498     }
1500     if (no_more) {
1501         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1502     }
1504     g_slist_free ((GSList *) items);
1507 void sp_selection_to_prev_layer ()
1509     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1511     Inkscape::Selection *selection = sp_desktop_selection(dt);
1513     // check if something is selected
1514     if (selection->isEmpty()) {
1515         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1516         return;
1517     }
1519     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1521     bool no_more = false; // Set to true, if no more layers below
1522     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1523     if (next) {
1524         GSList *temp_clip = NULL;
1525         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
1526         sp_selection_delete_impl (items, false, false);
1527         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1528         GSList *copied;
1529         if(next) {
1530             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1531         } else {
1532             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1533             no_more = true;
1534         }
1535         selection->setReprList((GSList const *) copied);
1536         g_slist_free (copied);
1537         if (temp_clip) g_slist_free (temp_clip);
1538         if (next) dt->setCurrentLayer(next);
1539         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1540                          _("Lower to previous layer"));
1541     } else {
1542         no_more = true;
1543     }
1545     if (no_more) {
1546         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1547     }
1549     g_slist_free ((GSList *) items);
1552 bool
1553 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1555     bool contains_original = false;
1557     bool is_use = SP_IS_USE(item);
1558     SPItem *item_use = item;
1559     SPItem *item_use_first = item;
1560     while (is_use && item_use && !contains_original)
1561     {
1562         item_use = sp_use_get_original (SP_USE(item_use));
1563         contains_original |= selection->includes(item_use);
1564         if (item_use == item_use_first)
1565             break;
1566         is_use = SP_IS_USE(item_use);
1567     }
1569     // If it's a tref, check whether the object containing the character
1570     // data is part of the selection
1571     if (!contains_original && SP_IS_TREF(item)) {
1572         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1573     }
1575     return contains_original;
1579 bool
1580 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1582     bool clone_with_original = false;
1583     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1584         SPItem *item = SP_ITEM(l->data);
1585         clone_with_original |= selection_contains_original(item, selection);
1586         if (clone_with_original)
1587             break;
1588     }
1589     return clone_with_original;
1593 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1594 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1595 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1596 that case, items are already in the new position, but the repr is in the old, and this function
1597 then simply updates the repr from item->transform.
1598  */
1599 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1601     if (selection->isEmpty())
1602         return;
1604     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1605         SPItem *item = SP_ITEM(l->data);
1607         NR::Point old_center(0,0);
1608         if (set_i2d && item->isCenterSet())
1609             old_center = item->getCenter();
1611 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1612          At the time of writing, this is the only place to re-enable. */
1613         sp_item_update_cns(*item, selection->desktop());
1614 #endif
1616         // we're moving both a clone and its original or any ancestor in clone chain?
1617         bool transform_clone_with_original = selection_contains_original(item, selection);
1618         // ...both a text-on-path and its path?
1619         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)))) ));
1620         // ...both a flowtext and its frame?
1621         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)
1622         // ...both an offset and its source?
1623         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1625         // If we're moving a connector, we want to detach it
1626         // from shapes that aren't part of the selection, but
1627         // leave it attached if they are
1628         if (cc_item_is_connector(item)) {
1629             SPItem *attItem[2];
1630             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1632             for (int n = 0; n < 2; ++n) {
1633                 if (!selection->includes(attItem[n])) {
1634                     sp_conn_end_detach(item, n);
1635                 }
1636             }
1637         }
1639         // "clones are unmoved when original is moved" preference
1640         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1641         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1642         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1644         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1645         // transform of its original and respond to it itself. Without this, a clone is doubly
1646         // transformed, very unintuitive.
1647       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1648       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1649       // Same for linked offset if we are also moving its source: do not move it.
1650         if (transform_textpath_with_path || transform_offset_with_source) {
1651                 // restore item->transform field from the repr, in case it was changed by seltrans
1652             sp_object_read_attr (SP_OBJECT (item), "transform");
1654         } else if (transform_flowtext_with_frame) {
1655             // apply the inverse of the region's transform to the <use> so that the flow remains
1656             // the same (even though the output itself gets transformed)
1657             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1658                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1659                     continue;
1660                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1661                     if (!SP_IS_USE(use)) continue;
1662                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1663                 }
1664             }
1665         } else if (transform_clone_with_original) {
1666             // We are transforming a clone along with its original. The below matrix juggling is
1667             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1668             // transform and its move compensation are both cancelled out.
1670             // restore item->transform field from the repr, in case it was changed by seltrans
1671             sp_object_read_attr (SP_OBJECT (item), "transform");
1673             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1674             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1675             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1676             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1677             NR::Matrix result = t_inv * item->transform * t;
1679             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1680                 // we need to cancel out the move compensation, too
1682                 // find out the clone move, same as in sp_use_move_compensate
1683                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1684                 NR::Matrix clone_move = parent.inverse() * t * parent;
1686                 if (prefs_parallel) {
1687                     NR::Matrix move = result * clone_move * t_inv;
1688                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1690                 } else if (prefs_unmoved) {
1691                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1692                     //    clone_move = NR::identity();
1693                     NR::Matrix move = result * clone_move;
1694                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1695                 }
1697             } else {
1698                 // just apply the result
1699                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1700             }
1702         } else {
1703             if (set_i2d) {
1704                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1705             }
1706             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1707         }
1709         // if we're moving the actual object, not just updating the repr, we can transform the
1710         // center by the same matrix (only necessary for non-translations)
1711         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1712             item->setCenter(old_center * affine);
1713             SP_OBJECT(item)->updateRepr();
1714         }
1715     }
1718 void sp_selection_remove_transform()
1720     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1721     if (desktop == NULL)
1722         return;
1724     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1726     GSList const *l = (GSList *) selection->reprList();
1727     while (l != NULL) {
1728         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1729         l = l->next;
1730     }
1732     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1733                      _("Remove transform"));
1736 void
1737 sp_selection_scale_absolute(Inkscape::Selection *selection,
1738                             double const x0, double const x1,
1739                             double const y0, double const y1)
1741     if (selection->isEmpty())
1742         return;
1744     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1745     if ( !bbox || bbox->isEmpty() ) {
1746         return;
1747     }
1749     NR::translate const p2o(-bbox->min());
1751     NR::scale const newSize(x1 - x0,
1752                             y1 - y0);
1753     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1754     NR::translate const o2n(x0, y0);
1755     NR::Matrix const final( p2o * scale * o2n );
1757     sp_selection_apply_affine(selection, final);
1761 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1763     if (selection->isEmpty())
1764         return;
1766     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1768     if ( !bbox || bbox->isEmpty() ) {
1769         return;
1770     }
1772     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1773     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1774          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1775     {
1776         return;
1777     }
1779     NR::translate const n2d(-align);
1780     NR::translate const d2n(align);
1781     NR::Matrix const final( n2d * scale * d2n );
1782     sp_selection_apply_affine(selection, final);
1785 void
1786 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1788     NR::translate const d2n(center);
1789     NR::translate const n2d(-center);
1790     NR::rotate const rotate(rotate_degrees(angle_degrees));
1791     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1792     sp_selection_apply_affine(selection, final);
1795 void
1796 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1798     NR::translate const d2n(align);
1799     NR::translate const n2d(-align);
1800     NR::Matrix const skew(1, dy,
1801                           dx, 1,
1802                           0, 0);
1803     NR::Matrix const final( n2d * skew * d2n );
1804     sp_selection_apply_affine(selection, final);
1807 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1809     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1812 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1814     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1818 /**
1819  * \brief sp_selection_rotate_90
1820  *
1821  * This function rotates selected objects 90 degrees clockwise.
1822  *
1823  */
1825 void sp_selection_rotate_90_cw()
1827     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1829     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1831     if (selection->isEmpty())
1832         return;
1834     GSList const *l = selection->itemList();
1835     NR::rotate const rot_neg_90(NR::Point(0, -1));
1836     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1837         SPItem *item = SP_ITEM(l2->data);
1838         sp_item_rotate_rel(item, rot_neg_90);
1839     }
1841     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1842                      _("Rotate 90&#176; CW"));
1846 /**
1847  * \brief sp_selection_rotate_90_ccw
1848  *
1849  * This function rotates selected objects 90 degrees counter-clockwise.
1850  *
1851  */
1853 void sp_selection_rotate_90_ccw()
1855     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1857     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1859     if (selection->isEmpty())
1860         return;
1862     GSList const *l = selection->itemList();
1863     NR::rotate const rot_neg_90(NR::Point(0, 1));
1864     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1865         SPItem *item = SP_ITEM(l2->data);
1866         sp_item_rotate_rel(item, rot_neg_90);
1867     }
1869     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1870                      _("Rotate 90&#176; CCW"));
1873 void
1874 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1876     if (selection->isEmpty())
1877         return;
1879     NR::Maybe<NR::Point> center = selection->center();
1880     if (!center) {
1881         return;
1882     }
1884     sp_selection_rotate_relative(selection, *center, angle_degrees);
1886     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1887                            ( ( angle_degrees > 0 )
1888                              ? "selector:rotate:ccw"
1889                              : "selector:rotate:cw" ),
1890                            SP_VERB_CONTEXT_SELECT,
1891                            _("Rotate"));
1894 /**
1895 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1896 */
1897 void
1898 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1900     if (selection->isEmpty())
1901         return;
1903     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1904     NR::Maybe<NR::Point> center = selection->center();
1906     if ( !bbox || !center ) {
1907         return;
1908     }
1910     gdouble const zoom = selection->desktop()->current_zoom();
1911     gdouble const zmove = angle / zoom;
1912     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1914     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1916     sp_selection_rotate_relative(selection, *center, zangle);
1918     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1919                            ( (angle > 0)
1920                              ? "selector:rotate:ccw"
1921                              : "selector:rotate:cw" ),
1922                            SP_VERB_CONTEXT_SELECT,
1923                            _("Rotate by pixels"));
1926 void
1927 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1929     if (selection->isEmpty())
1930         return;
1932     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1933     if (!bbox) {
1934         return;
1935     }
1937     NR::Point const center(bbox->midpoint());
1939     // you can't scale "do nizhe pola" (below zero)
1940     double const max_len = bbox->maxExtent();
1941     if ( max_len + grow <= 1e-3 ) {
1942         return;
1943     }
1945     double const times = 1.0 + grow / max_len;
1946     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1948     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1949                            ( (grow > 0)
1950                              ? "selector:scale:larger"
1951                              : "selector:scale:smaller" ),
1952                            SP_VERB_CONTEXT_SELECT,
1953                            _("Scale"));
1956 void
1957 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1959     sp_selection_scale(selection,
1960                        grow_pixels / selection->desktop()->current_zoom());
1963 void
1964 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1966     if (selection->isEmpty())
1967         return;
1969     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1971     if (!sel_bbox) {
1972         return;
1973     }
1975     NR::Point const center(sel_bbox->midpoint());
1976     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1977     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1978                      _("Scale by whole factor"));
1981 void
1982 sp_selection_move(gdouble dx, gdouble dy)
1984     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1985     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1986     if (selection->isEmpty()) {
1987         return;
1988     }
1990     sp_selection_move_relative(selection, dx, dy);
1992     if (dx == 0) {
1993         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1994                                _("Move vertically"));
1995     } else if (dy == 0) {
1996         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1997                                _("Move horizontally"));
1998     } else {
1999         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
2000                          _("Move"));
2001     }
2004 void
2005 sp_selection_move_screen(gdouble dx, gdouble dy)
2007     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2009     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2010     if (selection->isEmpty()) {
2011         return;
2012     }
2014     // same as sp_selection_move but divide deltas by zoom factor
2015     gdouble const zoom = desktop->current_zoom();
2016     gdouble const zdx = dx / zoom;
2017     gdouble const zdy = dy / zoom;
2018     sp_selection_move_relative(selection, zdx, zdy);
2020     if (dx == 0) {
2021         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
2022                                _("Move vertically by pixels"));
2023     } else if (dy == 0) {
2024         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
2025                                _("Move horizontally by pixels"));
2026     } else {
2027         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
2028                          _("Move"));
2029     }
2032 namespace {
2034 template <typename D>
2035 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2036                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
2038 template <typename D>
2039 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
2040                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
2042 struct Forward {
2043     typedef SPObject *Iterator;
2045     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
2046     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
2047     static void dispose(Iterator /*i*/) {}
2049     static SPObject *object(Iterator i) { return i; }
2050     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
2051 };
2053 struct Reverse {
2054     typedef GSList *Iterator;
2056     static Iterator children(SPObject *o) {
2057         return make_list(o->firstChild(), NULL);
2058     }
2059     static Iterator siblings_after(SPObject *o) {
2060         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
2061     }
2062     static void dispose(Iterator i) {
2063         g_slist_free(i);
2064     }
2066     static SPObject *object(Iterator i) {
2067         return reinterpret_cast<SPObject *>(i->data);
2068     }
2069     static Iterator next(Iterator i) { return i->next; }
2071 private:
2072     static GSList *make_list(SPObject *object, SPObject *limit) {
2073         GSList *list=NULL;
2074         while ( object != limit ) {
2075             list = g_slist_prepend(list, object);
2076             object = SP_OBJECT_NEXT(object);
2077         }
2078         return list;
2079     }
2080 };
2084 void
2085 sp_selection_item_next(void)
2087     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2088     g_return_if_fail(desktop != NULL);
2089     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2091     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2092     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2093     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2095     SPObject *root;
2096     if (PREFS_SELECTION_ALL != inlayer) {
2097         root = selection->activeContext();
2098     } else {
2099         root = desktop->currentRoot();
2100     }
2102     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2104     if (item) {
2105         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2106         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2107             scroll_to_show_item(desktop, item);
2108         }
2109     }
2112 void
2113 sp_selection_item_prev(void)
2115     SPDocument *document = SP_ACTIVE_DOCUMENT;
2116     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2117     g_return_if_fail(document != NULL);
2118     g_return_if_fail(desktop != NULL);
2119     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2121     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2122     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2123     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2125     SPObject *root;
2126     if (PREFS_SELECTION_ALL != inlayer) {
2127         root = selection->activeContext();
2128     } else {
2129         root = desktop->currentRoot();
2130     }
2132     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2134     if (item) {
2135         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2136         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2137             scroll_to_show_item(desktop, item);
2138         }
2139     }
2142 void sp_selection_next_patheffect_param(SPDesktop * dt)
2144     if (!dt) return;
2146     Inkscape::Selection *selection = sp_desktop_selection(dt);
2147     if ( selection && !selection->isEmpty() ) {
2148         SPItem *item = selection->singleItem();
2149         if ( item && SP_IS_SHAPE(item)) {
2150             SPShape *shape = SP_SHAPE(item);
2151             if (sp_shape_has_path_effect(shape)) {
2152                 sp_shape_edit_next_param_oncanvas(shape, dt);
2153             } else {
2154                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
2155             }
2156         }
2157     }
2160 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
2162     if (!dt) return;
2164     Inkscape::Selection *selection = sp_desktop_selection(dt);
2165     if ( selection && !selection->isEmpty() ) {
2166         SPItem *item = selection->singleItem();
2167         if ( item ) {
2168             SPObject *obj = NULL;
2169             if (clip)
2170                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
2171             else
2172                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
2174             if (obj) {
2175                 // obj is a group object, the children are the actual clippers
2176                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
2177                     if ( SP_IS_ITEM(child) ) {
2178                         // If not already in nodecontext, goto it!
2179                         if (!tools_isactive(dt, TOOLS_NODES)) {
2180                             tools_switch_current(TOOLS_NODES);
2181                         }
2183                         ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
2184                         shape_editor->set_item(SP_ITEM(child));
2185                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
2186                         if (np) {
2187                             // take colors from prefs (same as used in outline mode)
2188                             np->helperpath_rgba = clip ? 
2189                                 prefs_get_int_attribute("options.wireframecolors", "clips", 0x00ff00ff) : 
2190                                 prefs_get_int_attribute("options.wireframecolors", "masks", 0x0000ffff);
2191                             np->helperpath_width = 1.0;
2192                             sp_nodepath_show_helperpath(np, true);
2193                         }
2194                         break; // break out of for loop after 1st encountered item
2195                     }
2196                 }
2197             } else if (clip) {
2198                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
2199             } else {
2200                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
2201             }
2202         }
2203     }
2207 namespace {
2209 template <typename D>
2210 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
2211                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2213     SPObject *current=root;
2214     while (items) {
2215         SPItem *item=SP_ITEM(items->data);
2216         if ( root->isAncestorOf(item) &&
2217              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
2218         {
2219             current = item;
2220             break;
2221         }
2222         items = items->next;
2223     }
2225     GSList *path=NULL;
2226     while ( current != root ) {
2227         path = g_slist_prepend(path, current);
2228         current = SP_OBJECT_PARENT(current);
2229     }
2231     SPItem *next;
2232     // first, try from the current object
2233     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2234     g_slist_free(path);
2236     if (!next) { // if we ran out of objects, start over at the root
2237         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2238     }
2240     return next;
2243 template <typename D>
2244 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2245                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2247     typename D::Iterator children;
2248     typename D::Iterator iter;
2250     SPItem *found=NULL;
2252     if (path) {
2253         SPObject *object=reinterpret_cast<SPObject *>(path->data);
2254         g_assert(SP_OBJECT_PARENT(object) == root);
2255         if (desktop->isLayer(object)) {
2256             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2257         }
2258         iter = children = D::siblings_after(object);
2259     } else {
2260         iter = children = D::children(root);
2261     }
2263     while ( iter && !found ) {
2264         SPObject *object=D::object(iter);
2265         if (desktop->isLayer(object)) {
2266             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
2267                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2268             }
2269         } else if ( SP_IS_ITEM(object) &&
2270                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2271                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2272                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2273                     !desktop->isLayer(SP_ITEM(object)) )
2274         {
2275             found = SP_ITEM(object);
2276         }
2277         iter = D::next(iter);
2278     }
2280     D::dispose(children);
2282     return found;
2287 /**
2288  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2289  * \a item.
2290  */
2291 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2293     NR::Rect dbox = desktop->get_display_area();
2294     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2296     if ( sbox && dbox.contains(*sbox) == false ) {
2297         NR::Point const s_dt = sbox->midpoint();
2298         NR::Point const s_w = desktop->d2w(s_dt);
2299         NR::Point const d_dt = dbox.midpoint();
2300         NR::Point const d_w = desktop->d2w(d_dt);
2301         NR::Point const moved_w( d_w - s_w );
2302         gint const dx = (gint) moved_w[X];
2303         gint const dy = (gint) moved_w[Y];
2304         desktop->scroll_world(dx, dy);
2305     }
2309 void
2310 sp_selection_clone()
2312     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2313     if (desktop == NULL)
2314         return;
2316     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2318     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2320     // check if something is selected
2321     if (selection->isEmpty()) {
2322         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2323         return;
2324     }
2326     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2328     selection->clear();
2330     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2331     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2333     GSList *newsel = NULL;
2335     while (reprs) {
2336         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2337         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2339         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2340         sp_repr_set_attr(clone, "x", "0");
2341         sp_repr_set_attr(clone, "y", "0");
2342         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2344         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2345         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2347         // add the new clone to the top of the original's parent
2348         parent->appendChild(clone);
2350         newsel = g_slist_prepend(newsel, clone);
2351         reprs = g_slist_remove(reprs, sel_repr);
2352         Inkscape::GC::release(clone);
2353     }
2355     // TRANSLATORS: only translate "string" in "context|string".
2356     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2357     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2358                      Q_("action|Clone"));
2360     selection->setReprList(newsel);
2362     g_slist_free(newsel);
2365 void
2366 sp_selection_unlink()
2368     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2369     if (!desktop)
2370         return;
2372     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2374     if (selection->isEmpty()) {
2375         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2376         return;
2377     }
2379     // Get a copy of current selection.
2380     GSList *new_select = NULL;
2381     bool unlinked = false;
2382     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2383          items != NULL;
2384          items = items->next)
2385     {
2386         SPItem *item = (SPItem *) items->data;
2388         if (SP_IS_TEXT(item)) {
2389             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2391             if (tspan) {
2392                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2393             }
2395             // Set unlink to true, and fall into the next if which
2396             // will include this text item in the new selection
2397             unlinked = true;
2398         }
2400         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2401             // keep the non-use item in the new selection
2402             new_select = g_slist_prepend(new_select, item);
2403             continue;
2404         }
2406         SPItem *unlink;
2407         if (SP_IS_USE(item)) {
2408             unlink = sp_use_unlink(SP_USE(item));
2409         } else /*if (SP_IS_TREF(use))*/ {
2410             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2411         }
2413         unlinked = true;
2414         // Add ungrouped items to the new selection.
2415         new_select = g_slist_prepend(new_select, unlink);
2416     }
2418     if (new_select) { // set new selection
2419         selection->clear();
2420         selection->setList(new_select);
2421         g_slist_free(new_select);
2422     }
2423     if (!unlinked) {
2424         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2425     }
2427     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2428                      _("Unlink clone"));
2431 void
2432 sp_select_clone_original()
2434     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2435     if (desktop == NULL)
2436         return;
2438     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2440     SPItem *item = selection->singleItem();
2442     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.");
2444     // Check if other than two objects are selected
2445     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2446         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2447         return;
2448     }
2450     SPItem *original = NULL;
2451     if (SP_IS_USE(item)) {
2452         original = sp_use_get_original (SP_USE(item));
2453     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2454         original = sp_offset_get_source (SP_OFFSET(item));
2455     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2456         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2457     } else if (SP_IS_FLOWTEXT(item)) {
2458         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2459     } else { // it's an object that we don't know what to do with
2460         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2461         return;
2462     }
2464     if (!original) {
2465         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2466         return;
2467     }
2469     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2470         if (SP_IS_DEFS (o)) {
2471             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2472             return;
2473         }
2474     }
2476     if (original) {
2477         selection->clear();
2478         selection->set(original);
2479         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2480             scroll_to_show_item(desktop, original);
2481         }
2482     }
2486 void sp_selection_to_marker(bool apply)
2488     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2489     if (desktop == NULL)
2490         return;
2492     SPDocument *doc = sp_desktop_document(desktop);
2493     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2495     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2497     // check if something is selected
2498     if (selection->isEmpty()) {
2499         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2500         return;
2501     }
2503     sp_document_ensure_up_to_date(doc);
2504     NR::Maybe<NR::Rect> r = selection->bounds();
2505     NR::Maybe<NR::Point> c = selection->center();
2506     if ( !r || !c || r->isEmpty() ) {
2507         return;
2508     }
2510     // calculate the transform to be applied to objects to move them to 0,0
2511     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - *c;
2512     move_p[NR::Y] = -move_p[NR::Y];
2513     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2515     GSList *items = g_slist_copy((GSList *) selection->itemList());
2517     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2519     // bottommost object, after sorting
2520     SPObject *parent = SP_OBJECT_PARENT (items->data);
2522     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2524     // remember the position of the first item
2525     gint pos = SP_OBJECT_REPR (items->data)->position();
2526     (void)pos; // TODO check why this was remembered
2528     // create a list of duplicates
2529     GSList *repr_copies = NULL;
2530     for (GSList *i = items; i != NULL; i = i->next) {
2531         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2532         repr_copies = g_slist_prepend (repr_copies, dup);
2533     }
2535     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2537     if (apply) {
2538         // delete objects so that their clones don't get alerted; this object will be restored shortly
2539         for (GSList *i = items; i != NULL; i = i->next) {
2540             SPObject *item = SP_OBJECT (i->data);
2541             item->deleteObject (false);
2542         }
2543     }
2545     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2546     // without disturbing clones.
2547     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2548     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2549     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2551     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2552                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2553                                                                                                 r->max()[NR::Y]))))
2554                                              * parent_transform.inverse() ),
2555                                            parent_transform * move);
2556     (void)mark_id;
2558     // restore compensation setting
2559     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2562     g_slist_free (items);
2564     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2565                       _("Objects to marker"));
2568 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem) {
2569     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item)) {
2570         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2571             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem);
2572         }
2573     } else {
2574         sp_item_convert_item_to_guides(item);
2576         if (deleteitem) {
2577             SP_OBJECT(item)->deleteObject(true);
2578         }
2579     }
2582 void sp_selection_to_guides()
2584     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2585     if (desktop == NULL)
2586         return;
2588     SPDocument *doc = sp_desktop_document(desktop);
2589     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2590     // we need to copy the list because it gets reset when objects are deleted
2591     GSList *items = g_slist_copy((GSList *) selection->itemList());
2593     if (!items) {
2594         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2595         return;
2596     }
2597  
2598     bool deleteitem = (prefs_get_int_attribute("tools", "cvg_keep_objects", 0) == 0);
2600     for (GSList const *i = items; i != NULL; i = i->next) {
2601         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem);
2602     }
2604     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2607 void
2608 sp_selection_tile(bool apply)
2610     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2611     if (desktop == NULL)
2612         return;
2614     SPDocument *doc = sp_desktop_document(desktop);
2615     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2617     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2619     // check if something is selected
2620     if (selection->isEmpty()) {
2621         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2622         return;
2623     }
2625     sp_document_ensure_up_to_date(doc);
2626     NR::Maybe<NR::Rect> r = selection->bounds();
2627     if ( !r || r->isEmpty() ) {
2628         return;
2629     }
2631     // calculate the transform to be applied to objects to move them to 0,0
2632     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2633     move_p[NR::Y] = -move_p[NR::Y];
2634     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2636     GSList *items = g_slist_copy((GSList *) selection->itemList());
2638     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2640     // bottommost object, after sorting
2641     SPObject *parent = SP_OBJECT_PARENT (items->data);
2643     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2645     // remember the position of the first item
2646     gint pos = SP_OBJECT_REPR (items->data)->position();
2648     // create a list of duplicates
2649     GSList *repr_copies = NULL;
2650     for (GSList *i = items; i != NULL; i = i->next) {
2651         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2652         repr_copies = g_slist_prepend (repr_copies, dup);
2653     }
2654     // restore the z-order after prepends
2655     repr_copies = g_slist_reverse (repr_copies);
2657     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2659     if (apply) {
2660         // delete objects so that their clones don't get alerted; this object will be restored shortly
2661         for (GSList *i = items; i != NULL; i = i->next) {
2662             SPObject *item = SP_OBJECT (i->data);
2663             item->deleteObject (false);
2664         }
2665     }
2667     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2668     // without disturbing clones.
2669     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2670     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2671     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2673     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2674                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2675                                                                                             r->max()[NR::Y]))))
2676                                          * parent_transform.inverse() ),
2677                                        parent_transform * move);
2679     // restore compensation setting
2680     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2682     if (apply) {
2683         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2684         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2686         NR::Point min = bounds.min() * parent_transform.inverse();
2687         NR::Point max = bounds.max() * parent_transform.inverse();
2689         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2690         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2691         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2692         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2694         // restore parent and position
2695         SP_OBJECT_REPR (parent)->appendChild(rect);
2696         rect->setPosition(pos > 0 ? pos : 0);
2697         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2699         Inkscape::GC::release(rect);
2701         selection->clear();
2702         selection->set(rectangle);
2703     }
2705     g_slist_free (items);
2707     sp_document_done (doc, SP_VERB_EDIT_TILE,
2708                       _("Objects to pattern"));
2711 void
2712 sp_selection_untile()
2714     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2715     if (desktop == NULL)
2716         return;
2718     SPDocument *doc = sp_desktop_document(desktop);
2719     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2721     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2723     // check if something is selected
2724     if (selection->isEmpty()) {
2725         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2726         return;
2727     }
2729     GSList *new_select = NULL;
2731     bool did = false;
2733     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2734          items != NULL;
2735          items = items->next) {
2737         SPItem *item = (SPItem *) items->data;
2739         SPStyle *style = SP_OBJECT_STYLE (item);
2741         if (!style || !style->fill.isPaintserver())
2742             continue;
2744         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2746         if (!SP_IS_PATTERN(server))
2747             continue;
2749         did = true;
2751         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2753         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2754         pat_transform *= item->transform;
2756         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2757             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2758             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2760            // FIXME: relink clones to the new canvas objects
2761            // use SPObject::setid when mental finishes it to steal ids of
2763             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2764             sp_document_ensure_up_to_date (doc);
2766             NR::Matrix transform( i->transform * pat_transform );
2767             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2769             new_select = g_slist_prepend(new_select, i);
2770         }
2772         SPCSSAttr *css = sp_repr_css_attr_new ();
2773         sp_repr_css_set_property (css, "fill", "none");
2774         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2775     }
2777     if (!did) {
2778         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2779     } else {
2780         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2781                          _("Pattern to objects"));
2782         selection->setList(new_select);
2783     }
2786 void
2787 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2789     if (selection->isEmpty()) {
2790         return;
2791     }
2793     GSList const *reprlst = selection->reprList();
2794     bool filename_search = TRUE;
2795     bool xdpi_search = TRUE;
2796     bool ydpi_search = TRUE;
2798     for(; reprlst != NULL &&
2799             filename_search &&
2800             xdpi_search &&
2801             ydpi_search;
2802         reprlst = reprlst->next) {
2803         gchar const *dpi_string;
2804         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2806         if (filename_search) {
2807             *filename = repr->attribute("inkscape:export-filename");
2808             if (*filename != NULL)
2809                 filename_search = FALSE;
2810         }
2812         if (xdpi_search) {
2813             dpi_string = NULL;
2814             dpi_string = repr->attribute("inkscape:export-xdpi");
2815             if (dpi_string != NULL) {
2816                 *xdpi = atof(dpi_string);
2817                 xdpi_search = FALSE;
2818             }
2819         }
2821         if (ydpi_search) {
2822             dpi_string = NULL;
2823             dpi_string = repr->attribute("inkscape:export-ydpi");
2824             if (dpi_string != NULL) {
2825                 *ydpi = atof(dpi_string);
2826                 ydpi_search = FALSE;
2827             }
2828         }
2829     }
2832 void
2833 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2835     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2836     gchar const *dpi_string;
2838     *filename = repr->attribute("inkscape:export-filename");
2840     dpi_string = NULL;
2841     dpi_string = repr->attribute("inkscape:export-xdpi");
2842     if (dpi_string != NULL) {
2843         *xdpi = atof(dpi_string);
2844     }
2846     dpi_string = NULL;
2847     dpi_string = repr->attribute("inkscape:export-ydpi");
2848     if (dpi_string != NULL) {
2849         *ydpi = atof(dpi_string);
2850     }
2853 void
2854 sp_selection_create_bitmap_copy ()
2856     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2857     if (desktop == NULL)
2858         return;
2860     SPDocument *document = sp_desktop_document(desktop);
2861     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2863     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2865     // check if something is selected
2866     if (selection->isEmpty()) {
2867         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2868         return;
2869     }
2871     // Get the bounding box of the selection
2872     NRRect bbox;
2873     sp_document_ensure_up_to_date (document);
2874     selection->bounds(&bbox);
2875     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2876         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2877     }
2879     // List of the items to show; all others will be hidden
2880     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2882     // Sort items so that the topmost comes last
2883     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2885     // Generate a random value from the current time (you may create bitmap from the same object(s)
2886     // multiple times, and this is done so that they don't clash)
2887     GTimeVal cu;
2888     g_get_current_time (&cu);
2889     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2891     // Create the filename
2892     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2893     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2894     // digits, and a few other chars, with "_"
2895     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2896     // Build the complete path by adding document->base if set
2897     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2899     //g_print ("%s\n", filepath);
2901     // Remember parent and z-order of the topmost one
2902     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2903     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2904     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2906     // Calculate resolution
2907     double res;
2908     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2909     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2910     if (0 < prefs_res) {
2911         // If it's given explicitly in prefs, take it
2912         res = prefs_res;
2913     } else if (0 < prefs_min) {
2914         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2915         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2916     } else {
2917         float hint_xdpi = 0, hint_ydpi = 0;
2918         char const *hint_filename;
2919         // take resolution hint from the selected objects
2920         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2921         if (hint_xdpi != 0) {
2922             res = hint_xdpi;
2923         } else {
2924             // take resolution hint from the document
2925             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2926             if (hint_xdpi != 0) {
2927                 res = hint_xdpi;
2928             } else {
2929                 // if all else fails, take the default 90 dpi
2930                 res = PX_PER_IN;
2931             }
2932         }
2933     }
2935     // The width and height of the bitmap in pixels
2936     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2937     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2939     // Find out if we have to run a filter
2940     gchar const *run = NULL;
2941     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2942     if (filter) {
2943         // filter command is given;
2944         // see if we have a parameter to pass to it
2945         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2946         if (param1) {
2947             if (param1[strlen(param1) - 1] == '%') {
2948                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2949                 gchar p1[256];
2950                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2951                 // the first param is always the image filename, the second is param1
2952                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2953             } else {
2954                 // otherwise pass the param1 unchanged
2955                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2956             }
2957         } else {
2958             // run without extra parameter
2959             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2960         }
2961     }
2963     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2964     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2965     NR::Matrix t;
2967     double shift_x = bbox.x0;
2968     double shift_y = bbox.y1;
2969     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2970         shift_x = round (shift_x);
2971         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2972     }
2973     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2975     // Do the export
2976     sp_export_png_file(document, filepath,
2977                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2978                    width, height, res, res,
2979                    (guint32) 0xffffff00,
2980                    NULL, NULL,
2981                    true,  /*bool force_overwrite,*/
2982                    items);
2984     g_slist_free (items);
2986     // Run filter, if any
2987     if (run) {
2988         g_print ("Running external filter: %s\n", run);
2989         system (run);
2990     }
2992     // Import the image back
2993     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2994     if (pb) {
2995         // Create the repr for the image
2996         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2997         repr->setAttribute("xlink:href", filename);
2998         repr->setAttribute("sodipodi:absref", filepath);
2999         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
3000             sp_repr_set_svg_double(repr, "width", width);
3001             sp_repr_set_svg_double(repr, "height", height);
3002         } else {
3003             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
3004             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
3005         }
3007         // Write transform
3008         gchar *c=sp_svg_transform_write(t);
3009         repr->setAttribute("transform", c);
3010         g_free(c);
3012         // add the new repr to the parent
3013         parent->appendChild(repr);
3015         // move to the saved position
3016         repr->setPosition(pos > 0 ? pos + 1 : 1);
3018         // Set selection to the new image
3019         selection->clear();
3020         selection->add(repr);
3022         // Clean up
3023         Inkscape::GC::release(repr);
3024         gdk_pixbuf_unref (pb);
3026         // Complete undoable transaction
3027         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
3028                           _("Create bitmap"));
3029     }
3031     g_free (filename);
3032     g_free (filepath);
3035 /**
3036  * \brief sp_selection_set_mask
3037  *
3038  * This function creates a mask or clipPath from selection
3039  * Two different modes:
3040  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
3041  *       and is applied to current layer
3042  *  otherwise, topmost object is used as mask for other objects
3043  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
3044  *
3045  */
3046 void
3047 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
3049     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3050     if (desktop == NULL)
3051         return;
3053     SPDocument *doc = sp_desktop_document(desktop);
3054     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3056     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3058     // check if something is selected
3059     bool is_empty = selection->isEmpty();
3060     if ( apply_to_layer && is_empty) {
3061         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
3062         return;
3063     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
3064         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
3065         return;
3066     }
3068     // FIXME: temporary patch to prevent crash!
3069     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
3070     bool clone_with_original = selection_contains_both_clone_and_original (selection);
3071     if (clone_with_original) {
3072         return; // in this version, you cannot clip/mask an object with its own clone
3073     }
3074     // /END FIXME
3076     sp_document_ensure_up_to_date(doc);
3078     GSList *items = g_slist_copy((GSList *) selection->itemList());
3080     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
3082     // create a list of duplicates
3083     GSList *mask_items = NULL;
3084     GSList *apply_to_items = NULL;
3085     GSList *items_to_delete = NULL;
3086     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
3087     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3089     if (apply_to_layer) {
3090         // all selected items are used for mask, which is applied to a layer
3091         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
3093         for (GSList *i = items; i != NULL; i = i->next) {
3094             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3095             mask_items = g_slist_prepend (mask_items, dup);
3097             if (remove_original) {
3098                 SPObject *item = SP_OBJECT (i->data);
3099                 items_to_delete = g_slist_prepend (items_to_delete, item);
3100             }
3101         }
3102     } else if (!topmost) {
3103         // topmost item is used as a mask, which is applied to other items in a selection
3104         GSList *i = items;
3105         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3106         mask_items = g_slist_prepend (mask_items, dup);
3108         if (remove_original) {
3109             SPObject *item = SP_OBJECT (i->data);
3110             items_to_delete = g_slist_prepend (items_to_delete, item);
3111         }
3113         for (i = i->next; i != NULL; i = i->next) {
3114             apply_to_items = g_slist_prepend (apply_to_items, i->data);
3115         }
3116     } else {
3117         GSList *i = NULL;
3118         for (i = items; NULL != i->next; i = i->next) {
3119             apply_to_items = g_slist_prepend (apply_to_items, i->data);
3120         }
3122         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
3123         mask_items = g_slist_prepend (mask_items, dup);
3125         if (remove_original) {
3126             SPObject *item = SP_OBJECT (i->data);
3127             items_to_delete = g_slist_prepend (items_to_delete, item);
3128         }
3129     }
3131     g_slist_free (items);
3132     items = NULL;
3134     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3135     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
3136         SPItem *item = reinterpret_cast<SPItem *>(i->data);
3137         // inverted object transform should be applied to a mask object,
3138         // as mask is calculated in user space (after applying transform)
3139         NR::Matrix maskTransform (item->transform.inverse());
3141         GSList *mask_items_dup = NULL;
3142         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
3143             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
3144             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
3145         }
3147         gchar const *mask_id = NULL;
3148         if (apply_clip_path) {
3149             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
3150         } else {
3151             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
3152         }
3154         g_slist_free (mask_items_dup);
3155         mask_items_dup = NULL;
3157         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3158     }
3160     g_slist_free (mask_items);
3161     g_slist_free (apply_to_items);
3163     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3164         SPObject *item = SP_OBJECT (i->data);
3165         item->deleteObject (false);
3166     }
3167     g_slist_free (items_to_delete);
3169     if (apply_clip_path)
3170         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3171     else
3172         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3175 void sp_selection_unset_mask(bool apply_clip_path) {
3176     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3177     if (desktop == NULL)
3178         return;
3180     SPDocument *doc = sp_desktop_document(desktop);
3181     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3182     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3184     // check if something is selected
3185     if (selection->isEmpty()) {
3186         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3187         return;
3188     }
3190     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3191     sp_document_ensure_up_to_date(doc);
3193     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3194     std::map<SPObject*,SPItem*> referenced_objects;
3195     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3196         if (remove_original) {
3197             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3198             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3199             Inkscape::URIReference *uri_ref = NULL;
3201             if (apply_clip_path) {
3202                 uri_ref = item->clip_ref;
3203             } else {
3204                 uri_ref = item->mask_ref;
3205             }
3207             // collect distinct mask object (and associate with item to apply transform)
3208             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3209                 referenced_objects[uri_ref->getObject()] = item;
3210             }
3211         }
3213         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3214     }
3216     // restore mask objects into a document
3217     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3218         SPObject *obj = (*it).first;
3219         GSList *items_to_move = NULL;
3220         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3221             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3222             items_to_move = g_slist_prepend (items_to_move, copy);
3223         }
3225         if (!obj->isReferenced()) {
3226             // delete from defs if no other object references this mask
3227             obj->deleteObject(false);
3228         }
3230         // remember parent and position of the item to which the clippath/mask was applied
3231         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3232         gint pos = SP_OBJECT_REPR((*it).second)->position();
3234         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3235             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3237             // insert into parent, restore pos
3238             parent->appendChild(repr);
3239             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3241             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
3242             selection->add(repr);
3244             // transform mask, so it is moved the same spot where mask was applied
3245             NR::Matrix transform (mask_item->transform);
3246             transform *= (*it).second->transform;
3247             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3248         }
3250         g_slist_free (items_to_move);
3251     }
3253     if (apply_clip_path)
3254         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3255     else
3256         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3259 void fit_canvas_to_selection(SPDesktop *desktop) {
3260     g_return_if_fail(desktop != NULL);
3261     SPDocument *doc = sp_desktop_document(desktop);
3263     g_return_if_fail(doc != NULL);
3264     g_return_if_fail(desktop->selection != NULL);
3266     if (desktop->selection->isEmpty()) {
3267         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3268         return;
3269     }
3270     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
3271     if (bbox && !bbox->isEmpty()) {
3272         doc->fitToRect(*bbox);
3273     }
3274 };
3276 void fit_canvas_to_drawing(SPDocument *doc) {
3277     g_return_if_fail(doc != NULL);
3279     sp_document_ensure_up_to_date(doc);
3280     SPItem const *const root = SP_ITEM(doc->root);
3281     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
3282     if (bbox && !bbox->isEmpty()) {
3283         doc->fitToRect(*bbox);
3284     }
3285 };
3287 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3288     g_return_if_fail(desktop != NULL);
3289     SPDocument *doc = sp_desktop_document(desktop);
3291     g_return_if_fail(doc != NULL);
3292     g_return_if_fail(desktop->selection != NULL);
3294     if (desktop->selection->isEmpty()) {
3295         fit_canvas_to_drawing(doc);
3296     } else {
3297         fit_canvas_to_selection(desktop);
3298     }
3300     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
3301                      _("Fit page to selection"));
3302 };
3304 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3305     // don't operate on layers
3306     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3307         f(SP_ITEM(root), desktop);
3308     }
3309     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3310         //don't recurse into locked layers
3311         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3312             itemtree_map(f, iter, desktop);
3313         }
3314     }
3317 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3318     if (item->isLocked()) {
3319         item->setLocked(FALSE);
3320     }
3323 static void unhide(SPItem *item, SPDesktop *desktop) {
3324     if (desktop->itemIsHidden(item)) {
3325         item->setExplicitlyHidden(FALSE);
3326     }
3329 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3330     if (!dt) return;
3332     SPObject *root;
3333     if (layer_only) {
3334         root = dt->currentLayer();
3335     } else {
3336         root = dt->currentRoot();
3337     }
3339     itemtree_map(f, root, dt);
3342 void unlock_all(SPDesktop *dt) {
3343     process_all(&unlock, dt, true);
3346 void unlock_all_in_all_layers(SPDesktop *dt) {
3347     process_all(&unlock, dt, false);
3350 void unhide_all(SPDesktop *dt) {
3351     process_all(&unhide, dt, true);
3354 void unhide_all_in_all_layers(SPDesktop *dt) {
3355     process_all(&unhide, dt, false);
3359 GSList * sp_selection_get_clipboard() {
3360     return clipboard;
3364 /*
3365   Local Variables:
3366   mode:c++
3367   c-file-style:"stroustrup"
3368   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3369   indent-tabs-mode:nil
3370   fill-column:99
3371   End:
3372 */
3373 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :