Code

Slightly more 'object-oriented' way to invoke item-specific conversion-to-guides...
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-tref.h"
39 #include "sp-flowtext.h"
40 #include "sp-flowregion.h"
41 #include "text-editing.h"
42 #include "text-context.h"
43 #include "connector-context.h"
44 #include "sp-path.h"
45 #include "sp-conn-end.h"
46 #include "dropper-context.h"
47 #include <glibmm/i18n.h>
48 #include "libnr/nr-matrix-rotate-ops.h"
49 #include "libnr/nr-matrix-translate-ops.h"
50 #include "libnr/nr-rotate-fns.h"
51 #include "libnr/nr-scale-ops.h"
52 #include "libnr/nr-scale-translate-ops.h"
53 #include "libnr/nr-translate-matrix-ops.h"
54 #include "libnr/nr-translate-scale-ops.h"
55 #include "xml/repr.h"
56 #include "style.h"
57 #include "document-private.h"
58 #include "sp-gradient.h"
59 #include "sp-gradient-reference.h"
60 #include "sp-linear-gradient-fns.h"
61 #include "sp-pattern.h"
62 #include "sp-radial-gradient-fns.h"
63 #include "sp-namedview.h"
64 #include "prefs-utils.h"
65 #include "sp-offset.h"
66 #include "sp-clippath.h"
67 #include "sp-mask.h"
68 #include "file.h"
69 #include "helper/png-write.h"
70 #include "layer-fns.h"
71 #include "context-fns.h"
72 #include <map>
73 #include "helper/units.h"
74 #include "sp-item.h"
75 #include "box3d.h"
76 #include "unit-constants.h"
77 #include "xml/simple-document.h"
78 #include "sp-filter-reference.h"
79 #include "gradient-drag.h"
80 #include "uri-references.h"
81 #include "live_effects/lpeobject.h"
83 using NR::X;
84 using NR::Y;
86 #include "selection-chemistry.h"
88 /* fixme: find a better place */
89 Inkscape::XML::Document *clipboard_document = NULL;
90 GSList *clipboard = NULL;
91 GSList *defs_clipboard = NULL;
92 SPCSSAttr *style_clipboard = NULL;
93 NR::Maybe<NR::Rect> size_clipboard;
95 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc);
97 /**
98  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
99  * then prepends the copy to 'clip'.
100  */
101 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
103     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
105     // copy complete inherited style
106     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
107     sp_repr_css_set(copy, css, "style");
108     sp_repr_css_attr_unref(css);
110     // write the complete accumulated transform passed to us
111     // (we're dealing with unattached repr, so we write to its attr
112     // instead of using sp_item_set_transform)
113     gchar *affinestr=sp_svg_transform_write(full_t);
114     copy->setAttribute("transform", affinestr);
115     g_free(affinestr);
117     *clip = g_slist_prepend(*clip, copy);
120 void sp_selection_copy_impl (GSList const *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
123     // Copy stuff referenced by all items to defs_clip:
124     if (defs_clip) {
125         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
126             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
127         }
128         *defs_clip = g_slist_reverse(*defs_clip);
129     }
131     // Store style:
132     if (style_clip) {
133         SPItem *item = SP_ITEM (items->data); // take from the first selected item
134         *style_clip = take_style_from_item (item);
135     }
137     if (clip) {
138         // Sort items:
139         GSList *sorted_items = g_slist_copy ((GSList *) items);
140         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
142         // Copy item reprs:
143         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
144             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
145         }
147         *clip = g_slist_reverse(*clip);
148         g_slist_free ((GSList *) sorted_items);
149     }
152 /**
153  * Add gradients/patterns/markers referenced by copied objects to defs.
154  * Iterates through 'defs_clip', and for each item it adds the data
155  * repr into the global defs.
156  */
157 void
158 paste_defs (GSList **defs_clip, SPDocument *doc)
160     if (!defs_clip)
161         return;
163     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
164         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
165         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
166         gchar const *id = repr->attribute("id");
167         if (!id || !doc->getObjectById(id)) {
168             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
169             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
170             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
171             Inkscape::GC::release(copy);
172         }
173     }
176 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
178     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
179     paste_defs (defs_clip, doc);
181     GSList *copied = NULL;
182     // add objects to document
183     for (GSList *l = *clip; l != NULL; l = l->next) {
184         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
185         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
187         // premultiply the item transform by the accumulated parent transform in the paste layer
188         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
189         if (!local.test_identity()) {
190             gchar const *t_str = copy->attribute("transform");
191             NR::Matrix item_t (NR::identity());
192             if (t_str)
193                 sp_svg_transform_read(t_str, &item_t);
194             item_t *= local.inverse();
195             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
196             gchar *affinestr=sp_svg_transform_write(item_t);
197             copy->setAttribute("transform", affinestr);
198             g_free(affinestr);
199         }
201         parent->appendChildRepr(copy);
202         copied = g_slist_prepend(copied, copy);
203         Inkscape::GC::release(copy);
204     }
205     return copied;
208 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
210     for (GSList const *i = items ; i ; i = i->next ) {
211         sp_object_ref((SPObject *)i->data, NULL);
212     }
213     for (GSList const *i = items; i != NULL; i = i->next) {
214         SPItem *item = (SPItem *) i->data;
215         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
216         sp_object_unref((SPObject *)item, NULL);
217     }
221 void sp_selection_delete()
223     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
224     if (desktop == NULL) {
225         return;
226     }
228     if (tools_isactive (desktop, TOOLS_TEXT))
229         if (sp_text_delete_selection(desktop->event_context)) {
230             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
231                              _("Delete text"));
232             return;
233         }
235     Inkscape::Selection *selection = sp_desktop_selection(desktop);
237     // check if something is selected
238     if (selection->isEmpty()) {
239         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
240         return;
241     }
243     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
244     selection->clear();
245     sp_selection_delete_impl (selected);
246     g_slist_free ((GSList *) selected);
248     /* a tool may have set up private information in it's selection context
249      * that depends on desktop items.  I think the only sane way to deal with
250      * this currently is to reset the current tool, which will reset it's
251      * associated selection context.  For example: deleting an object
252      * while moving it around the canvas.
253      */
254     tools_switch ( desktop, tools_active ( desktop ) );
256     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
257                      _("Delete"));
260 /* fixme: sequencing */
261 void sp_selection_duplicate()
263     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
264     if (desktop == NULL)
265         return;
267     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
268     Inkscape::Selection *selection = sp_desktop_selection(desktop);
270     // check if something is selected
271     if (selection->isEmpty()) {
272         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
273         return;
274     }
276     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
278     selection->clear();
280     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
281     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
283     GSList *newsel = NULL;
285     while (reprs) {
286         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
287         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
289         parent->appendChild(copy);
291         newsel = g_slist_prepend(newsel, copy);
292         reprs = g_slist_remove(reprs, reprs->data);
293         Inkscape::GC::release(copy);
294     }
296     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
297                      _("Duplicate"));
299     selection->setReprList(newsel);
301     g_slist_free(newsel);
304 void sp_edit_clear_all()
306     SPDesktop *dt = SP_ACTIVE_DESKTOP;
307     if (!dt)
308         return;
310     SPDocument *doc = sp_desktop_document(dt);
311     sp_desktop_selection(dt)->clear();
313     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
314     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
316     while (items) {
317         SP_OBJECT (items->data)->deleteObject();
318         items = g_slist_remove(items, items->data);
319     }
321     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
322                      _("Delete all"));
325 GSList *
326 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
328     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
329         if (SP_IS_ITEM(child) &&
330             !desktop->isLayer(SP_ITEM(child)) &&
331             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
332             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
333             (!exclude || !g_slist_find ((GSList *) exclude, child))
334             )
335         {
336             list = g_slist_prepend (list, SP_ITEM(child));
337         }
339         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
340             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
341         }
342     }
344     return list;
347 void sp_edit_select_all_full (bool force_all_layers, bool invert)
349     SPDesktop *dt = SP_ACTIVE_DESKTOP;
350     if (!dt)
351         return;
353     Inkscape::Selection *selection = sp_desktop_selection(dt);
355     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
357     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
358     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
359     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
361     GSList *items = NULL;
363     GSList const *exclude = NULL;
364     if (invert) {
365         exclude = selection->itemList();
366     }
368     if (force_all_layers)
369         inlayer = PREFS_SELECTION_ALL;
371     switch (inlayer) {
372         case PREFS_SELECTION_LAYER: {
373         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
374              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
375         return;
377         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
379         for (GSList *i = all_items; i; i = i->next) {
380             SPItem *item = SP_ITEM (i->data);
382             if (item && (!onlysensitive || !item->isLocked())) {
383                 if (!onlyvisible || !dt->itemIsHidden(item)) {
384                     if (!dt->isLayer(item)) {
385                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
386                             items = g_slist_prepend (items, item); // leave it in the list
387                         }
388                     }
389                 }
390             }
391         }
393         g_slist_free (all_items);
394             break;
395         }
396         case PREFS_SELECTION_LAYER_RECURSIVE: {
397             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
398             break;
399         }
400         default: {
401         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
402             break;
403     }
404     }
406     selection->setList (items);
408     if (items) {
409         g_slist_free (items);
410     }
413 void sp_edit_select_all ()
415     sp_edit_select_all_full (false, false);
418 void sp_edit_select_all_in_all_layers ()
420     sp_edit_select_all_full (true, false);
423 void sp_edit_invert ()
425     sp_edit_select_all_full (false, true);
428 void sp_edit_invert_in_all_layers ()
430     sp_edit_select_all_full (true, true);
433 void sp_selection_group()
435     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
436     if (desktop == NULL)
437         return;
439     SPDocument *doc = sp_desktop_document (desktop);
440     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
442     Inkscape::Selection *selection = sp_desktop_selection(desktop);
444     // Check if something is selected.
445     if (selection->isEmpty()) {
446         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
447         return;
448     }
450     GSList const *l = (GSList *) selection->reprList();
452     GSList *p = g_slist_copy((GSList *) l);
454     selection->clear();
456     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
458     // Remember the position and parent of the topmost object.
459     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
460     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
462     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
464     while (p) {
465         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
467         if (current->parent() == topmost_parent) {
468             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
469             sp_repr_unparent(current);
470             group->appendChild(spnew);
471             Inkscape::GC::release(spnew);
472             topmost --; // only reduce count for those items deleted from topmost_parent
473         } else { // move it to topmost_parent first
474                 GSList *temp_clip = NULL;
476                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
477                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
478                 gchar const *t_str = current->attribute("transform");
479                 NR::Matrix item_t (NR::identity());
480                 if (t_str)
481                     sp_svg_transform_read(t_str, &item_t);
482                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
483                 //FIXME: when moving both clone and original from a transformed group (either by
484                 //grouping into another parent, or by cut/paste) the transform from the original's
485                 //parent becomes embedded into original itself, and this affects its clones. Fix
486                 //this by remembering the transform diffs we write to each item into an array and
487                 //then, if this is clone, looking up its original in that array and pre-multiplying
488                 //it by the inverse of that original's transform diff.
490                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
491                 sp_repr_unparent(current);
493                 // paste into topmost_parent (temporarily)
494                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
495                 if (temp_clip) g_slist_free (temp_clip);
496                 if (copied) { // if success,
497                     // take pasted object (now in topmost_parent)
498                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
499                     // make a copy
500                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
501                     // remove pasted
502                     sp_repr_unparent(in_topmost);
503                     // put its copy into group
504                     group->appendChild(spnew);
505                     Inkscape::GC::release(spnew);
506                     g_slist_free (copied);
507                 }
508         }
509         p = g_slist_remove(p, current);
510     }
512     // Add the new group to the topmost members' parent
513     topmost_parent->appendChild(group);
515     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
516     group->setPosition(topmost + 1);
518     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
519                      _("Group"));
521     selection->set(group);
522     Inkscape::GC::release(group);
525 void sp_selection_ungroup()
527     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
528     if (desktop == NULL)
529         return;
531     Inkscape::Selection *selection = sp_desktop_selection(desktop);
533     if (selection->isEmpty()) {
534         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
535         return;
536     }
538     GSList *items = g_slist_copy((GSList *) selection->itemList());
539     selection->clear();
541     // Get a copy of current selection.
542     GSList *new_select = NULL;
543     bool ungrouped = false;
544     for (GSList *i = items;
545          i != NULL;
546          i = i->next)
547     {
548         SPItem *group = (SPItem *) i->data;
550         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
551         if (!SP_IS_OBJECT(group)) {
552             continue;
553         }
555         /* We do not allow ungrouping <svg> etc. (lauris) */
556         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
557             // keep the non-group item in the new selection
558             selection->add(group);
559             continue;
560         }
562         GSList *children = NULL;
563         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
564         sp_item_group_ungroup(SP_GROUP(group), &children, false);
565         ungrouped = true;
566         // Add ungrouped items to the new selection.
567         new_select = g_slist_concat(new_select, children);
568     }
570     if (new_select) { // Set new selection.
571         selection->addList(new_select);
572         g_slist_free(new_select);
573     }
574     if (!ungrouped) {
575         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
576     }
578     g_slist_free(items);
580     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
581                      _("Ungroup"));
584 static SPGroup *
585 sp_item_list_common_parent_group(GSList const *items)
587     if (!items) {
588         return NULL;
589     }
590     SPObject *parent = SP_OBJECT_PARENT(items->data);
591     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
592     if (!SP_IS_GROUP(parent)) {
593         return NULL;
594     }
595     for (items = items->next; items; items = items->next) {
596         if (SP_OBJECT_PARENT(items->data) != parent) {
597             return NULL;
598         }
599     }
601     return SP_GROUP(parent);
604 /** Finds out the minimum common bbox of the selected items. */
605 static NR::Maybe<NR::Rect>
606 enclose_items(GSList const *items)
608     g_assert(items != NULL);
610     NR::Maybe<NR::Rect> r = NR::Nothing();
611     for (GSList const *i = items; i; i = i->next) {
612         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
613     }
614     return r;
617 SPObject *
618 prev_sibling(SPObject *child)
620     SPObject *parent = SP_OBJECT_PARENT(child);
621     if (!SP_IS_GROUP(parent)) {
622         return NULL;
623     }
624     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
625         if (i->next == child)
626             return i;
627     }
628     return NULL;
631 void
632 sp_selection_raise()
634     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
635     if (!desktop)
636         return;
638     Inkscape::Selection *selection = sp_desktop_selection(desktop);
640     GSList const *items = (GSList *) selection->itemList();
641     if (!items) {
642         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
643         return;
644     }
646     SPGroup const *group = sp_item_list_common_parent_group(items);
647     if (!group) {
648         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
649         return;
650     }
652     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
654     /* Construct reverse-ordered list of selected children. */
655     GSList *rev = g_slist_copy((GSList *) items);
656     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
658     // Determine the common bbox of the selected items.
659     NR::Maybe<NR::Rect> selected = enclose_items(items);
661     // Iterate over all objects in the selection (starting from top).
662     if (selected) {
663         while (rev) {
664             SPObject *child = SP_OBJECT(rev->data);
665             // for each selected object, find the next sibling
666             for (SPObject *newref = child->next; newref; newref = newref->next) {
667                 // if the sibling is an item AND overlaps our selection,
668                 if (SP_IS_ITEM(newref)) {
669                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
670                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
671                         // AND if it's not one of our selected objects,
672                         if (!g_slist_find((GSList *) items, newref)) {
673                             // move the selected object after that sibling
674                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
675                         }
676                         break;
677                     }
678                 }
679             }
680             rev = g_slist_remove(rev, child);
681         }
682     } else {
683         g_slist_free(rev);
684     }
686     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
687                      _("Raise"));
690 void sp_selection_raise_to_top()
692     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
693     if (desktop == NULL)
694         return;
696     SPDocument *document = sp_desktop_document(desktop);
697     Inkscape::Selection *selection = sp_desktop_selection(desktop);
699     if (selection->isEmpty()) {
700         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
701         return;
702     }
704     GSList const *items = (GSList *) selection->itemList();
706     SPGroup const *group = sp_item_list_common_parent_group(items);
707     if (!group) {
708         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
709         return;
710     }
712     GSList *rl = g_slist_copy((GSList *) selection->reprList());
713     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
715     for (GSList *l = rl; l != NULL; l = l->next) {
716         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
717         repr->setPosition(-1);
718     }
720     g_slist_free(rl);
722     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
723                      _("Raise to top"));
726 void
727 sp_selection_lower()
729     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
730     if (desktop == NULL)
731         return;
733     Inkscape::Selection *selection = sp_desktop_selection(desktop);
735     GSList const *items = (GSList *) selection->itemList();
736     if (!items) {
737         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
738         return;
739     }
741     SPGroup const *group = sp_item_list_common_parent_group(items);
742     if (!group) {
743         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
744         return;
745     }
747     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
749     // Determine the common bbox of the selected items.
750     NR::Maybe<NR::Rect> selected = enclose_items(items);
752     /* Construct direct-ordered list of selected children. */
753     GSList *rev = g_slist_copy((GSList *) items);
754     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
755     rev = g_slist_reverse(rev);
757     // Iterate over all objects in the selection (starting from top).
758     if (selected) {
759         while (rev) {
760             SPObject *child = SP_OBJECT(rev->data);
761             // for each selected object, find the prev sibling
762             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
763                 // if the sibling is an item AND overlaps our selection,
764                 if (SP_IS_ITEM(newref)) {
765                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
766                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
767                         // AND if it's not one of our selected objects,
768                         if (!g_slist_find((GSList *) items, newref)) {
769                             // move the selected object before that sibling
770                             SPObject *put_after = prev_sibling(newref);
771                             if (put_after)
772                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
773                             else
774                                 SP_OBJECT_REPR(child)->setPosition(0);
775                         }
776                         break;
777                     }
778                 }
779             }
780             rev = g_slist_remove(rev, child);
781         }
782     } else {
783         g_slist_free(rev);
784     }
786     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
787                      _("Lower"));
790 void sp_selection_lower_to_bottom()
792     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
793     if (desktop == NULL)
794         return;
796     SPDocument *document = sp_desktop_document(desktop);
797     Inkscape::Selection *selection = sp_desktop_selection(desktop);
799     if (selection->isEmpty()) {
800         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
801         return;
802     }
804     GSList const *items = (GSList *) selection->itemList();
806     SPGroup const *group = sp_item_list_common_parent_group(items);
807     if (!group) {
808         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
809         return;
810     }
812     GSList *rl;
813     rl = g_slist_copy((GSList *) selection->reprList());
814     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
815     rl = g_slist_reverse(rl);
817     for (GSList *l = rl; l != NULL; l = l->next) {
818         gint minpos;
819         SPObject *pp, *pc;
820         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
821         pp = document->getObjectByRepr(sp_repr_parent(repr));
822         minpos = 0;
823         g_assert(SP_IS_GROUP(pp));
824         pc = sp_object_first_child(pp);
825         while (!SP_IS_ITEM(pc)) {
826             minpos += 1;
827             pc = pc->next;
828         }
829         repr->setPosition(minpos);
830     }
832     g_slist_free(rl);
834     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
835                      _("Lower to bottom"));
838 void
839 sp_undo(SPDesktop *desktop, SPDocument *)
841         if (!sp_document_undo(sp_desktop_document(desktop)))
842             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
845 void
846 sp_redo(SPDesktop *desktop, SPDocument *)
848         if (!sp_document_redo(sp_desktop_document(desktop)))
849             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
852 void sp_selection_cut()
854     sp_selection_copy();
855     sp_selection_delete();
858 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
860     SPGradient *ref = gradient;
862     while (ref) {
863         // climb up the refs, copying each one in the chain
864         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
865         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
867         ref = ref->ref->getObject();
868     }
871 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
873     SPPattern *ref = pattern;
875     while (ref) {
876         // climb up the refs, copying each one in the chain
877         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
878         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
880         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
881         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
882             if (!SP_IS_ITEM (child))
883                 continue;
884             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
885         }
887         ref = ref->ref->getObject();
888     }
891 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
893     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
894     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
898 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, GSList const *items, Inkscape::XML::Document* xml_doc)
900     SPItem *path = sp_textpath_get_path_item (tp);
901     if (!path)
902         return;
903     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
904         return;
905     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
906     *defs_clip = g_slist_prepend (*defs_clip, repr);
909 /**
910  * Copies things like patterns, markers, gradients, etc.
911  */
912 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc)
914     SPStyle *style = SP_OBJECT_STYLE (item);
916     if (style && (style->fill.isPaintserver())) {
917         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
918         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
919             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
920         if (SP_IS_PATTERN (server))
921             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
922     }
924     if (style && (style->stroke.isPaintserver())) {
925         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
926         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
927             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
928         if (SP_IS_PATTERN (server))
929             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
930     }
932     // For shapes, copy all of the shape's markers into defs_clip
933     if (SP_IS_SHAPE (item)) {
934         SPShape *shape = SP_SHAPE (item);
935         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
936             if (shape->marker[i]) {
937                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
938             }
939         }
941         // For shapes, also copy liveeffect if applicable
942         if (sp_shape_has_path_effect(shape)) {
943             sp_copy_single (defs_clip, SP_OBJECT(sp_shape_get_livepatheffectobject(shape)), xml_doc);
944         }
945     }
947     if (SP_IS_TEXT_TEXTPATH (item)) {
948         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
949     }
951     if (item->clip_ref->getObject()) {
952         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
953     }
955     if (item->mask_ref->getObject()) {
956         SPObject *mask = item->mask_ref->getObject();
957         sp_copy_single (defs_clip, mask, xml_doc);
958         // recurse into the mask for its gradients etc.
959         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
960             if (SP_IS_ITEM(o))
961                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
962         }
963     }
965     if (style->getFilter()) {
966         SPObject *filter = style->getFilter();
967         if (SP_IS_FILTER(filter)) {
968             sp_copy_single (defs_clip, filter, xml_doc);
969         }
970     }
972     // recurse
973     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
974         if (SP_IS_ITEM(o))
975             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
976     }
979 void
980 sp_set_style_clipboard (SPCSSAttr *css)
982     if (css != NULL) {
983         // clear style clipboard
984         if (style_clipboard) {
985             sp_repr_css_attr_unref (style_clipboard);
986             style_clipboard = NULL;
987         }
988         //sp_repr_css_print (css);
989         style_clipboard = css;
990     }
993 /**
994  * \pre item != NULL
995  */
996 SPCSSAttr *
997 take_style_from_item (SPItem *item)
999     // write the complete cascaded style, context-free
1000     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1001     if (css == NULL)
1002         return NULL;
1004     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1005         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1006         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1007         // If this is a group, merge the style of its topmost (last) child with style
1008         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
1009             if (SP_OBJECT_STYLE (last_element) != NULL) {
1010                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
1011                 if (temp) {
1012                     sp_repr_css_merge (css, temp);
1013                     sp_repr_css_attr_unref (temp);
1014                 }
1015                 break;
1016             }
1017         }
1018     }
1019     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
1020         // do not copy text properties from non-text objects, it's confusing
1021         css = sp_css_attr_unset_text (css);
1022     }
1024     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1025     double ex = NR::expansion(sp_item_i2doc_affine(item));
1026     if (ex != 1.0) {
1027         css = sp_css_attr_scale (css, ex);
1028     }
1030     return css;
1034 void sp_selection_copy()
1036     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1037     if (desktop == NULL)
1038         return;
1040     if (!clipboard_document) {
1041         clipboard_document = new Inkscape::XML::SimpleDocument();
1042     }
1044     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1046     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1047         sp_dropper_context_copy(desktop->event_context);
1048         return; // copied color under cursor, nothing else to do
1049     }
1051     if (desktop->event_context->get_drag() && desktop->event_context->get_drag()->copy()) {
1052         return; // copied selected stop(s), nothing else to do
1053     }
1055     // check if something is selected
1056     if (selection->isEmpty()) {
1057         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1058         return;
1059     }
1061     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1063     // 0. Copy text to system clipboard
1064     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1065     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1066     Glib::ustring text;
1067     if (tools_isactive (desktop, TOOLS_TEXT)) {
1068         text = sp_text_get_selected_text(desktop->event_context);
1069     }
1071     if (text.empty()) {
1072         guint texts = 0;
1073         for (GSList *i = (GSList *) items; i; i = i->next) {
1074             SPItem *item = SP_ITEM (i->data);
1075             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1076                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1077                     text += " ";
1078                 gchar *this_text = sp_te_get_string_multiline (item);
1079                 if (this_text) {
1080                     text += this_text;
1081                     g_free(this_text);
1082                 }
1083                 texts++;
1084             }
1085         }
1086     }
1087     if (!text.empty()) {
1088         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1089         refClipboard->set_text(text);
1090     }
1092     // clear old defs clipboard
1093     while (defs_clipboard) {
1094         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1095         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1096     }
1098     // clear style clipboard
1099     if (style_clipboard) {
1100         sp_repr_css_attr_unref (style_clipboard);
1101         style_clipboard = NULL;
1102     }
1104     //clear main clipboard
1105     while (clipboard) {
1106         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1107         clipboard = g_slist_remove(clipboard, clipboard->data);
1108     }
1110     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1112     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1113         SPStyle *const query = sp_style_new(SP_ACTIVE_DOCUMENT);
1114         if (sp_desktop_query_style_all (desktop, query)) {
1115             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1116             sp_set_style_clipboard (css);
1117         }
1118         sp_style_unref(query);
1119     }
1121     size_clipboard = selection->bounds();
1123     g_slist_free ((GSList *) items);
1126 //____________________________________________________________________________
1128 /** Paste the bitmap in the clipboard if one is in there.
1129         The bitmap is saved to a PNG file then imported into the document
1131         @return true if a bitmap was detected and pasted; false if no bitmap
1132 */
1133 static bool pastedPicFromClipboard()
1135         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1136         SPDocument *doc = SP_ACTIVE_DOCUMENT;
1137         if ( desktop == NULL || doc == NULL)
1138                 return false;
1140         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1141         Glib::RefPtr<Gdk::Pixbuf> pic = refClipboard->wait_for_image();
1143         // Stop if the system clipboard doesn't have a bitmap.
1144         if ( pic == 0 )
1145         {
1146                 return false;
1147         } //if
1148         else
1149         {
1150                 // Write into a file, then import the file into the document.
1151                 // Make a file name based on current time; use the current working dir.
1152                 time_t rawtime;
1153                 char filename[50];
1154                 const char* path;
1156                 time ( &rawtime );
1157                 strftime (filename,50,"pastedpic_%m%d%Y_%H%M%S.png",localtime( &rawtime ));
1158                 path = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1159                 Glib::ustring finalPath = path;
1160                 finalPath.append(G_DIR_SEPARATOR_S).append(filename);
1161                 pic->save( finalPath, "png" );
1162                 file_import(doc, finalPath, NULL);
1164                 // Clear the clipboard so that the bitmap in there won't always over
1165                 // ride the normal inkscape clipboard.This isn't the ideal solution.
1166                 refClipboard->set_text("");
1167                 return true;
1168         } //else
1170         return false;
1171 } //pastedPicFromClipboard
1173 //____________________________________________________________________________
1175 void sp_selection_paste(bool in_place)
1177     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1179     if (desktop == NULL) {
1180         return;
1181     }
1183     SPDocument *document = sp_desktop_document(desktop);
1185     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1186         return;
1187     }
1189     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1191     if (tools_isactive (desktop, TOOLS_TEXT)) {
1192         if (sp_text_paste_inline(desktop->event_context))
1193             return; // pasted from system clipboard into text, nothing else to do
1194     }
1196     // check if something is in the clipboard
1198     // Stop if successfully pasted a clipboard bitmap.
1199     if ( pastedPicFromClipboard() )
1200         return;
1203     if (clipboard == NULL) {
1204         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing in the clipboard."));
1205         return;
1206     }
1208     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1209     // add pasted objects to selection
1210     selection->setReprList((GSList const *) copied);
1211     g_slist_free (copied);
1213     if (!in_place) {
1214         sp_document_ensure_up_to_date(document);
1216         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1217         NR::Point m( desktop->point() );
1218         if (sel_bbox) {
1219             m -= sel_bbox->midpoint();
1220         }
1222         sp_selection_move_relative(selection, m);
1223     }
1225     sp_document_done(document, SP_VERB_EDIT_PASTE, _("Paste"));
1228 void sp_selection_paste_style()
1230     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1231     if (desktop == NULL) return;
1233     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1235     // check if something is in the clipboard
1236     if (style_clipboard == NULL) {
1237         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the style clipboard."));
1238         return;
1239     }
1241     // check if something is selected
1242     if (selection->isEmpty()) {
1243         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1244         return;
1245     }
1247     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1249     sp_desktop_set_style (desktop, style_clipboard);
1251     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1252                      _("Paste style"));
1255 void sp_selection_paste_livepatheffect()
1257     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1258     if (desktop == NULL) return;
1260     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1262     // check if something is in the clipboard
1263     if (clipboard == NULL) {
1264         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1265         return;
1266     }
1268     // check if something is selected
1269     if (selection->isEmpty()) {
1270         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste live path effect to."));
1271         return;
1272     }
1274     SPDocument *doc = sp_desktop_document(desktop);
1275     paste_defs (&defs_clipboard, doc);
1277     Inkscape::XML::Node *repr = (Inkscape::XML::Node *) clipboard->data;
1278     char const *effecturi = repr->attribute("inkscape:path-effect");
1279     if (!effecturi) {
1280         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Clipboard does not contain a live path effect."));
1281         return;
1282     }
1284     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1285         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1286         if ( item && SP_IS_SHAPE(item) ) {
1287             SPShape * shape = SP_SHAPE(item);
1289             // create a private LPE object!
1290             SPObject * obj = sp_uri_reference_resolve(doc, effecturi);
1291             LivePathEffectObject * lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(0);
1292             
1293             sp_shape_set_path_effect(shape, lpeobj);
1295             // set inkscape:original-d for paths. the other shapes don't need this.
1296             if ( SP_IS_PATH(item) ) {
1297                 Inkscape::XML::Node *pathrepr = SP_OBJECT_REPR(item);
1298                 if ( ! pathrepr->attribute("inkscape:original-d") ) {
1299                     pathrepr->setAttribute("inkscape:original-d", pathrepr->attribute("d"));
1300                 }
1301             }
1302         }
1303     }
1305     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1306                      _("Paste live path effect"));
1309 void sp_selection_paste_size (bool apply_x, bool apply_y)
1311     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1312     if (desktop == NULL) return;
1314     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1316     // check if something is in the clipboard
1317     if (!size_clipboard) {
1318         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1319         return;
1320     }
1322     // check if something is selected
1323     if (selection->isEmpty()) {
1324         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1325         return;
1326     }
1328     NR::Maybe<NR::Rect> current = selection->bounds();
1329     if ( !current || current->isEmpty() ) {
1330         return;
1331     }
1333     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1334     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1336     sp_selection_scale_relative (selection, current->midpoint(),
1337                                  NR::scale(
1338                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1339                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1341     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1342                      _("Paste size"));
1345 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
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 ( !size_clipboard ) {
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 size to."));
1361         return;
1362     }
1364     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1365         SPItem *item = SP_ITEM(l->data);
1367         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1368         if ( !current || current->isEmpty() ) {
1369             continue;
1370         }
1372         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1373         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1375         sp_item_scale_rel (item,
1376                                  NR::scale(
1377                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1378                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1380     }
1382     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1383                      _("Paste size separately"));
1386 void sp_selection_to_next_layer ()
1388     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1390     Inkscape::Selection *selection = sp_desktop_selection(dt);
1392     // check if something is selected
1393     if (selection->isEmpty()) {
1394         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1395         return;
1396     }
1398     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1400     bool no_more = false; // Set to true, if no more layers above
1401     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1402     if (next) {
1403         GSList *temp_clip = NULL;
1404         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
1405         sp_selection_delete_impl (items, false, false);
1406         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1407         GSList *copied;
1408         if(next) {
1409             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1410         } else {
1411             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1412             no_more = true;
1413         }
1414         selection->setReprList((GSList const *) copied);
1415         g_slist_free (copied);
1416         if (temp_clip) g_slist_free (temp_clip);
1417         if (next) dt->setCurrentLayer(next);
1418         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1419                          _("Raise to next layer"));
1420     } else {
1421         no_more = true;
1422     }
1424     if (no_more) {
1425         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1426     }
1428     g_slist_free ((GSList *) items);
1431 void sp_selection_to_prev_layer ()
1433     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1435     Inkscape::Selection *selection = sp_desktop_selection(dt);
1437     // check if something is selected
1438     if (selection->isEmpty()) {
1439         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1440         return;
1441     }
1443     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1445     bool no_more = false; // Set to true, if no more layers below
1446     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1447     if (next) {
1448         GSList *temp_clip = NULL;
1449         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
1450         sp_selection_delete_impl (items, false, false);
1451         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1452         GSList *copied;
1453         if(next) {
1454             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1455         } else {
1456             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1457             no_more = true;
1458         }
1459         selection->setReprList((GSList const *) copied);
1460         g_slist_free (copied);
1461         if (temp_clip) g_slist_free (temp_clip);
1462         if (next) dt->setCurrentLayer(next);
1463         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1464                          _("Lower to previous layer"));
1465     } else {
1466         no_more = true;
1467     }
1469     if (no_more) {
1470         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1471     }
1473     g_slist_free ((GSList *) items);
1476 bool
1477 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1479     bool contains_original = false;
1481     bool is_use = SP_IS_USE(item);
1482     SPItem *item_use = item;
1483     SPItem *item_use_first = item;
1484     while (is_use && item_use && !contains_original)
1485     {
1486         item_use = sp_use_get_original (SP_USE(item_use));
1487         contains_original |= selection->includes(item_use);
1488         if (item_use == item_use_first)
1489             break;
1490         is_use = SP_IS_USE(item_use);
1491     }
1493     // If it's a tref, check whether the object containing the character
1494     // data is part of the selection
1495     if (!contains_original && SP_IS_TREF(item)) {
1496         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1497     }
1499     return contains_original;
1503 bool
1504 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1506     bool clone_with_original = false;
1507     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1508         SPItem *item = SP_ITEM(l->data);
1509         clone_with_original |= selection_contains_original(item, selection);
1510         if (clone_with_original)
1511             break;
1512     }
1513     return clone_with_original;
1517 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1518 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1519 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1520 that case, items are already in the new position, but the repr is in the old, and this function
1521 then simply updates the repr from item->transform.
1522  */
1523 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1525     if (selection->isEmpty())
1526         return;
1528     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1529         SPItem *item = SP_ITEM(l->data);
1531         NR::Point old_center(0,0);
1532         if (set_i2d && item->isCenterSet())
1533             old_center = item->getCenter();
1535 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1536          At the time of writing, this is the only place to re-enable. */
1537         sp_item_update_cns(*item, selection->desktop());
1538 #endif
1540         // we're moving both a clone and its original or any ancestor in clone chain?
1541         bool transform_clone_with_original = selection_contains_original(item, selection);
1542         // ...both a text-on-path and its path?
1543         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)))) ));
1544         // ...both a flowtext and its frame?
1545         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)
1546         // ...both an offset and its source?
1547         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1549         // If we're moving a connector, we want to detach it
1550         // from shapes that aren't part of the selection, but
1551         // leave it attached if they are
1552         if (cc_item_is_connector(item)) {
1553             SPItem *attItem[2];
1554             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1556             for (int n = 0; n < 2; ++n) {
1557                 if (!selection->includes(attItem[n])) {
1558                     sp_conn_end_detach(item, n);
1559                 }
1560             }
1561         }
1563         // "clones are unmoved when original is moved" preference
1564         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1565         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1566         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1568         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1569         // transform of its original and respond to it itself. Without this, a clone is doubly
1570         // transformed, very unintuitive.
1571       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1572       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1573       // Same for linked offset if we are also moving its source: do not move it.
1574         if (transform_textpath_with_path || transform_offset_with_source) {
1575                 // restore item->transform field from the repr, in case it was changed by seltrans
1576             sp_object_read_attr (SP_OBJECT (item), "transform");
1578         } else if (transform_flowtext_with_frame) {
1579             // apply the inverse of the region's transform to the <use> so that the flow remains
1580             // the same (even though the output itself gets transformed)
1581             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1582                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1583                     continue;
1584                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1585                     if (!SP_IS_USE(use)) continue;
1586                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1587                 }
1588             }
1589         } else if (transform_clone_with_original) {
1590             // We are transforming a clone along with its original. The below matrix juggling is
1591             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1592             // transform and its move compensation are both cancelled out.
1594             // restore item->transform field from the repr, in case it was changed by seltrans
1595             sp_object_read_attr (SP_OBJECT (item), "transform");
1597             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1598             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1599             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1600             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1601             NR::Matrix result = t_inv * item->transform * t;
1603             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1604                 // we need to cancel out the move compensation, too
1606                 // find out the clone move, same as in sp_use_move_compensate
1607                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1608                 NR::Matrix clone_move = parent.inverse() * t * parent;
1610                 if (prefs_parallel) {
1611                     NR::Matrix move = result * clone_move * t_inv;
1612                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1614                 } else if (prefs_unmoved) {
1615                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1616                     //    clone_move = NR::identity();
1617                     NR::Matrix move = result * clone_move;
1618                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1619                 }
1621             } else {
1622                 // just apply the result
1623                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1624             }
1626         } else {
1627             if (set_i2d) {
1628                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1629             }
1630             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1631         }
1633         // if we're moving the actual object, not just updating the repr, we can transform the
1634         // center by the same matrix (only necessary for non-translations)
1635         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1636             item->setCenter(old_center * affine);
1637             SP_OBJECT(item)->updateRepr();
1638         }
1639     }
1642 void sp_selection_remove_transform()
1644     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1645     if (desktop == NULL)
1646         return;
1648     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1650     GSList const *l = (GSList *) selection->reprList();
1651     while (l != NULL) {
1652         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1653         l = l->next;
1654     }
1656     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1657                      _("Remove transform"));
1660 void
1661 sp_selection_scale_absolute(Inkscape::Selection *selection,
1662                             double const x0, double const x1,
1663                             double const y0, double const y1)
1665     if (selection->isEmpty())
1666         return;
1668     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1669     if ( !bbox || bbox->isEmpty() ) {
1670         return;
1671     }
1673     NR::translate const p2o(-bbox->min());
1675     NR::scale const newSize(x1 - x0,
1676                             y1 - y0);
1677     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1678     NR::translate const o2n(x0, y0);
1679     NR::Matrix const final( p2o * scale * o2n );
1681     sp_selection_apply_affine(selection, final);
1685 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1687     if (selection->isEmpty())
1688         return;
1690     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1692     if ( !bbox || bbox->isEmpty() ) {
1693         return;
1694     }
1696     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1697     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1698          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1699     {
1700         return;
1701     }
1703     NR::translate const n2d(-align);
1704     NR::translate const d2n(align);
1705     NR::Matrix const final( n2d * scale * d2n );
1706     sp_selection_apply_affine(selection, final);
1709 void
1710 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1712     NR::translate const d2n(center);
1713     NR::translate const n2d(-center);
1714     NR::rotate const rotate(rotate_degrees(angle_degrees));
1715     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1716     sp_selection_apply_affine(selection, final);
1719 void
1720 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1722     NR::translate const d2n(align);
1723     NR::translate const n2d(-align);
1724     NR::Matrix const skew(1, dy,
1725                           dx, 1,
1726                           0, 0);
1727     NR::Matrix const final( n2d * skew * d2n );
1728     sp_selection_apply_affine(selection, final);
1731 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1733     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1736 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1738     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1742 /**
1743  * \brief sp_selection_rotate_90
1744  *
1745  * This function rotates selected objects 90 degrees clockwise.
1746  *
1747  */
1749 void sp_selection_rotate_90_cw()
1751     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1753     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1755     if (selection->isEmpty())
1756         return;
1758     GSList const *l = selection->itemList();
1759     NR::rotate const rot_neg_90(NR::Point(0, -1));
1760     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1761         SPItem *item = SP_ITEM(l2->data);
1762         sp_item_rotate_rel(item, rot_neg_90);
1763     }
1765     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1766                      _("Rotate 90&#176; CW"));
1770 /**
1771  * \brief sp_selection_rotate_90_ccw
1772  *
1773  * This function rotates selected objects 90 degrees counter-clockwise.
1774  *
1775  */
1777 void sp_selection_rotate_90_ccw()
1779     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1781     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1783     if (selection->isEmpty())
1784         return;
1786     GSList const *l = selection->itemList();
1787     NR::rotate const rot_neg_90(NR::Point(0, 1));
1788     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1789         SPItem *item = SP_ITEM(l2->data);
1790         sp_item_rotate_rel(item, rot_neg_90);
1791     }
1793     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1794                      _("Rotate 90&#176; CCW"));
1797 void
1798 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1800     if (selection->isEmpty())
1801         return;
1803     NR::Maybe<NR::Point> center = selection->center();
1804     if (!center) {
1805         return;
1806     }
1808     sp_selection_rotate_relative(selection, *center, angle_degrees);
1810     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1811                            ( ( angle_degrees > 0 )
1812                              ? "selector:rotate:ccw"
1813                              : "selector:rotate:cw" ),
1814                            SP_VERB_CONTEXT_SELECT,
1815                            _("Rotate"));
1818 /**
1819 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1820 */
1821 void
1822 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1824     if (selection->isEmpty())
1825         return;
1827     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1828     NR::Maybe<NR::Point> center = selection->center();
1830     if ( !bbox || !center ) {
1831         return;
1832     }
1834     gdouble const zoom = selection->desktop()->current_zoom();
1835     gdouble const zmove = angle / zoom;
1836     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1838     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1840     sp_selection_rotate_relative(selection, *center, zangle);
1842     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1843                            ( (angle > 0)
1844                              ? "selector:rotate:ccw"
1845                              : "selector:rotate:cw" ),
1846                            SP_VERB_CONTEXT_SELECT,
1847                            _("Rotate by pixels"));
1850 void
1851 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1853     if (selection->isEmpty())
1854         return;
1856     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1857     if (!bbox) {
1858         return;
1859     }
1861     NR::Point const center(bbox->midpoint());
1863     // you can't scale "do nizhe pola" (below zero)
1864     double const max_len = bbox->maxExtent();
1865     if ( max_len + grow <= 1e-3 ) {
1866         return;
1867     }
1869     double const times = 1.0 + grow / max_len;
1870     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1872     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1873                            ( (grow > 0)
1874                              ? "selector:scale:larger"
1875                              : "selector:scale:smaller" ),
1876                            SP_VERB_CONTEXT_SELECT,
1877                            _("Scale"));
1880 void
1881 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1883     sp_selection_scale(selection,
1884                        grow_pixels / selection->desktop()->current_zoom());
1887 void
1888 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1890     if (selection->isEmpty())
1891         return;
1893     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1895     if (!sel_bbox) {
1896         return;
1897     }
1899     NR::Point const center(sel_bbox->midpoint());
1900     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1901     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1902                      _("Scale by whole factor"));
1905 void
1906 sp_selection_move(gdouble dx, gdouble dy)
1908     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1909     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1910     if (selection->isEmpty()) {
1911         return;
1912     }
1914     sp_selection_move_relative(selection, dx, dy);
1916     if (dx == 0) {
1917         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1918                                _("Move vertically"));
1919     } else if (dy == 0) {
1920         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1921                                _("Move horizontally"));
1922     } else {
1923         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1924                          _("Move"));
1925     }
1928 void
1929 sp_selection_move_screen(gdouble dx, gdouble dy)
1931     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1933     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1934     if (selection->isEmpty()) {
1935         return;
1936     }
1938     // same as sp_selection_move but divide deltas by zoom factor
1939     gdouble const zoom = desktop->current_zoom();
1940     gdouble const zdx = dx / zoom;
1941     gdouble const zdy = dy / zoom;
1942     sp_selection_move_relative(selection, zdx, zdy);
1944     if (dx == 0) {
1945         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1946                                _("Move vertically by pixels"));
1947     } else if (dy == 0) {
1948         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1949                                _("Move horizontally by pixels"));
1950     } else {
1951         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1952                          _("Move"));
1953     }
1956 namespace {
1958 template <typename D>
1959 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1960                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1962 template <typename D>
1963 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1964                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1966 struct Forward {
1967     typedef SPObject *Iterator;
1969     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1970     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1971     static void dispose(Iterator /*i*/) {}
1973     static SPObject *object(Iterator i) { return i; }
1974     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1975 };
1977 struct Reverse {
1978     typedef GSList *Iterator;
1980     static Iterator children(SPObject *o) {
1981         return make_list(o->firstChild(), NULL);
1982     }
1983     static Iterator siblings_after(SPObject *o) {
1984         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1985     }
1986     static void dispose(Iterator i) {
1987         g_slist_free(i);
1988     }
1990     static SPObject *object(Iterator i) {
1991         return reinterpret_cast<SPObject *>(i->data);
1992     }
1993     static Iterator next(Iterator i) { return i->next; }
1995 private:
1996     static GSList *make_list(SPObject *object, SPObject *limit) {
1997         GSList *list=NULL;
1998         while ( object != limit ) {
1999             list = g_slist_prepend(list, object);
2000             object = SP_OBJECT_NEXT(object);
2001         }
2002         return list;
2003     }
2004 };
2008 void
2009 sp_selection_item_next(void)
2011     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2012     g_return_if_fail(desktop != NULL);
2013     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2015     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2016     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2017     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2019     SPObject *root;
2020     if (PREFS_SELECTION_ALL != inlayer) {
2021         root = selection->activeContext();
2022     } else {
2023         root = desktop->currentRoot();
2024     }
2026     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2028     if (item) {
2029         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2030         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2031             scroll_to_show_item(desktop, item);
2032         }
2033     }
2036 void
2037 sp_selection_item_prev(void)
2039     SPDocument *document = SP_ACTIVE_DOCUMENT;
2040     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2041     g_return_if_fail(document != NULL);
2042     g_return_if_fail(desktop != NULL);
2043     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2045     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2046     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2047     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2049     SPObject *root;
2050     if (PREFS_SELECTION_ALL != inlayer) {
2051         root = selection->activeContext();
2052     } else {
2053         root = desktop->currentRoot();
2054     }
2056     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2058     if (item) {
2059         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2060         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2061             scroll_to_show_item(desktop, item);
2062         }
2063     }
2066 void sp_selection_next_patheffect_param(SPDesktop * dt)
2068     if (!dt) return;
2070     Inkscape::Selection *selection = sp_desktop_selection(dt);
2071     if ( selection && !selection->isEmpty() ) {
2072         SPItem *item = selection->singleItem();
2073         if ( item && SP_IS_SHAPE(item)) {
2074             SPShape *shape = SP_SHAPE(item);
2075             if (sp_shape_has_path_effect(shape)) {
2076                 sp_shape_edit_next_param_oncanvas(shape, dt);
2077             } else {
2078                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
2079             }
2080         }
2081     }
2084 namespace {
2086 template <typename D>
2087 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
2088                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2090     SPObject *current=root;
2091     while (items) {
2092         SPItem *item=SP_ITEM(items->data);
2093         if ( root->isAncestorOf(item) &&
2094              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
2095         {
2096             current = item;
2097             break;
2098         }
2099         items = items->next;
2100     }
2102     GSList *path=NULL;
2103     while ( current != root ) {
2104         path = g_slist_prepend(path, current);
2105         current = SP_OBJECT_PARENT(current);
2106     }
2108     SPItem *next;
2109     // first, try from the current object
2110     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2111     g_slist_free(path);
2113     if (!next) { // if we ran out of objects, start over at the root
2114         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2115     }
2117     return next;
2120 template <typename D>
2121 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2122                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2124     typename D::Iterator children;
2125     typename D::Iterator iter;
2127     SPItem *found=NULL;
2129     if (path) {
2130         SPObject *object=reinterpret_cast<SPObject *>(path->data);
2131         g_assert(SP_OBJECT_PARENT(object) == root);
2132         if (desktop->isLayer(object)) {
2133             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2134         }
2135         iter = children = D::siblings_after(object);
2136     } else {
2137         iter = children = D::children(root);
2138     }
2140     while ( iter && !found ) {
2141         SPObject *object=D::object(iter);
2142         if (desktop->isLayer(object)) {
2143             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
2144                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2145             }
2146         } else if ( SP_IS_ITEM(object) &&
2147                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2148                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2149                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2150                     !desktop->isLayer(SP_ITEM(object)) )
2151         {
2152             found = SP_ITEM(object);
2153         }
2154         iter = D::next(iter);
2155     }
2157     D::dispose(children);
2159     return found;
2164 /**
2165  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2166  * \a item.
2167  */
2168 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2170     NR::Rect dbox = desktop->get_display_area();
2171     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2173     if ( sbox && dbox.contains(*sbox) == false ) {
2174         NR::Point const s_dt = sbox->midpoint();
2175         NR::Point const s_w = desktop->d2w(s_dt);
2176         NR::Point const d_dt = dbox.midpoint();
2177         NR::Point const d_w = desktop->d2w(d_dt);
2178         NR::Point const moved_w( d_w - s_w );
2179         gint const dx = (gint) moved_w[X];
2180         gint const dy = (gint) moved_w[Y];
2181         desktop->scroll_world(dx, dy);
2182     }
2186 void
2187 sp_selection_clone()
2189     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2190     if (desktop == NULL)
2191         return;
2193     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2195     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2197     // check if something is selected
2198     if (selection->isEmpty()) {
2199         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2200         return;
2201     }
2203     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2205     selection->clear();
2207     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2208     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2210     GSList *newsel = NULL;
2212     while (reprs) {
2213         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2214         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2216         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2217         sp_repr_set_attr(clone, "x", "0");
2218         sp_repr_set_attr(clone, "y", "0");
2219         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2221         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2222         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2224         // add the new clone to the top of the original's parent
2225         parent->appendChild(clone);
2227         newsel = g_slist_prepend(newsel, clone);
2228         reprs = g_slist_remove(reprs, sel_repr);
2229         Inkscape::GC::release(clone);
2230     }
2232     // TRANSLATORS: only translate "string" in "context|string".
2233     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2234     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2235                      Q_("action|Clone"));
2237     selection->setReprList(newsel);
2239     g_slist_free(newsel);
2242 void
2243 sp_selection_unlink()
2245     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2246     if (!desktop)
2247         return;
2249     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2251     if (selection->isEmpty()) {
2252         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2253         return;
2254     }
2256     // Get a copy of current selection.
2257     GSList *new_select = NULL;
2258     bool unlinked = false;
2259     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2260          items != NULL;
2261          items = items->next)
2262     {
2263         SPItem *item = (SPItem *) items->data;
2265         if (SP_IS_TEXT(item)) {
2266             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2268             if (tspan) {
2269                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2270             }
2272             // Set unlink to true, and fall into the next if which
2273             // will include this text item in the new selection
2274             unlinked = true;
2275         }
2277         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2278             // keep the non-use item in the new selection
2279             new_select = g_slist_prepend(new_select, item);
2280             continue;
2281         }
2283         SPItem *unlink;
2284         if (SP_IS_USE(item)) {
2285             unlink = sp_use_unlink(SP_USE(item));
2286         } else /*if (SP_IS_TREF(use))*/ {
2287             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2288         }
2290         unlinked = true;
2291         // Add ungrouped items to the new selection.
2292         new_select = g_slist_prepend(new_select, unlink);
2293     }
2295     if (new_select) { // set new selection
2296         selection->clear();
2297         selection->setList(new_select);
2298         g_slist_free(new_select);
2299     }
2300     if (!unlinked) {
2301         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2302     }
2304     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2305                      _("Unlink clone"));
2308 void
2309 sp_select_clone_original()
2311     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2312     if (desktop == NULL)
2313         return;
2315     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2317     SPItem *item = selection->singleItem();
2319     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.");
2321     // Check if other than two objects are selected
2322     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2323         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2324         return;
2325     }
2327     SPItem *original = NULL;
2328     if (SP_IS_USE(item)) {
2329         original = sp_use_get_original (SP_USE(item));
2330     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2331         original = sp_offset_get_source (SP_OFFSET(item));
2332     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2333         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2334     } else if (SP_IS_FLOWTEXT(item)) {
2335         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2336     } else { // it's an object that we don't know what to do with
2337         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2338         return;
2339     }
2341     if (!original) {
2342         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2343         return;
2344     }
2346     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2347         if (SP_IS_DEFS (o)) {
2348             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2349             return;
2350         }
2351     }
2353     if (original) {
2354         selection->clear();
2355         selection->set(original);
2356         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2357             scroll_to_show_item(desktop, original);
2358         }
2359     }
2363 void sp_selection_to_marker(bool apply)
2365     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2366     if (desktop == NULL)
2367         return;
2369     SPDocument *doc = sp_desktop_document(desktop);
2370     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2372     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2374     // check if something is selected
2375     if (selection->isEmpty()) {
2376         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2377         return;
2378     }
2380     sp_document_ensure_up_to_date(doc);
2381     NR::Maybe<NR::Rect> r = selection->bounds();
2382     if ( !r || r->isEmpty() ) {
2383         return;
2384     }
2386     // calculate the transform to be applied to objects to move them to 0,0
2387     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point ((r->extent(NR::X))/2, (r->extent(NR::Y))/2));
2388     move_p[NR::Y] = -move_p[NR::Y];
2389     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2391     GSList *items = g_slist_copy((GSList *) selection->itemList());
2393     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2395     // bottommost object, after sorting
2396     SPObject *parent = SP_OBJECT_PARENT (items->data);
2398     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2400     // remember the position of the first item
2401     gint pos = SP_OBJECT_REPR (items->data)->position();
2402     (void)pos; // TODO check why this was remembered
2404     // create a list of duplicates
2405     GSList *repr_copies = NULL;
2406     for (GSList *i = items; i != NULL; i = i->next) {
2407         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2408         repr_copies = g_slist_prepend (repr_copies, dup);
2409     }
2411     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2413     if (apply) {
2414         // delete objects so that their clones don't get alerted; this object will be restored shortly
2415         for (GSList *i = items; i != NULL; i = i->next) {
2416             SPObject *item = SP_OBJECT (i->data);
2417             item->deleteObject (false);
2418         }
2419     }
2421     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2422     // without disturbing clones.
2423     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2424     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2425     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2427     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2428                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2429                                                                                                 r->max()[NR::Y]))))
2430                                              * parent_transform.inverse() ),
2431                                            parent_transform * move);
2432     (void)mark_id;
2434     // restore compensation setting
2435     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2438     g_slist_free (items);
2440     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2441                       _("Objects to marker"));
2444 static void sp_selection_to_guides_recursive(SPItem *item) {
2445     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item)) {
2446         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2447             sp_selection_to_guides_recursive(SP_ITEM(i->data));
2448         }
2449     } else {
2450         sp_item_convert_item_to_guides(item);
2451     }
2454 void sp_selection_to_guides()
2456     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2457     if (desktop == NULL)
2458         return;
2460     SPDocument *doc = sp_desktop_document(desktop);
2461     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2462     // we need to copy the list because it gets reset when objects are deleted
2463     GSList *items = g_slist_copy((GSList *) selection->itemList());
2465     if (!items) {
2466         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2467         return;
2468     }
2469  
2470     for (GSList const *i = items; i != NULL; i = i->next) {
2471         sp_selection_to_guides_recursive(SP_ITEM(i->data));
2472     }
2474     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2477 void
2478 sp_selection_tile(bool apply)
2480     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2481     if (desktop == NULL)
2482         return;
2484     SPDocument *doc = sp_desktop_document(desktop);
2485     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2487     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2489     // check if something is selected
2490     if (selection->isEmpty()) {
2491         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2492         return;
2493     }
2495     sp_document_ensure_up_to_date(doc);
2496     NR::Maybe<NR::Rect> r = selection->bounds();
2497     if ( !r || r->isEmpty() ) {
2498         return;
2499     }
2501     // calculate the transform to be applied to objects to move them to 0,0
2502     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2503     move_p[NR::Y] = -move_p[NR::Y];
2504     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2506     GSList *items = g_slist_copy((GSList *) selection->itemList());
2508     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2510     // bottommost object, after sorting
2511     SPObject *parent = SP_OBJECT_PARENT (items->data);
2513     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2515     // remember the position of the first item
2516     gint pos = SP_OBJECT_REPR (items->data)->position();
2518     // create a list of duplicates
2519     GSList *repr_copies = NULL;
2520     for (GSList *i = items; i != NULL; i = i->next) {
2521         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2522         repr_copies = g_slist_prepend (repr_copies, dup);
2523     }
2525     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2527     if (apply) {
2528         // delete objects so that their clones don't get alerted; this object will be restored shortly
2529         for (GSList *i = items; i != NULL; i = i->next) {
2530             SPObject *item = SP_OBJECT (i->data);
2531             item->deleteObject (false);
2532         }
2533     }
2535     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2536     // without disturbing clones.
2537     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2538     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2539     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2541     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2542                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2543                                                                                             r->max()[NR::Y]))))
2544                                          * parent_transform.inverse() ),
2545                                        parent_transform * move);
2547     // restore compensation setting
2548     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2550     if (apply) {
2551         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2552         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2554         NR::Point min = bounds.min() * parent_transform.inverse();
2555         NR::Point max = bounds.max() * parent_transform.inverse();
2557         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2558         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2559         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2560         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2562         // restore parent and position
2563         SP_OBJECT_REPR (parent)->appendChild(rect);
2564         rect->setPosition(pos > 0 ? pos : 0);
2565         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2567         Inkscape::GC::release(rect);
2569         selection->clear();
2570         selection->set(rectangle);
2571     }
2573     g_slist_free (items);
2575     sp_document_done (doc, SP_VERB_EDIT_TILE,
2576                       _("Objects to pattern"));
2579 void
2580 sp_selection_untile()
2582     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2583     if (desktop == NULL)
2584         return;
2586     SPDocument *doc = sp_desktop_document(desktop);
2587     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2589     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2591     // check if something is selected
2592     if (selection->isEmpty()) {
2593         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2594         return;
2595     }
2597     GSList *new_select = NULL;
2599     bool did = false;
2601     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2602          items != NULL;
2603          items = items->next) {
2605         SPItem *item = (SPItem *) items->data;
2607         SPStyle *style = SP_OBJECT_STYLE (item);
2609         if (!style || !style->fill.isPaintserver())
2610             continue;
2612         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2614         if (!SP_IS_PATTERN(server))
2615             continue;
2617         did = true;
2619         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2621         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2622         pat_transform *= item->transform;
2624         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2625             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2626             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2628            // FIXME: relink clones to the new canvas objects
2629            // use SPObject::setid when mental finishes it to steal ids of
2631             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2632             sp_document_ensure_up_to_date (doc);
2634             NR::Matrix transform( i->transform * pat_transform );
2635             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2637             new_select = g_slist_prepend(new_select, i);
2638         }
2640         SPCSSAttr *css = sp_repr_css_attr_new ();
2641         sp_repr_css_set_property (css, "fill", "none");
2642         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2643     }
2645     if (!did) {
2646         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2647     } else {
2648         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2649                          _("Pattern to objects"));
2650         selection->setList(new_select);
2651     }
2654 void
2655 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2657     if (selection->isEmpty()) {
2658         return;
2659     }
2661     GSList const *reprlst = selection->reprList();
2662     bool filename_search = TRUE;
2663     bool xdpi_search = TRUE;
2664     bool ydpi_search = TRUE;
2666     for(; reprlst != NULL &&
2667             filename_search &&
2668             xdpi_search &&
2669             ydpi_search;
2670         reprlst = reprlst->next) {
2671         gchar const *dpi_string;
2672         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2674         if (filename_search) {
2675             *filename = repr->attribute("inkscape:export-filename");
2676             if (*filename != NULL)
2677                 filename_search = FALSE;
2678         }
2680         if (xdpi_search) {
2681             dpi_string = NULL;
2682             dpi_string = repr->attribute("inkscape:export-xdpi");
2683             if (dpi_string != NULL) {
2684                 *xdpi = atof(dpi_string);
2685                 xdpi_search = FALSE;
2686             }
2687         }
2689         if (ydpi_search) {
2690             dpi_string = NULL;
2691             dpi_string = repr->attribute("inkscape:export-ydpi");
2692             if (dpi_string != NULL) {
2693                 *ydpi = atof(dpi_string);
2694                 ydpi_search = FALSE;
2695             }
2696         }
2697     }
2700 void
2701 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2703     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2704     gchar const *dpi_string;
2706     *filename = repr->attribute("inkscape:export-filename");
2708     dpi_string = NULL;
2709     dpi_string = repr->attribute("inkscape:export-xdpi");
2710     if (dpi_string != NULL) {
2711         *xdpi = atof(dpi_string);
2712     }
2714     dpi_string = NULL;
2715     dpi_string = repr->attribute("inkscape:export-ydpi");
2716     if (dpi_string != NULL) {
2717         *ydpi = atof(dpi_string);
2718     }
2721 void
2722 sp_selection_create_bitmap_copy ()
2724     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2725     if (desktop == NULL)
2726         return;
2728     SPDocument *document = sp_desktop_document(desktop);
2729     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2731     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2733     // check if something is selected
2734     if (selection->isEmpty()) {
2735         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2736         return;
2737     }
2739     // Get the bounding box of the selection
2740     NRRect bbox;
2741     sp_document_ensure_up_to_date (document);
2742     selection->bounds(&bbox);
2743     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2744         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2745     }
2747     // List of the items to show; all others will be hidden
2748     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2750     // Sort items so that the topmost comes last
2751     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2753     // Generate a random value from the current time (you may create bitmap from the same object(s)
2754     // multiple times, and this is done so that they don't clash)
2755     GTimeVal cu;
2756     g_get_current_time (&cu);
2757     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2759     // Create the filename
2760     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2761     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2762     // digits, and a few other chars, with "_"
2763     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2764     // Build the complete path by adding document->base if set
2765     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2767     //g_print ("%s\n", filepath);
2769     // Remember parent and z-order of the topmost one
2770     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2771     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2772     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2774     // Calculate resolution
2775     double res;
2776     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2777     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2778     if (0 < prefs_res) {
2779         // If it's given explicitly in prefs, take it
2780         res = prefs_res;
2781     } else if (0 < prefs_min) {
2782         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2783         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2784     } else {
2785         float hint_xdpi = 0, hint_ydpi = 0;
2786         char const *hint_filename;
2787         // take resolution hint from the selected objects
2788         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2789         if (hint_xdpi != 0) {
2790             res = hint_xdpi;
2791         } else {
2792             // take resolution hint from the document
2793             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2794             if (hint_xdpi != 0) {
2795                 res = hint_xdpi;
2796             } else {
2797                 // if all else fails, take the default 90 dpi
2798                 res = PX_PER_IN;
2799             }
2800         }
2801     }
2803     // The width and height of the bitmap in pixels
2804     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2805     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2807     // Find out if we have to run a filter
2808     gchar const *run = NULL;
2809     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2810     if (filter) {
2811         // filter command is given;
2812         // see if we have a parameter to pass to it
2813         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2814         if (param1) {
2815             if (param1[strlen(param1) - 1] == '%') {
2816                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2817                 gchar p1[256];
2818                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2819                 // the first param is always the image filename, the second is param1
2820                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2821             } else {
2822                 // otherwise pass the param1 unchanged
2823                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2824             }
2825         } else {
2826             // run without extra parameter
2827             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2828         }
2829     }
2831     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2832     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2833     NR::Matrix t;
2835     double shift_x = bbox.x0;
2836     double shift_y = bbox.y1;
2837     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2838         shift_x = round (shift_x);
2839         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2840     }
2841     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2843     // Do the export
2844     sp_export_png_file(document, filepath,
2845                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2846                    width, height, res, res,
2847                    (guint32) 0xffffff00,
2848                    NULL, NULL,
2849                    true,  /*bool force_overwrite,*/
2850                    items);
2852     g_slist_free (items);
2854     // Run filter, if any
2855     if (run) {
2856         g_print ("Running external filter: %s\n", run);
2857         system (run);
2858     }
2860     // Import the image back
2861     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2862     if (pb) {
2863         // Create the repr for the image
2864         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2865         repr->setAttribute("xlink:href", filename);
2866         repr->setAttribute("sodipodi:absref", filepath);
2867         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2868             sp_repr_set_svg_double(repr, "width", width);
2869             sp_repr_set_svg_double(repr, "height", height);
2870         } else {
2871             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2872             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2873         }
2875         // Write transform
2876         gchar *c=sp_svg_transform_write(t);
2877         repr->setAttribute("transform", c);
2878         g_free(c);
2880         // add the new repr to the parent
2881         parent->appendChild(repr);
2883         // move to the saved position
2884         repr->setPosition(pos > 0 ? pos + 1 : 1);
2886         // Set selection to the new image
2887         selection->clear();
2888         selection->add(repr);
2890         // Clean up
2891         Inkscape::GC::release(repr);
2892         gdk_pixbuf_unref (pb);
2894         // Complete undoable transaction
2895         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2896                           _("Create bitmap"));
2897     }
2899     g_free (filename);
2900     g_free (filepath);
2903 /**
2904  * \brief sp_selection_set_mask
2905  *
2906  * This function creates a mask or clipPath from selection
2907  * Two different modes:
2908  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2909  *       and is applied to current layer
2910  *  otherwise, topmost object is used as mask for other objects
2911  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2912  *
2913  */
2914 void
2915 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2917     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2918     if (desktop == NULL)
2919         return;
2921     SPDocument *doc = sp_desktop_document(desktop);
2922     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2924     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2926     // check if something is selected
2927     bool is_empty = selection->isEmpty();
2928     if ( apply_to_layer && is_empty) {
2929         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2930         return;
2931     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2932         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2933         return;
2934     }
2936     // FIXME: temporary patch to prevent crash!
2937     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2938     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2939     if (clone_with_original) {
2940         return; // in this version, you cannot clip/mask an object with its own clone
2941     }
2942     // /END FIXME
2944     sp_document_ensure_up_to_date(doc);
2946     GSList *items = g_slist_copy((GSList *) selection->itemList());
2948     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2950     // create a list of duplicates
2951     GSList *mask_items = NULL;
2952     GSList *apply_to_items = NULL;
2953     GSList *items_to_delete = NULL;
2954     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2955     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2957     if (apply_to_layer) {
2958         // all selected items are used for mask, which is applied to a layer
2959         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2961         for (GSList *i = items; i != NULL; i = i->next) {
2962             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2963             mask_items = g_slist_prepend (mask_items, dup);
2965             if (remove_original) {
2966                 SPObject *item = SP_OBJECT (i->data);
2967                 items_to_delete = g_slist_prepend (items_to_delete, item);
2968             }
2969         }
2970     } else if (!topmost) {
2971         // topmost item is used as a mask, which is applied to other items in a selection
2972         GSList *i = items;
2973         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2974         mask_items = g_slist_prepend (mask_items, dup);
2976         if (remove_original) {
2977             SPObject *item = SP_OBJECT (i->data);
2978             items_to_delete = g_slist_prepend (items_to_delete, item);
2979         }
2981         for (i = i->next; i != NULL; i = i->next) {
2982             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2983         }
2984     } else {
2985         GSList *i = NULL;
2986         for (i = items; NULL != i->next; i = i->next) {
2987             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2988         }
2990         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2991         mask_items = g_slist_prepend (mask_items, dup);
2993         if (remove_original) {
2994             SPObject *item = SP_OBJECT (i->data);
2995             items_to_delete = g_slist_prepend (items_to_delete, item);
2996         }
2997     }
2999     g_slist_free (items);
3000     items = NULL;
3002     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3003     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
3004         SPItem *item = reinterpret_cast<SPItem *>(i->data);
3005         // inverted object transform should be applied to a mask object,
3006         // as mask is calculated in user space (after applying transform)
3007         NR::Matrix maskTransform (item->transform.inverse());
3009         GSList *mask_items_dup = NULL;
3010         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
3011             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
3012             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
3013         }
3015         gchar const *mask_id = NULL;
3016         if (apply_clip_path) {
3017             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
3018         } else {
3019             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
3020         }
3022         g_slist_free (mask_items_dup);
3023         mask_items_dup = NULL;
3025         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3026     }
3028     g_slist_free (mask_items);
3029     g_slist_free (apply_to_items);
3031     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3032         SPObject *item = SP_OBJECT (i->data);
3033         item->deleteObject (false);
3034     }
3035     g_slist_free (items_to_delete);
3037     if (apply_clip_path)
3038         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3039     else
3040         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3043 void sp_selection_unset_mask(bool apply_clip_path) {
3044     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3045     if (desktop == NULL)
3046         return;
3048     SPDocument *doc = sp_desktop_document(desktop);
3049     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3050     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3052     // check if something is selected
3053     if (selection->isEmpty()) {
3054         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3055         return;
3056     }
3058     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3059     sp_document_ensure_up_to_date(doc);
3061     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3062     std::map<SPObject*,SPItem*> referenced_objects;
3063     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3064         if (remove_original) {
3065             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3066             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3067             Inkscape::URIReference *uri_ref = NULL;
3069             if (apply_clip_path) {
3070                 uri_ref = item->clip_ref;
3071             } else {
3072                 uri_ref = item->mask_ref;
3073             }
3075             // collect distinct mask object (and associate with item to apply transform)
3076             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3077                 referenced_objects[uri_ref->getObject()] = item;
3078             }
3079         }
3081         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3082     }
3084     // restore mask objects into a document
3085     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3086         SPObject *obj = (*it).first;
3087         GSList *items_to_move = NULL;
3088         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3089             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3090             items_to_move = g_slist_prepend (items_to_move, copy);
3091         }
3093         if (!obj->isReferenced()) {
3094             // delete from defs if no other object references this mask
3095             obj->deleteObject(false);
3096         }
3098         // remember parent and position of the item to which the clippath/mask was applied
3099         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3100         gint pos = SP_OBJECT_REPR((*it).second)->position();
3102         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3103             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3105             // insert into parent, restore pos
3106             parent->appendChild(repr);
3107             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3109             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
3110             selection->add(repr);
3112             // transform mask, so it is moved the same spot where mask was applied
3113             NR::Matrix transform (mask_item->transform);
3114             transform *= (*it).second->transform;
3115             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3116         }
3118         g_slist_free (items_to_move);
3119     }
3121     if (apply_clip_path)
3122         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3123     else
3124         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3127 void fit_canvas_to_selection(SPDesktop *desktop) {
3128     g_return_if_fail(desktop != NULL);
3129     SPDocument *doc = sp_desktop_document(desktop);
3131     g_return_if_fail(doc != NULL);
3132     g_return_if_fail(desktop->selection != NULL);
3134     if (desktop->selection->isEmpty()) {
3135         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3136         return;
3137     }
3138     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
3139     if (bbox && !bbox->isEmpty()) {
3140         doc->fitToRect(*bbox);
3141     }
3142 };
3144 void fit_canvas_to_drawing(SPDocument *doc) {
3145     g_return_if_fail(doc != NULL);
3147     sp_document_ensure_up_to_date(doc);
3148     SPItem const *const root = SP_ITEM(doc->root);
3149     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
3150     if (bbox && !bbox->isEmpty()) {
3151         doc->fitToRect(*bbox);
3152     }
3153 };
3155 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3156     g_return_if_fail(desktop != NULL);
3157     SPDocument *doc = sp_desktop_document(desktop);
3159     g_return_if_fail(doc != NULL);
3160     g_return_if_fail(desktop->selection != NULL);
3162     if (desktop->selection->isEmpty()) {
3163         fit_canvas_to_drawing(doc);
3164     } else {
3165         fit_canvas_to_selection(desktop);
3166     }
3168     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
3169                      _("Fit page to selection"));
3170 };
3172 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3173     // don't operate on layers
3174     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3175         f(SP_ITEM(root), desktop);
3176     }
3177     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3178         //don't recurse into locked layers
3179         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3180             itemtree_map(f, iter, desktop);
3181         }
3182     }
3185 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3186     if (item->isLocked()) {
3187         item->setLocked(FALSE);
3188     }
3191 static void unhide(SPItem *item, SPDesktop *desktop) {
3192     if (desktop->itemIsHidden(item)) {
3193         item->setExplicitlyHidden(FALSE);
3194     }
3197 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3198     if (!dt) return;
3200     SPObject *root;
3201     if (layer_only) {
3202         root = dt->currentLayer();
3203     } else {
3204         root = dt->currentRoot();
3205     }
3207     itemtree_map(f, root, dt);
3210 void unlock_all(SPDesktop *dt) {
3211     process_all(&unlock, dt, true);
3214 void unlock_all_in_all_layers(SPDesktop *dt) {
3215     process_all(&unlock, dt, false);
3218 void unhide_all(SPDesktop *dt) {
3219     process_all(&unhide, dt, true);
3222 void unhide_all_in_all_layers(SPDesktop *dt) {
3223     process_all(&unhide, dt, false);
3227 GSList * sp_selection_get_clipboard() {
3228     return clipboard;
3232 /*
3233   Local Variables:
3234   mode:c++
3235   c-file-style:"stroustrup"
3236   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3237   indent-tabs-mode:nil
3238   fill-column:99
3239   End:
3240 */
3241 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :