Code

+ Fix bug #179840, forking of LPEs
[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 "unit-constants.h"
76 #include "xml/simple-document.h"
77 #include "sp-filter-reference.h"
78 #include "gradient-drag.h"
79 #include "uri-references.h"
80 #include "live_effects/lpeobject.h"
82 using NR::X;
83 using NR::Y;
85 #include "selection-chemistry.h"
87 /* fixme: find a better place */
88 Inkscape::XML::Document *clipboard_document = NULL;
89 GSList *clipboard = NULL;
90 GSList *defs_clipboard = NULL;
91 SPCSSAttr *style_clipboard = NULL;
92 NR::Maybe<NR::Rect> size_clipboard;
94 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc);
96 /**
97  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
98  * then prepends the copy to 'clip'.
99  */
100 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
102     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
104     // copy complete inherited style
105     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
106     sp_repr_css_set(copy, css, "style");
107     sp_repr_css_attr_unref(css);
109     // write the complete accumulated transform passed to us
110     // (we're dealing with unattached repr, so we write to its attr
111     // instead of using sp_item_set_transform)
112     gchar *affinestr=sp_svg_transform_write(full_t);
113     copy->setAttribute("transform", affinestr);
114     g_free(affinestr);
116     *clip = g_slist_prepend(*clip, copy);
119 void sp_selection_copy_impl (GSList const *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
122     // Copy stuff referenced by all items to defs_clip:
123     if (defs_clip) {
124         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
125             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
126         }
127         *defs_clip = g_slist_reverse(*defs_clip);
128     }
130     // Store style:
131     if (style_clip) {
132         SPItem *item = SP_ITEM (items->data); // take from the first selected item
133         *style_clip = take_style_from_item (item);
134     }
136     if (clip) {
137         // Sort items:
138         GSList *sorted_items = g_slist_copy ((GSList *) items);
139         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
141         // Copy item reprs:
142         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
143             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
144         }
146         *clip = g_slist_reverse(*clip);
147         g_slist_free ((GSList *) sorted_items);
148     }
151 /**
152  * Add gradients/patterns/markers referenced by copied objects to defs.
153  * Iterates through 'defs_clip', and for each item it adds the data
154  * repr into the global defs.
155  */
156 void
157 paste_defs (GSList **defs_clip, SPDocument *doc)
159     if (!defs_clip)
160         return;
162     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
163         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
164         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
165         gchar const *id = repr->attribute("id");
166         if (!id || !doc->getObjectById(id)) {
167             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
168             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
169             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
170             Inkscape::GC::release(copy);
171         }
172     }
175 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
177     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
178     paste_defs (defs_clip, doc);
180     GSList *copied = NULL;
181     // add objects to document
182     for (GSList *l = *clip; l != NULL; l = l->next) {
183         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
184         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
186         // premultiply the item transform by the accumulated parent transform in the paste layer
187         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
188         if (!local.test_identity()) {
189             gchar const *t_str = copy->attribute("transform");
190             NR::Matrix item_t (NR::identity());
191             if (t_str)
192                 sp_svg_transform_read(t_str, &item_t);
193             item_t *= local.inverse();
194             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
195             gchar *affinestr=sp_svg_transform_write(item_t);
196             copy->setAttribute("transform", affinestr);
197             g_free(affinestr);
198         }
200         parent->appendChildRepr(copy);
201         copied = g_slist_prepend(copied, copy);
202         Inkscape::GC::release(copy);
203     }
204     return copied;
207 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
209     for (GSList const *i = items ; i ; i = i->next ) {
210         sp_object_ref((SPObject *)i->data, NULL);
211     }
212     for (GSList const *i = items; i != NULL; i = i->next) {
213         SPItem *item = (SPItem *) i->data;
214         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
215         sp_object_unref((SPObject *)item, NULL);
216     }
220 void sp_selection_delete()
222     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
223     if (desktop == NULL) {
224         return;
225     }
227     if (tools_isactive (desktop, TOOLS_TEXT))
228         if (sp_text_delete_selection(desktop->event_context)) {
229             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
230                              _("Delete text"));
231             return;
232         }
234     Inkscape::Selection *selection = sp_desktop_selection(desktop);
236     // check if something is selected
237     if (selection->isEmpty()) {
238         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
239         return;
240     }
242     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
243     selection->clear();
244     sp_selection_delete_impl (selected);
245     g_slist_free ((GSList *) selected);
247     /* a tool may have set up private information in it's selection context
248      * that depends on desktop items.  I think the only sane way to deal with
249      * this currently is to reset the current tool, which will reset it's
250      * associated selection context.  For example: deleting an object
251      * while moving it around the canvas.
252      */
253     tools_switch ( desktop, tools_active ( desktop ) );
255     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
256                      _("Delete"));
259 /* fixme: sequencing */
260 void sp_selection_duplicate()
262     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
263     if (desktop == NULL)
264         return;
266     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
267     Inkscape::Selection *selection = sp_desktop_selection(desktop);
269     // check if something is selected
270     if (selection->isEmpty()) {
271         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
272         return;
273     }
275     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
277     selection->clear();
279     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
280     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
282     GSList *newsel = NULL;
284     while (reprs) {
285         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
286         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
288         parent->appendChild(copy);
290         newsel = g_slist_prepend(newsel, copy);
291         reprs = g_slist_remove(reprs, reprs->data);
292         Inkscape::GC::release(copy);
293     }
295     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
296                      _("Duplicate"));
298     selection->setReprList(newsel);
300     g_slist_free(newsel);
303 void sp_edit_clear_all()
305     SPDesktop *dt = SP_ACTIVE_DESKTOP;
306     if (!dt)
307         return;
309     SPDocument *doc = sp_desktop_document(dt);
310     sp_desktop_selection(dt)->clear();
312     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
313     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
315     while (items) {
316         SP_OBJECT (items->data)->deleteObject();
317         items = g_slist_remove(items, items->data);
318     }
320     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
321                      _("Delete all"));
324 GSList *
325 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
327     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
328         if (SP_IS_ITEM(child) &&
329             !desktop->isLayer(SP_ITEM(child)) &&
330             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
331             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
332             (!exclude || !g_slist_find ((GSList *) exclude, child))
333             )
334         {
335             list = g_slist_prepend (list, SP_ITEM(child));
336         }
338         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
339             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
340         }
341     }
343     return list;
346 void sp_edit_select_all_full (bool force_all_layers, bool invert)
348     SPDesktop *dt = SP_ACTIVE_DESKTOP;
349     if (!dt)
350         return;
352     Inkscape::Selection *selection = sp_desktop_selection(dt);
354     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
356     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
357     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
358     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
360     GSList *items = NULL;
362     GSList const *exclude = NULL;
363     if (invert) {
364         exclude = selection->itemList();
365     }
367     if (force_all_layers)
368         inlayer = PREFS_SELECTION_ALL;
370     switch (inlayer) {
371         case PREFS_SELECTION_LAYER: {
372         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
373              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
374         return;
376         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
378         for (GSList *i = all_items; i; i = i->next) {
379             SPItem *item = SP_ITEM (i->data);
381             if (item && (!onlysensitive || !item->isLocked())) {
382                 if (!onlyvisible || !dt->itemIsHidden(item)) {
383                     if (!dt->isLayer(item)) {
384                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
385                             items = g_slist_prepend (items, item); // leave it in the list
386                         }
387                     }
388                 }
389             }
390         }
392         g_slist_free (all_items);
393             break;
394         }
395         case PREFS_SELECTION_LAYER_RECURSIVE: {
396             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
397             break;
398         }
399         default: {
400         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
401             break;
402     }
403     }
405     selection->setList (items);
407     if (items) {
408         g_slist_free (items);
409     }
412 void sp_edit_select_all ()
414     sp_edit_select_all_full (false, false);
417 void sp_edit_select_all_in_all_layers ()
419     sp_edit_select_all_full (true, false);
422 void sp_edit_invert ()
424     sp_edit_select_all_full (false, true);
427 void sp_edit_invert_in_all_layers ()
429     sp_edit_select_all_full (true, true);
432 void sp_selection_group()
434     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
435     if (desktop == NULL)
436         return;
438     SPDocument *doc = sp_desktop_document (desktop);
439     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
441     Inkscape::Selection *selection = sp_desktop_selection(desktop);
443     // Check if something is selected.
444     if (selection->isEmpty()) {
445         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
446         return;
447     }
449     GSList const *l = (GSList *) selection->reprList();
451     GSList *p = g_slist_copy((GSList *) l);
453     selection->clear();
455     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
457     // Remember the position and parent of the topmost object.
458     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
459     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
461     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
463     while (p) {
464         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
466         if (current->parent() == topmost_parent) {
467             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
468             sp_repr_unparent(current);
469             group->appendChild(spnew);
470             Inkscape::GC::release(spnew);
471             topmost --; // only reduce count for those items deleted from topmost_parent
472         } else { // move it to topmost_parent first
473                 GSList *temp_clip = NULL;
475                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
476                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
477                 gchar const *t_str = current->attribute("transform");
478                 NR::Matrix item_t (NR::identity());
479                 if (t_str)
480                     sp_svg_transform_read(t_str, &item_t);
481                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
482                 //FIXME: when moving both clone and original from a transformed group (either by
483                 //grouping into another parent, or by cut/paste) the transform from the original's
484                 //parent becomes embedded into original itself, and this affects its clones. Fix
485                 //this by remembering the transform diffs we write to each item into an array and
486                 //then, if this is clone, looking up its original in that array and pre-multiplying
487                 //it by the inverse of that original's transform diff.
489                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
490                 sp_repr_unparent(current);
492                 // paste into topmost_parent (temporarily)
493                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
494                 if (temp_clip) g_slist_free (temp_clip);
495                 if (copied) { // if success,
496                     // take pasted object (now in topmost_parent)
497                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
498                     // make a copy
499                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
500                     // remove pasted
501                     sp_repr_unparent(in_topmost);
502                     // put its copy into group
503                     group->appendChild(spnew);
504                     Inkscape::GC::release(spnew);
505                     g_slist_free (copied);
506                 }
507         }
508         p = g_slist_remove(p, current);
509     }
511     // Add the new group to the topmost members' parent
512     topmost_parent->appendChild(group);
514     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
515     group->setPosition(topmost + 1);
517     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
518                      _("Group"));
520     selection->set(group);
521     Inkscape::GC::release(group);
524 void sp_selection_ungroup()
526     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
527     if (desktop == NULL)
528         return;
530     Inkscape::Selection *selection = sp_desktop_selection(desktop);
532     if (selection->isEmpty()) {
533         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
534         return;
535     }
537     GSList *items = g_slist_copy((GSList *) selection->itemList());
538     selection->clear();
540     // Get a copy of current selection.
541     GSList *new_select = NULL;
542     bool ungrouped = false;
543     for (GSList *i = items;
544          i != NULL;
545          i = i->next)
546     {
547         SPItem *group = (SPItem *) i->data;
549         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
550         if (!SP_IS_OBJECT(group)) {
551             continue;
552         }
554         /* We do not allow ungrouping <svg> etc. (lauris) */
555         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
556             // keep the non-group item in the new selection
557             selection->add(group);
558             continue;
559         }
561         GSList *children = NULL;
562         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
563         sp_item_group_ungroup(SP_GROUP(group), &children, false);
564         ungrouped = true;
565         // Add ungrouped items to the new selection.
566         new_select = g_slist_concat(new_select, children);
567     }
569     if (new_select) { // Set new selection.
570         selection->addList(new_select);
571         g_slist_free(new_select);
572     }
573     if (!ungrouped) {
574         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
575     }
577     g_slist_free(items);
579     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
580                      _("Ungroup"));
583 static SPGroup *
584 sp_item_list_common_parent_group(GSList const *items)
586     if (!items) {
587         return NULL;
588     }
589     SPObject *parent = SP_OBJECT_PARENT(items->data);
590     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
591     if (!SP_IS_GROUP(parent)) {
592         return NULL;
593     }
594     for (items = items->next; items; items = items->next) {
595         if (SP_OBJECT_PARENT(items->data) != parent) {
596             return NULL;
597         }
598     }
600     return SP_GROUP(parent);
603 /** Finds out the minimum common bbox of the selected items. */
604 static NR::Maybe<NR::Rect>
605 enclose_items(GSList const *items)
607     g_assert(items != NULL);
609     NR::Maybe<NR::Rect> r = NR::Nothing();
610     for (GSList const *i = items; i; i = i->next) {
611         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
612     }
613     return r;
616 SPObject *
617 prev_sibling(SPObject *child)
619     SPObject *parent = SP_OBJECT_PARENT(child);
620     if (!SP_IS_GROUP(parent)) {
621         return NULL;
622     }
623     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
624         if (i->next == child)
625             return i;
626     }
627     return NULL;
630 void
631 sp_selection_raise()
633     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
634     if (!desktop)
635         return;
637     Inkscape::Selection *selection = sp_desktop_selection(desktop);
639     GSList const *items = (GSList *) selection->itemList();
640     if (!items) {
641         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
642         return;
643     }
645     SPGroup const *group = sp_item_list_common_parent_group(items);
646     if (!group) {
647         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
648         return;
649     }
651     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
653     /* Construct reverse-ordered list of selected children. */
654     GSList *rev = g_slist_copy((GSList *) items);
655     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
657     // Determine the common bbox of the selected items.
658     NR::Maybe<NR::Rect> selected = enclose_items(items);
660     // Iterate over all objects in the selection (starting from top).
661     if (selected) {
662         while (rev) {
663             SPObject *child = SP_OBJECT(rev->data);
664             // for each selected object, find the next sibling
665             for (SPObject *newref = child->next; newref; newref = newref->next) {
666                 // if the sibling is an item AND overlaps our selection,
667                 if (SP_IS_ITEM(newref)) {
668                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
669                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
670                         // AND if it's not one of our selected objects,
671                         if (!g_slist_find((GSList *) items, newref)) {
672                             // move the selected object after that sibling
673                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
674                         }
675                         break;
676                     }
677                 }
678             }
679             rev = g_slist_remove(rev, child);
680         }
681     } else {
682         g_slist_free(rev);
683     }
685     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
686                      _("Raise"));
689 void sp_selection_raise_to_top()
691     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
692     if (desktop == NULL)
693         return;
695     SPDocument *document = sp_desktop_document(desktop);
696     Inkscape::Selection *selection = sp_desktop_selection(desktop);
698     if (selection->isEmpty()) {
699         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
700         return;
701     }
703     GSList const *items = (GSList *) selection->itemList();
705     SPGroup const *group = sp_item_list_common_parent_group(items);
706     if (!group) {
707         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
708         return;
709     }
711     GSList *rl = g_slist_copy((GSList *) selection->reprList());
712     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
714     for (GSList *l = rl; l != NULL; l = l->next) {
715         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
716         repr->setPosition(-1);
717     }
719     g_slist_free(rl);
721     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
722                      _("Raise to top"));
725 void
726 sp_selection_lower()
728     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
729     if (desktop == NULL)
730         return;
732     Inkscape::Selection *selection = sp_desktop_selection(desktop);
734     GSList const *items = (GSList *) selection->itemList();
735     if (!items) {
736         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
737         return;
738     }
740     SPGroup const *group = sp_item_list_common_parent_group(items);
741     if (!group) {
742         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
743         return;
744     }
746     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
748     // Determine the common bbox of the selected items.
749     NR::Maybe<NR::Rect> selected = enclose_items(items);
751     /* Construct direct-ordered list of selected children. */
752     GSList *rev = g_slist_copy((GSList *) items);
753     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
754     rev = g_slist_reverse(rev);
756     // Iterate over all objects in the selection (starting from top).
757     if (selected) {
758         while (rev) {
759             SPObject *child = SP_OBJECT(rev->data);
760             // for each selected object, find the prev sibling
761             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
762                 // if the sibling is an item AND overlaps our selection,
763                 if (SP_IS_ITEM(newref)) {
764                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
765                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
766                         // AND if it's not one of our selected objects,
767                         if (!g_slist_find((GSList *) items, newref)) {
768                             // move the selected object before that sibling
769                             SPObject *put_after = prev_sibling(newref);
770                             if (put_after)
771                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
772                             else
773                                 SP_OBJECT_REPR(child)->setPosition(0);
774                         }
775                         break;
776                     }
777                 }
778             }
779             rev = g_slist_remove(rev, child);
780         }
781     } else {
782         g_slist_free(rev);
783     }
785     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
786                      _("Lower"));
789 void sp_selection_lower_to_bottom()
791     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
792     if (desktop == NULL)
793         return;
795     SPDocument *document = sp_desktop_document(desktop);
796     Inkscape::Selection *selection = sp_desktop_selection(desktop);
798     if (selection->isEmpty()) {
799         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
800         return;
801     }
803     GSList const *items = (GSList *) selection->itemList();
805     SPGroup const *group = sp_item_list_common_parent_group(items);
806     if (!group) {
807         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
808         return;
809     }
811     GSList *rl;
812     rl = g_slist_copy((GSList *) selection->reprList());
813     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
814     rl = g_slist_reverse(rl);
816     for (GSList *l = rl; l != NULL; l = l->next) {
817         gint minpos;
818         SPObject *pp, *pc;
819         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
820         pp = document->getObjectByRepr(sp_repr_parent(repr));
821         minpos = 0;
822         g_assert(SP_IS_GROUP(pp));
823         pc = sp_object_first_child(pp);
824         while (!SP_IS_ITEM(pc)) {
825             minpos += 1;
826             pc = pc->next;
827         }
828         repr->setPosition(minpos);
829     }
831     g_slist_free(rl);
833     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
834                      _("Lower to bottom"));
837 void
838 sp_undo(SPDesktop *desktop, SPDocument *)
840         if (!sp_document_undo(sp_desktop_document(desktop)))
841             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
844 void
845 sp_redo(SPDesktop *desktop, SPDocument *)
847         if (!sp_document_redo(sp_desktop_document(desktop)))
848             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
851 void sp_selection_cut()
853     sp_selection_copy();
854     sp_selection_delete();
857 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
859     SPGradient *ref = gradient;
861     while (ref) {
862         // climb up the refs, copying each one in the chain
863         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
864         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
866         ref = ref->ref->getObject();
867     }
870 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
872     SPPattern *ref = pattern;
874     while (ref) {
875         // climb up the refs, copying each one in the chain
876         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
877         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
879         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
880         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
881             if (!SP_IS_ITEM (child))
882                 continue;
883             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
884         }
886         ref = ref->ref->getObject();
887     }
890 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
892     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
893     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
897 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, GSList const *items, Inkscape::XML::Document* xml_doc)
899     SPItem *path = sp_textpath_get_path_item (tp);
900     if (!path)
901         return;
902     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
903         return;
904     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
905     *defs_clip = g_slist_prepend (*defs_clip, repr);
908 /**
909  * Copies things like patterns, markers, gradients, etc.
910  */
911 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, GSList const *items, Inkscape::XML::Document* xml_doc)
913     SPStyle *style = SP_OBJECT_STYLE (item);
915     if (style && (style->fill.isPaintserver())) {
916         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
917         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
918             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
919         if (SP_IS_PATTERN (server))
920             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
921     }
923     if (style && (style->stroke.isPaintserver())) {
924         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
925         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
926             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
927         if (SP_IS_PATTERN (server))
928             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
929     }
931     // For shapes, copy all of the shape's markers into defs_clip
932     if (SP_IS_SHAPE (item)) {
933         SPShape *shape = SP_SHAPE (item);
934         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
935             if (shape->marker[i]) {
936                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
937             }
938         }
940         // For shapes, also copy liveeffect if applicable
941         if (sp_shape_has_path_effect(shape)) {
942             sp_copy_single (defs_clip, SP_OBJECT(sp_shape_get_livepatheffectobject(shape)), xml_doc);
943         }
944     }
946     if (SP_IS_TEXT_TEXTPATH (item)) {
947         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
948     }
950     if (item->clip_ref->getObject()) {
951         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
952     }
954     if (item->mask_ref->getObject()) {
955         SPObject *mask = item->mask_ref->getObject();
956         sp_copy_single (defs_clip, mask, xml_doc);
957         // recurse into the mask for its gradients etc.
958         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
959             if (SP_IS_ITEM(o))
960                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
961         }
962     }
964     if (style->getFilter()) {
965         SPObject *filter = style->getFilter();
966         if (SP_IS_FILTER(filter)) {
967             sp_copy_single (defs_clip, filter, xml_doc);
968         }
969     }
971     // recurse
972     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
973         if (SP_IS_ITEM(o))
974             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
975     }
978 void
979 sp_set_style_clipboard (SPCSSAttr *css)
981     if (css != NULL) {
982         // clear style clipboard
983         if (style_clipboard) {
984             sp_repr_css_attr_unref (style_clipboard);
985             style_clipboard = NULL;
986         }
987         //sp_repr_css_print (css);
988         style_clipboard = css;
989     }
992 /**
993  * \pre item != NULL
994  */
995 SPCSSAttr *
996 take_style_from_item (SPItem *item)
998     // write the complete cascaded style, context-free
999     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1000     if (css == NULL)
1001         return NULL;
1003     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1004         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1005         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1006         // If this is a group, merge the style of its topmost (last) child with style
1007         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
1008             if (SP_OBJECT_STYLE (last_element) != NULL) {
1009                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
1010                 if (temp) {
1011                     sp_repr_css_merge (css, temp);
1012                     sp_repr_css_attr_unref (temp);
1013                 }
1014                 break;
1015             }
1016         }
1017     }
1018     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
1019         // do not copy text properties from non-text objects, it's confusing
1020         css = sp_css_attr_unset_text (css);
1021     }
1023     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1024     double ex = NR::expansion(sp_item_i2doc_affine(item));
1025     if (ex != 1.0) {
1026         css = sp_css_attr_scale (css, ex);
1027     }
1029     return css;
1033 void sp_selection_copy()
1035     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1036     if (desktop == NULL)
1037         return;
1039     if (!clipboard_document) {
1040         clipboard_document = new Inkscape::XML::SimpleDocument();
1041     }
1043     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1045     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1046         sp_dropper_context_copy(desktop->event_context);
1047         return; // copied color under cursor, nothing else to do
1048     }
1050     if (desktop->event_context->get_drag() && desktop->event_context->get_drag()->copy()) {
1051         return; // copied selected stop(s), nothing else to do
1052     }
1054     // check if something is selected
1055     if (selection->isEmpty()) {
1056         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1057         return;
1058     }
1060     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1062     // 0. Copy text to system clipboard
1063     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1064     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1065     Glib::ustring text;
1066     if (tools_isactive (desktop, TOOLS_TEXT)) {
1067         text = sp_text_get_selected_text(desktop->event_context);
1068     }
1070     if (text.empty()) {
1071         guint texts = 0;
1072         for (GSList *i = (GSList *) items; i; i = i->next) {
1073             SPItem *item = SP_ITEM (i->data);
1074             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1075                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1076                     text += " ";
1077                 gchar *this_text = sp_te_get_string_multiline (item);
1078                 if (this_text) {
1079                     text += this_text;
1080                     g_free(this_text);
1081                 }
1082                 texts++;
1083             }
1084         }
1085     }
1086     if (!text.empty()) {
1087         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1088         refClipboard->set_text(text);
1089     }
1091     // clear old defs clipboard
1092     while (defs_clipboard) {
1093         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1094         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1095     }
1097     // clear style clipboard
1098     if (style_clipboard) {
1099         sp_repr_css_attr_unref (style_clipboard);
1100         style_clipboard = NULL;
1101     }
1103     //clear main clipboard
1104     while (clipboard) {
1105         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1106         clipboard = g_slist_remove(clipboard, clipboard->data);
1107     }
1109     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1111     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1112         SPStyle *const query = sp_style_new(SP_ACTIVE_DOCUMENT);
1113         if (sp_desktop_query_style_all (desktop, query)) {
1114             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1115             sp_set_style_clipboard (css);
1116         }
1117         sp_style_unref(query);
1118     }
1120     size_clipboard = selection->bounds();
1122     g_slist_free ((GSList *) items);
1125 //____________________________________________________________________________
1127 /** Paste the bitmap in the clipboard if one is in there.
1128         The bitmap is saved to a PNG file then imported into the document
1130         @return true if a bitmap was detected and pasted; false if no bitmap
1131 */
1132 static bool pastedPicFromClipboard()
1134         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1135         SPDocument *doc = SP_ACTIVE_DOCUMENT;
1136         if ( desktop == NULL || doc == NULL)
1137                 return false;
1139         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1140         Glib::RefPtr<Gdk::Pixbuf> pic = refClipboard->wait_for_image();
1142         // Stop if the system clipboard doesn't have a bitmap.
1143         if ( pic == 0 )
1144         {
1145                 return false;
1146         } //if
1147         else
1148         {
1149                 // Write into a file, then import the file into the document.
1150                 // Make a file name based on current time; use the current working dir.
1151                 time_t rawtime;
1152                 char filename[50];
1153                 const char* path;
1155                 time ( &rawtime );
1156                 strftime (filename,50,"pastedpic_%m%d%Y_%H%M%S.png",localtime( &rawtime ));
1157                 path = (char *)prefs_get_string_attribute("dialogs.save_as", "path");
1158                 Glib::ustring finalPath = path;
1159                 finalPath.append(G_DIR_SEPARATOR_S).append(filename);
1160                 pic->save( finalPath, "png" );
1161                 file_import(doc, finalPath, NULL);
1163                 // Clear the clipboard so that the bitmap in there won't always over
1164                 // ride the normal inkscape clipboard.This isn't the ideal solution.
1165                 refClipboard->set_text("");
1166                 return true;
1167         } //else
1169         return false;
1170 } //pastedPicFromClipboard
1172 //____________________________________________________________________________
1174 void sp_selection_paste(bool in_place)
1176     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1178     if (desktop == NULL) {
1179         return;
1180     }
1182     SPDocument *document = sp_desktop_document(desktop);
1184     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1185         return;
1186     }
1188     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1190     if (tools_isactive (desktop, TOOLS_TEXT)) {
1191         if (sp_text_paste_inline(desktop->event_context))
1192             return; // pasted from system clipboard into text, nothing else to do
1193     }
1195     // check if something is in the clipboard
1197     // Stop if successfully pasted a clipboard bitmap.
1198     if ( pastedPicFromClipboard() )
1199         return;
1202     if (clipboard == NULL) {
1203         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing in the clipboard."));
1204         return;
1205     }
1207     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1208     // add pasted objects to selection
1209     selection->setReprList((GSList const *) copied);
1210     g_slist_free (copied);
1212     if (!in_place) {
1213         sp_document_ensure_up_to_date(document);
1215         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1216         NR::Point m( desktop->point() );
1217         if (sel_bbox) {
1218             m -= sel_bbox->midpoint();
1219         }
1221         sp_selection_move_relative(selection, m);
1222     }
1224     sp_document_done(document, SP_VERB_EDIT_PASTE, _("Paste"));
1227 void sp_selection_paste_style()
1229     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1230     if (desktop == NULL) return;
1232     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1234     // check if something is in the clipboard
1235     if (style_clipboard == NULL) {
1236         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the style clipboard."));
1237         return;
1238     }
1240     // check if something is selected
1241     if (selection->isEmpty()) {
1242         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1243         return;
1244     }
1246     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1248     sp_desktop_set_style (desktop, style_clipboard);
1250     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1251                      _("Paste style"));
1254 void sp_selection_paste_livepatheffect()
1256     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1257     if (desktop == NULL) return;
1259     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1261     // check if something is in the clipboard
1262     if (clipboard == NULL) {
1263         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1264         return;
1265     }
1267     // check if something is selected
1268     if (selection->isEmpty()) {
1269         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste live path effect to."));
1270         return;
1271     }
1273     SPDocument *doc = sp_desktop_document(desktop);
1274     paste_defs (&defs_clipboard, doc);
1276     Inkscape::XML::Node *repr = (Inkscape::XML::Node *) clipboard->data;
1277     char const *effecturi = repr->attribute("inkscape:path-effect");
1278     if (!effecturi) {
1279         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Clipboard does not contain a live path effect."));
1280         return;
1281     }
1283     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1284         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1285         if ( item && SP_IS_SHAPE(item) ) {
1286             SPShape * shape = SP_SHAPE(item);
1288             // create a private LPE object!
1289             SPObject * obj = sp_uri_reference_resolve(doc, effecturi);
1290             LivePathEffectObject * lpeobj = LIVEPATHEFFECT(obj)->fork_private_if_necessary(0);
1291             
1292             sp_shape_set_path_effect(shape, lpeobj);
1294             // set inkscape:original-d for paths. the other shapes don't need this.
1295             if ( SP_IS_PATH(item) ) {
1296                 Inkscape::XML::Node *pathrepr = SP_OBJECT_REPR(item);
1297                 if ( ! pathrepr->attribute("inkscape:original-d") ) {
1298                     pathrepr->setAttribute("inkscape:original-d", pathrepr->attribute("d"));
1299                 }
1300             }
1301         }
1302     }
1304     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1305                      _("Paste live path effect"));
1308 void sp_selection_paste_size (bool apply_x, bool apply_y)
1310     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1311     if (desktop == NULL) return;
1313     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1315     // check if something is in the clipboard
1316     if (!size_clipboard) {
1317         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1318         return;
1319     }
1321     // check if something is selected
1322     if (selection->isEmpty()) {
1323         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1324         return;
1325     }
1327     NR::Maybe<NR::Rect> current = selection->bounds();
1328     if ( !current || current->isEmpty() ) {
1329         return;
1330     }
1332     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1333     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1335     sp_selection_scale_relative (selection, current->midpoint(),
1336                                  NR::scale(
1337                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1338                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1340     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1341                      _("Paste size"));
1344 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1346     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1347     if (desktop == NULL) return;
1349     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1351     // check if something is in the clipboard
1352     if ( !size_clipboard ) {
1353         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1354         return;
1355     }
1357     // check if something is selected
1358     if (selection->isEmpty()) {
1359         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1360         return;
1361     }
1363     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1364         SPItem *item = SP_ITEM(l->data);
1366         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1367         if ( !current || current->isEmpty() ) {
1368             continue;
1369         }
1371         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1372         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1374         sp_item_scale_rel (item,
1375                                  NR::scale(
1376                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1377                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1379     }
1381     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1382                      _("Paste size separately"));
1385 void sp_selection_to_next_layer ()
1387     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1389     Inkscape::Selection *selection = sp_desktop_selection(dt);
1391     // check if something is selected
1392     if (selection->isEmpty()) {
1393         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1394         return;
1395     }
1397     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1399     bool no_more = false; // Set to true, if no more layers above
1400     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1401     if (next) {
1402         GSList *temp_clip = NULL;
1403         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
1404         sp_selection_delete_impl (items, false, false);
1405         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1406         GSList *copied;
1407         if(next) {
1408             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1409         } else {
1410             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1411             no_more = true;
1412         }
1413         selection->setReprList((GSList const *) copied);
1414         g_slist_free (copied);
1415         if (temp_clip) g_slist_free (temp_clip);
1416         if (next) dt->setCurrentLayer(next);
1417         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1418                          _("Raise to next layer"));
1419     } else {
1420         no_more = true;
1421     }
1423     if (no_more) {
1424         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1425     }
1427     g_slist_free ((GSList *) items);
1430 void sp_selection_to_prev_layer ()
1432     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1434     Inkscape::Selection *selection = sp_desktop_selection(dt);
1436     // check if something is selected
1437     if (selection->isEmpty()) {
1438         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1439         return;
1440     }
1442     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1444     bool no_more = false; // Set to true, if no more layers below
1445     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1446     if (next) {
1447         GSList *temp_clip = NULL;
1448         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
1449         sp_selection_delete_impl (items, false, false);
1450         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1451         GSList *copied;
1452         if(next) {
1453             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1454         } else {
1455             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1456             no_more = true;
1457         }
1458         selection->setReprList((GSList const *) copied);
1459         g_slist_free (copied);
1460         if (temp_clip) g_slist_free (temp_clip);
1461         if (next) dt->setCurrentLayer(next);
1462         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1463                          _("Lower to previous layer"));
1464     } else {
1465         no_more = true;
1466     }
1468     if (no_more) {
1469         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1470     }
1472     g_slist_free ((GSList *) items);
1475 bool
1476 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1478     bool contains_original = false;
1480     bool is_use = SP_IS_USE(item);
1481     SPItem *item_use = item;
1482     SPItem *item_use_first = item;
1483     while (is_use && item_use && !contains_original)
1484     {
1485         item_use = sp_use_get_original (SP_USE(item_use));
1486         contains_original |= selection->includes(item_use);
1487         if (item_use == item_use_first)
1488             break;
1489         is_use = SP_IS_USE(item_use);
1490     }
1492     // If it's a tref, check whether the object containing the character
1493     // data is part of the selection
1494     if (!contains_original && SP_IS_TREF(item)) {
1495         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1496     }
1498     return contains_original;
1502 bool
1503 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1505     bool clone_with_original = false;
1506     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1507         SPItem *item = SP_ITEM(l->data);
1508         clone_with_original |= selection_contains_original(item, selection);
1509         if (clone_with_original)
1510             break;
1511     }
1512     return clone_with_original;
1516 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1517 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1518 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1519 that case, items are already in the new position, but the repr is in the old, and this function
1520 then simply updates the repr from item->transform.
1521  */
1522 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1524     if (selection->isEmpty())
1525         return;
1527     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1528         SPItem *item = SP_ITEM(l->data);
1530         NR::Point old_center(0,0);
1531         if (set_i2d && item->isCenterSet())
1532             old_center = item->getCenter();
1534 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1535          At the time of writing, this is the only place to re-enable. */
1536         sp_item_update_cns(*item, selection->desktop());
1537 #endif
1539         // we're moving both a clone and its original or any ancestor in clone chain?
1540         bool transform_clone_with_original = selection_contains_original(item, selection);
1541         // ...both a text-on-path and its path?
1542         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)))) ));
1543         // ...both a flowtext and its frame?
1544         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)
1545         // ...both an offset and its source?
1546         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1548         // If we're moving a connector, we want to detach it
1549         // from shapes that aren't part of the selection, but
1550         // leave it attached if they are
1551         if (cc_item_is_connector(item)) {
1552             SPItem *attItem[2];
1553             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1555             for (int n = 0; n < 2; ++n) {
1556                 if (!selection->includes(attItem[n])) {
1557                     sp_conn_end_detach(item, n);
1558                 }
1559             }
1560         }
1562         // "clones are unmoved when original is moved" preference
1563         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1564         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1565         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1567         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1568         // transform of its original and respond to it itself. Without this, a clone is doubly
1569         // transformed, very unintuitive.
1570       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1571       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1572       // Same for linked offset if we are also moving its source: do not move it.
1573         if (transform_textpath_with_path || transform_offset_with_source) {
1574                 // restore item->transform field from the repr, in case it was changed by seltrans
1575             sp_object_read_attr (SP_OBJECT (item), "transform");
1577         } else if (transform_flowtext_with_frame) {
1578             // apply the inverse of the region's transform to the <use> so that the flow remains
1579             // the same (even though the output itself gets transformed)
1580             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1581                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1582                     continue;
1583                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1584                     if (!SP_IS_USE(use)) continue;
1585                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1586                 }
1587             }
1588         } else if (transform_clone_with_original) {
1589             // We are transforming a clone along with its original. The below matrix juggling is
1590             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1591             // transform and its move compensation are both cancelled out.
1593             // restore item->transform field from the repr, in case it was changed by seltrans
1594             sp_object_read_attr (SP_OBJECT (item), "transform");
1596             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1597             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1598             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1599             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1600             NR::Matrix result = t_inv * item->transform * t;
1602             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1603                 // we need to cancel out the move compensation, too
1605                 // find out the clone move, same as in sp_use_move_compensate
1606                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1607                 NR::Matrix clone_move = parent.inverse() * t * parent;
1609                 if (prefs_parallel) {
1610                     NR::Matrix move = result * clone_move * t_inv;
1611                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1613                 } else if (prefs_unmoved) {
1614                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1615                     //    clone_move = NR::identity();
1616                     NR::Matrix move = result * clone_move;
1617                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1618                 }
1620             } else {
1621                 // just apply the result
1622                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1623             }
1625         } else {
1626             if (set_i2d) {
1627                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1628             }
1629             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1630         }
1632         // if we're moving the actual object, not just updating the repr, we can transform the
1633         // center by the same matrix (only necessary for non-translations)
1634         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1635             item->setCenter(old_center * affine);
1636             SP_OBJECT(item)->updateRepr();
1637         }
1638     }
1641 void sp_selection_remove_transform()
1643     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1644     if (desktop == NULL)
1645         return;
1647     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1649     GSList const *l = (GSList *) selection->reprList();
1650     while (l != NULL) {
1651         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1652         l = l->next;
1653     }
1655     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1656                      _("Remove transform"));
1659 void
1660 sp_selection_scale_absolute(Inkscape::Selection *selection,
1661                             double const x0, double const x1,
1662                             double const y0, double const y1)
1664     if (selection->isEmpty())
1665         return;
1667     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1668     if ( !bbox || bbox->isEmpty() ) {
1669         return;
1670     }
1672     NR::translate const p2o(-bbox->min());
1674     NR::scale const newSize(x1 - x0,
1675                             y1 - y0);
1676     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1677     NR::translate const o2n(x0, y0);
1678     NR::Matrix const final( p2o * scale * o2n );
1680     sp_selection_apply_affine(selection, final);
1684 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1686     if (selection->isEmpty())
1687         return;
1689     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1691     if ( !bbox || bbox->isEmpty() ) {
1692         return;
1693     }
1695     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1696     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1697          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1698     {
1699         return;
1700     }
1702     NR::translate const n2d(-align);
1703     NR::translate const d2n(align);
1704     NR::Matrix const final( n2d * scale * d2n );
1705     sp_selection_apply_affine(selection, final);
1708 void
1709 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1711     NR::translate const d2n(center);
1712     NR::translate const n2d(-center);
1713     NR::rotate const rotate(rotate_degrees(angle_degrees));
1714     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1715     sp_selection_apply_affine(selection, final);
1718 void
1719 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1721     NR::translate const d2n(align);
1722     NR::translate const n2d(-align);
1723     NR::Matrix const skew(1, dy,
1724                           dx, 1,
1725                           0, 0);
1726     NR::Matrix const final( n2d * skew * d2n );
1727     sp_selection_apply_affine(selection, final);
1730 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1732     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1735 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1737     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1741 /**
1742  * \brief sp_selection_rotate_90
1743  *
1744  * This function rotates selected objects 90 degrees clockwise.
1745  *
1746  */
1748 void sp_selection_rotate_90_cw()
1750     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1752     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1754     if (selection->isEmpty())
1755         return;
1757     GSList const *l = selection->itemList();
1758     NR::rotate const rot_neg_90(NR::Point(0, -1));
1759     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1760         SPItem *item = SP_ITEM(l2->data);
1761         sp_item_rotate_rel(item, rot_neg_90);
1762     }
1764     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1765                      _("Rotate 90&#176; CW"));
1769 /**
1770  * \brief sp_selection_rotate_90_ccw
1771  *
1772  * This function rotates selected objects 90 degrees counter-clockwise.
1773  *
1774  */
1776 void sp_selection_rotate_90_ccw()
1778     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1780     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1782     if (selection->isEmpty())
1783         return;
1785     GSList const *l = selection->itemList();
1786     NR::rotate const rot_neg_90(NR::Point(0, 1));
1787     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1788         SPItem *item = SP_ITEM(l2->data);
1789         sp_item_rotate_rel(item, rot_neg_90);
1790     }
1792     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1793                      _("Rotate 90&#176; CCW"));
1796 void
1797 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1799     if (selection->isEmpty())
1800         return;
1802     NR::Maybe<NR::Point> center = selection->center();
1803     if (!center) {
1804         return;
1805     }
1807     sp_selection_rotate_relative(selection, *center, angle_degrees);
1809     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1810                            ( ( angle_degrees > 0 )
1811                              ? "selector:rotate:ccw"
1812                              : "selector:rotate:cw" ),
1813                            SP_VERB_CONTEXT_SELECT,
1814                            _("Rotate"));
1817 /**
1818 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1819 */
1820 void
1821 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1823     if (selection->isEmpty())
1824         return;
1826     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1827     NR::Maybe<NR::Point> center = selection->center();
1829     if ( !bbox || !center ) {
1830         return;
1831     }
1833     gdouble const zoom = selection->desktop()->current_zoom();
1834     gdouble const zmove = angle / zoom;
1835     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1837     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1839     sp_selection_rotate_relative(selection, *center, zangle);
1841     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1842                            ( (angle > 0)
1843                              ? "selector:rotate:ccw"
1844                              : "selector:rotate:cw" ),
1845                            SP_VERB_CONTEXT_SELECT,
1846                            _("Rotate by pixels"));
1849 void
1850 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1852     if (selection->isEmpty())
1853         return;
1855     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1856     if (!bbox) {
1857         return;
1858     }
1860     NR::Point const center(bbox->midpoint());
1862     // you can't scale "do nizhe pola" (below zero)
1863     double const max_len = bbox->maxExtent();
1864     if ( max_len + grow <= 1e-3 ) {
1865         return;
1866     }
1868     double const times = 1.0 + grow / max_len;
1869     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1871     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1872                            ( (grow > 0)
1873                              ? "selector:scale:larger"
1874                              : "selector:scale:smaller" ),
1875                            SP_VERB_CONTEXT_SELECT,
1876                            _("Scale"));
1879 void
1880 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1882     sp_selection_scale(selection,
1883                        grow_pixels / selection->desktop()->current_zoom());
1886 void
1887 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1889     if (selection->isEmpty())
1890         return;
1892     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1894     if (!sel_bbox) {
1895         return;
1896     }
1898     NR::Point const center(sel_bbox->midpoint());
1899     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1900     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1901                      _("Scale by whole factor"));
1904 void
1905 sp_selection_move(gdouble dx, gdouble dy)
1907     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1908     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1909     if (selection->isEmpty()) {
1910         return;
1911     }
1913     sp_selection_move_relative(selection, dx, dy);
1915     if (dx == 0) {
1916         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1917                                _("Move vertically"));
1918     } else if (dy == 0) {
1919         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1920                                _("Move horizontally"));
1921     } else {
1922         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1923                          _("Move"));
1924     }
1927 void
1928 sp_selection_move_screen(gdouble dx, gdouble dy)
1930     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1932     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1933     if (selection->isEmpty()) {
1934         return;
1935     }
1937     // same as sp_selection_move but divide deltas by zoom factor
1938     gdouble const zoom = desktop->current_zoom();
1939     gdouble const zdx = dx / zoom;
1940     gdouble const zdy = dy / zoom;
1941     sp_selection_move_relative(selection, zdx, zdy);
1943     if (dx == 0) {
1944         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1945                                _("Move vertically by pixels"));
1946     } else if (dy == 0) {
1947         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1948                                _("Move horizontally by pixels"));
1949     } else {
1950         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1951                          _("Move"));
1952     }
1955 namespace {
1957 template <typename D>
1958 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1959                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1961 template <typename D>
1962 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1963                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1965 struct Forward {
1966     typedef SPObject *Iterator;
1968     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1969     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1970     static void dispose(Iterator /*i*/) {}
1972     static SPObject *object(Iterator i) { return i; }
1973     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1974 };
1976 struct Reverse {
1977     typedef GSList *Iterator;
1979     static Iterator children(SPObject *o) {
1980         return make_list(o->firstChild(), NULL);
1981     }
1982     static Iterator siblings_after(SPObject *o) {
1983         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1984     }
1985     static void dispose(Iterator i) {
1986         g_slist_free(i);
1987     }
1989     static SPObject *object(Iterator i) {
1990         return reinterpret_cast<SPObject *>(i->data);
1991     }
1992     static Iterator next(Iterator i) { return i->next; }
1994 private:
1995     static GSList *make_list(SPObject *object, SPObject *limit) {
1996         GSList *list=NULL;
1997         while ( object != limit ) {
1998             list = g_slist_prepend(list, object);
1999             object = SP_OBJECT_NEXT(object);
2000         }
2001         return list;
2002     }
2003 };
2007 void
2008 sp_selection_item_next(void)
2010     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2011     g_return_if_fail(desktop != NULL);
2012     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2014     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2015     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2016     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2018     SPObject *root;
2019     if (PREFS_SELECTION_ALL != inlayer) {
2020         root = selection->activeContext();
2021     } else {
2022         root = desktop->currentRoot();
2023     }
2025     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2027     if (item) {
2028         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2029         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2030             scroll_to_show_item(desktop, item);
2031         }
2032     }
2035 void
2036 sp_selection_item_prev(void)
2038     SPDocument *document = SP_ACTIVE_DOCUMENT;
2039     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2040     g_return_if_fail(document != NULL);
2041     g_return_if_fail(desktop != NULL);
2042     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2044     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
2045     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
2046     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
2048     SPObject *root;
2049     if (PREFS_SELECTION_ALL != inlayer) {
2050         root = selection->activeContext();
2051     } else {
2052         root = desktop->currentRoot();
2053     }
2055     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
2057     if (item) {
2058         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
2059         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
2060             scroll_to_show_item(desktop, item);
2061         }
2062     }
2065 void sp_selection_next_patheffect_param(SPDesktop * dt)
2067     if (!dt) return;
2069     Inkscape::Selection *selection = sp_desktop_selection(dt);
2070     if ( selection && !selection->isEmpty() ) {
2071         SPItem *item = selection->singleItem();
2072         if ( item && SP_IS_SHAPE(item)) {
2073             SPShape *shape = SP_SHAPE(item);
2074             if (sp_shape_has_path_effect(shape)) {
2075                 sp_shape_edit_next_param_oncanvas(shape, dt);
2076             } else {
2077                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
2078             }
2079         }
2080     }
2083 namespace {
2085 template <typename D>
2086 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
2087                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2089     SPObject *current=root;
2090     while (items) {
2091         SPItem *item=SP_ITEM(items->data);
2092         if ( root->isAncestorOf(item) &&
2093              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
2094         {
2095             current = item;
2096             break;
2097         }
2098         items = items->next;
2099     }
2101     GSList *path=NULL;
2102     while ( current != root ) {
2103         path = g_slist_prepend(path, current);
2104         current = SP_OBJECT_PARENT(current);
2105     }
2107     SPItem *next;
2108     // first, try from the current object
2109     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2110     g_slist_free(path);
2112     if (!next) { // if we ran out of objects, start over at the root
2113         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2114     }
2116     return next;
2119 template <typename D>
2120 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2121                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2123     typename D::Iterator children;
2124     typename D::Iterator iter;
2126     SPItem *found=NULL;
2128     if (path) {
2129         SPObject *object=reinterpret_cast<SPObject *>(path->data);
2130         g_assert(SP_OBJECT_PARENT(object) == root);
2131         if (desktop->isLayer(object)) {
2132             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2133         }
2134         iter = children = D::siblings_after(object);
2135     } else {
2136         iter = children = D::children(root);
2137     }
2139     while ( iter && !found ) {
2140         SPObject *object=D::object(iter);
2141         if (desktop->isLayer(object)) {
2142             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
2143                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2144             }
2145         } else if ( SP_IS_ITEM(object) &&
2146                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2147                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2148                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2149                     !desktop->isLayer(SP_ITEM(object)) )
2150         {
2151             found = SP_ITEM(object);
2152         }
2153         iter = D::next(iter);
2154     }
2156     D::dispose(children);
2158     return found;
2163 /**
2164  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2165  * \a item.
2166  */
2167 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2169     NR::Rect dbox = desktop->get_display_area();
2170     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2172     if ( sbox && dbox.contains(*sbox) == false ) {
2173         NR::Point const s_dt = sbox->midpoint();
2174         NR::Point const s_w = desktop->d2w(s_dt);
2175         NR::Point const d_dt = dbox.midpoint();
2176         NR::Point const d_w = desktop->d2w(d_dt);
2177         NR::Point const moved_w( d_w - s_w );
2178         gint const dx = (gint) moved_w[X];
2179         gint const dy = (gint) moved_w[Y];
2180         desktop->scroll_world(dx, dy);
2181     }
2185 void
2186 sp_selection_clone()
2188     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2189     if (desktop == NULL)
2190         return;
2192     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2194     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2196     // check if something is selected
2197     if (selection->isEmpty()) {
2198         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2199         return;
2200     }
2202     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2204     selection->clear();
2206     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2207     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2209     GSList *newsel = NULL;
2211     while (reprs) {
2212         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2213         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2215         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2216         sp_repr_set_attr(clone, "x", "0");
2217         sp_repr_set_attr(clone, "y", "0");
2218         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2220         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2221         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2223         // add the new clone to the top of the original's parent
2224         parent->appendChild(clone);
2226         newsel = g_slist_prepend(newsel, clone);
2227         reprs = g_slist_remove(reprs, sel_repr);
2228         Inkscape::GC::release(clone);
2229     }
2231     // TRANSLATORS: only translate "string" in "context|string".
2232     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2233     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2234                      Q_("action|Clone"));
2236     selection->setReprList(newsel);
2238     g_slist_free(newsel);
2241 void
2242 sp_selection_unlink()
2244     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2245     if (!desktop)
2246         return;
2248     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2250     if (selection->isEmpty()) {
2251         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2252         return;
2253     }
2255     // Get a copy of current selection.
2256     GSList *new_select = NULL;
2257     bool unlinked = false;
2258     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2259          items != NULL;
2260          items = items->next)
2261     {
2262         SPItem *item = (SPItem *) items->data;
2264         if (SP_IS_TEXT(item)) {
2265             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2267             if (tspan) {
2268                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2269             }
2271             // Set unlink to true, and fall into the next if which
2272             // will include this text item in the new selection
2273             unlinked = true;
2274         }
2276         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2277             // keep the non-use item in the new selection
2278             new_select = g_slist_prepend(new_select, item);
2279             continue;
2280         }
2282         SPItem *unlink;
2283         if (SP_IS_USE(item)) {
2284             unlink = sp_use_unlink(SP_USE(item));
2285         } else /*if (SP_IS_TREF(use))*/ {
2286             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2287         }
2289         unlinked = true;
2290         // Add ungrouped items to the new selection.
2291         new_select = g_slist_prepend(new_select, unlink);
2292     }
2294     if (new_select) { // set new selection
2295         selection->clear();
2296         selection->setList(new_select);
2297         g_slist_free(new_select);
2298     }
2299     if (!unlinked) {
2300         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2301     }
2303     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2304                      _("Unlink clone"));
2307 void
2308 sp_select_clone_original()
2310     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2311     if (desktop == NULL)
2312         return;
2314     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2316     SPItem *item = selection->singleItem();
2318     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.");
2320     // Check if other than two objects are selected
2321     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2322         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2323         return;
2324     }
2326     SPItem *original = NULL;
2327     if (SP_IS_USE(item)) {
2328         original = sp_use_get_original (SP_USE(item));
2329     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2330         original = sp_offset_get_source (SP_OFFSET(item));
2331     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2332         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2333     } else if (SP_IS_FLOWTEXT(item)) {
2334         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2335     } else { // it's an object that we don't know what to do with
2336         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2337         return;
2338     }
2340     if (!original) {
2341         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2342         return;
2343     }
2345     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2346         if (SP_IS_DEFS (o)) {
2347             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2348             return;
2349         }
2350     }
2352     if (original) {
2353         selection->clear();
2354         selection->set(original);
2355         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2356             scroll_to_show_item(desktop, original);
2357         }
2358     }
2362 void sp_selection_to_marker(bool apply)
2364     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2365     if (desktop == NULL)
2366         return;
2368     SPDocument *doc = sp_desktop_document(desktop);
2369     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2371     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2373     // check if something is selected
2374     if (selection->isEmpty()) {
2375         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2376         return;
2377     }
2379     sp_document_ensure_up_to_date(doc);
2380     NR::Maybe<NR::Rect> r = selection->bounds();
2381     if ( !r || r->isEmpty() ) {
2382         return;
2383     }
2385     // calculate the transform to be applied to objects to move them to 0,0
2386     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));
2387     move_p[NR::Y] = -move_p[NR::Y];
2388     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2390     GSList *items = g_slist_copy((GSList *) selection->itemList());
2392     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2394     // bottommost object, after sorting
2395     SPObject *parent = SP_OBJECT_PARENT (items->data);
2397     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2399     // remember the position of the first item
2400     gint pos = SP_OBJECT_REPR (items->data)->position();
2401     (void)pos; // TODO check why this was remembered
2403     // create a list of duplicates
2404     GSList *repr_copies = NULL;
2405     for (GSList *i = items; i != NULL; i = i->next) {
2406         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2407         repr_copies = g_slist_prepend (repr_copies, dup);
2408     }
2410     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2412     if (apply) {
2413         // delete objects so that their clones don't get alerted; this object will be restored shortly
2414         for (GSList *i = items; i != NULL; i = i->next) {
2415             SPObject *item = SP_OBJECT (i->data);
2416             item->deleteObject (false);
2417         }
2418     }
2420     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2421     // without disturbing clones.
2422     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2423     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2424     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2426     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2427                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2428                                                                                                 r->max()[NR::Y]))))
2429                                              * parent_transform.inverse() ),
2430                                            parent_transform * move);
2431     (void)mark_id;
2433     // restore compensation setting
2434     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2437     g_slist_free (items);
2439     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2440                       _("Objects to marker"));
2443 void
2444 sp_selection_tile(bool apply)
2446     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2447     if (desktop == NULL)
2448         return;
2450     SPDocument *doc = sp_desktop_document(desktop);
2451     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2453     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2455     // check if something is selected
2456     if (selection->isEmpty()) {
2457         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2458         return;
2459     }
2461     sp_document_ensure_up_to_date(doc);
2462     NR::Maybe<NR::Rect> r = selection->bounds();
2463     if ( !r || r->isEmpty() ) {
2464         return;
2465     }
2467     // calculate the transform to be applied to objects to move them to 0,0
2468     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2469     move_p[NR::Y] = -move_p[NR::Y];
2470     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2472     GSList *items = g_slist_copy((GSList *) selection->itemList());
2474     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2476     // bottommost object, after sorting
2477     SPObject *parent = SP_OBJECT_PARENT (items->data);
2479     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2481     // remember the position of the first item
2482     gint pos = SP_OBJECT_REPR (items->data)->position();
2484     // create a list of duplicates
2485     GSList *repr_copies = NULL;
2486     for (GSList *i = items; i != NULL; i = i->next) {
2487         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2488         repr_copies = g_slist_prepend (repr_copies, dup);
2489     }
2491     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2493     if (apply) {
2494         // delete objects so that their clones don't get alerted; this object will be restored shortly
2495         for (GSList *i = items; i != NULL; i = i->next) {
2496             SPObject *item = SP_OBJECT (i->data);
2497             item->deleteObject (false);
2498         }
2499     }
2501     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2502     // without disturbing clones.
2503     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2504     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2505     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2507     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2508                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2509                                                                                             r->max()[NR::Y]))))
2510                                          * parent_transform.inverse() ),
2511                                        parent_transform * move);
2513     // restore compensation setting
2514     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2516     if (apply) {
2517         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2518         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2520         NR::Point min = bounds.min() * parent_transform.inverse();
2521         NR::Point max = bounds.max() * parent_transform.inverse();
2523         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2524         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2525         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2526         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2528         // restore parent and position
2529         SP_OBJECT_REPR (parent)->appendChild(rect);
2530         rect->setPosition(pos > 0 ? pos : 0);
2531         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2533         Inkscape::GC::release(rect);
2535         selection->clear();
2536         selection->set(rectangle);
2537     }
2539     g_slist_free (items);
2541     sp_document_done (doc, SP_VERB_EDIT_TILE,
2542                       _("Objects to pattern"));
2545 void
2546 sp_selection_untile()
2548     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2549     if (desktop == NULL)
2550         return;
2552     SPDocument *doc = sp_desktop_document(desktop);
2553     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2555     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2557     // check if something is selected
2558     if (selection->isEmpty()) {
2559         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2560         return;
2561     }
2563     GSList *new_select = NULL;
2565     bool did = false;
2567     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2568          items != NULL;
2569          items = items->next) {
2571         SPItem *item = (SPItem *) items->data;
2573         SPStyle *style = SP_OBJECT_STYLE (item);
2575         if (!style || !style->fill.isPaintserver())
2576             continue;
2578         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2580         if (!SP_IS_PATTERN(server))
2581             continue;
2583         did = true;
2585         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2587         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2588         pat_transform *= item->transform;
2590         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2591             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2592             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2594            // FIXME: relink clones to the new canvas objects
2595            // use SPObject::setid when mental finishes it to steal ids of
2597             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2598             sp_document_ensure_up_to_date (doc);
2600             NR::Matrix transform( i->transform * pat_transform );
2601             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2603             new_select = g_slist_prepend(new_select, i);
2604         }
2606         SPCSSAttr *css = sp_repr_css_attr_new ();
2607         sp_repr_css_set_property (css, "fill", "none");
2608         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2609     }
2611     if (!did) {
2612         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2613     } else {
2614         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2615                          _("Pattern to objects"));
2616         selection->setList(new_select);
2617     }
2620 void
2621 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2623     if (selection->isEmpty()) {
2624         return;
2625     }
2627     GSList const *reprlst = selection->reprList();
2628     bool filename_search = TRUE;
2629     bool xdpi_search = TRUE;
2630     bool ydpi_search = TRUE;
2632     for(; reprlst != NULL &&
2633             filename_search &&
2634             xdpi_search &&
2635             ydpi_search;
2636         reprlst = reprlst->next) {
2637         gchar const *dpi_string;
2638         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2640         if (filename_search) {
2641             *filename = repr->attribute("inkscape:export-filename");
2642             if (*filename != NULL)
2643                 filename_search = FALSE;
2644         }
2646         if (xdpi_search) {
2647             dpi_string = NULL;
2648             dpi_string = repr->attribute("inkscape:export-xdpi");
2649             if (dpi_string != NULL) {
2650                 *xdpi = atof(dpi_string);
2651                 xdpi_search = FALSE;
2652             }
2653         }
2655         if (ydpi_search) {
2656             dpi_string = NULL;
2657             dpi_string = repr->attribute("inkscape:export-ydpi");
2658             if (dpi_string != NULL) {
2659                 *ydpi = atof(dpi_string);
2660                 ydpi_search = FALSE;
2661             }
2662         }
2663     }
2666 void
2667 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2669     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2670     gchar const *dpi_string;
2672     *filename = repr->attribute("inkscape:export-filename");
2674     dpi_string = NULL;
2675     dpi_string = repr->attribute("inkscape:export-xdpi");
2676     if (dpi_string != NULL) {
2677         *xdpi = atof(dpi_string);
2678     }
2680     dpi_string = NULL;
2681     dpi_string = repr->attribute("inkscape:export-ydpi");
2682     if (dpi_string != NULL) {
2683         *ydpi = atof(dpi_string);
2684     }
2687 void
2688 sp_selection_create_bitmap_copy ()
2690     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2691     if (desktop == NULL)
2692         return;
2694     SPDocument *document = sp_desktop_document(desktop);
2695     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2697     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2699     // check if something is selected
2700     if (selection->isEmpty()) {
2701         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2702         return;
2703     }
2705     // Get the bounding box of the selection
2706     NRRect bbox;
2707     sp_document_ensure_up_to_date (document);
2708     selection->bounds(&bbox);
2709     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2710         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2711     }
2713     // List of the items to show; all others will be hidden
2714     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2716     // Sort items so that the topmost comes last
2717     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2719     // Generate a random value from the current time (you may create bitmap from the same object(s)
2720     // multiple times, and this is done so that they don't clash)
2721     GTimeVal cu;
2722     g_get_current_time (&cu);
2723     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2725     // Create the filename
2726     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2727     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2728     // digits, and a few other chars, with "_"
2729     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2730     // Build the complete path by adding document->base if set
2731     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2733     //g_print ("%s\n", filepath);
2735     // Remember parent and z-order of the topmost one
2736     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2737     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2738     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2740     // Calculate resolution
2741     double res;
2742     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2743     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2744     if (0 < prefs_res) {
2745         // If it's given explicitly in prefs, take it
2746         res = prefs_res;
2747     } else if (0 < prefs_min) {
2748         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2749         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2750     } else {
2751         float hint_xdpi = 0, hint_ydpi = 0;
2752         char const *hint_filename;
2753         // take resolution hint from the selected objects
2754         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2755         if (hint_xdpi != 0) {
2756             res = hint_xdpi;
2757         } else {
2758             // take resolution hint from the document
2759             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2760             if (hint_xdpi != 0) {
2761                 res = hint_xdpi;
2762             } else {
2763                 // if all else fails, take the default 90 dpi
2764                 res = PX_PER_IN;
2765             }
2766         }
2767     }
2769     // The width and height of the bitmap in pixels
2770     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2771     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2773     // Find out if we have to run a filter
2774     gchar const *run = NULL;
2775     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2776     if (filter) {
2777         // filter command is given;
2778         // see if we have a parameter to pass to it
2779         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2780         if (param1) {
2781             if (param1[strlen(param1) - 1] == '%') {
2782                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2783                 gchar p1[256];
2784                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2785                 // the first param is always the image filename, the second is param1
2786                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2787             } else {
2788                 // otherwise pass the param1 unchanged
2789                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2790             }
2791         } else {
2792             // run without extra parameter
2793             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2794         }
2795     }
2797     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2798     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2799     NR::Matrix t;
2801     double shift_x = bbox.x0;
2802     double shift_y = bbox.y1;
2803     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2804         shift_x = round (shift_x);
2805         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2806     }
2807     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2809     // Do the export
2810     sp_export_png_file(document, filepath,
2811                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2812                    width, height, res, res,
2813                    (guint32) 0xffffff00,
2814                    NULL, NULL,
2815                    true,  /*bool force_overwrite,*/
2816                    items);
2818     g_slist_free (items);
2820     // Run filter, if any
2821     if (run) {
2822         g_print ("Running external filter: %s\n", run);
2823         system (run);
2824     }
2826     // Import the image back
2827     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2828     if (pb) {
2829         // Create the repr for the image
2830         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2831         repr->setAttribute("xlink:href", filename);
2832         repr->setAttribute("sodipodi:absref", filepath);
2833         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2834             sp_repr_set_svg_double(repr, "width", width);
2835             sp_repr_set_svg_double(repr, "height", height);
2836         } else {
2837             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2838             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2839         }
2841         // Write transform
2842         gchar *c=sp_svg_transform_write(t);
2843         repr->setAttribute("transform", c);
2844         g_free(c);
2846         // add the new repr to the parent
2847         parent->appendChild(repr);
2849         // move to the saved position
2850         repr->setPosition(pos > 0 ? pos + 1 : 1);
2852         // Set selection to the new image
2853         selection->clear();
2854         selection->add(repr);
2856         // Clean up
2857         Inkscape::GC::release(repr);
2858         gdk_pixbuf_unref (pb);
2860         // Complete undoable transaction
2861         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2862                           _("Create bitmap"));
2863     }
2865     g_free (filename);
2866     g_free (filepath);
2869 /**
2870  * \brief sp_selection_set_mask
2871  *
2872  * This function creates a mask or clipPath from selection
2873  * Two different modes:
2874  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2875  *       and is applied to current layer
2876  *  otherwise, topmost object is used as mask for other objects
2877  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2878  *
2879  */
2880 void
2881 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2883     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2884     if (desktop == NULL)
2885         return;
2887     SPDocument *doc = sp_desktop_document(desktop);
2888     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2890     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2892     // check if something is selected
2893     bool is_empty = selection->isEmpty();
2894     if ( apply_to_layer && is_empty) {
2895         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2896         return;
2897     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2898         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2899         return;
2900     }
2902     // FIXME: temporary patch to prevent crash!
2903     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2904     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2905     if (clone_with_original) {
2906         return; // in this version, you cannot clip/mask an object with its own clone
2907     }
2908     // /END FIXME
2910     sp_document_ensure_up_to_date(doc);
2912     GSList *items = g_slist_copy((GSList *) selection->itemList());
2914     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2916     // create a list of duplicates
2917     GSList *mask_items = NULL;
2918     GSList *apply_to_items = NULL;
2919     GSList *items_to_delete = NULL;
2920     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2921     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2923     if (apply_to_layer) {
2924         // all selected items are used for mask, which is applied to a layer
2925         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2927         for (GSList *i = items; i != NULL; i = i->next) {
2928             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2929             mask_items = g_slist_prepend (mask_items, dup);
2931             if (remove_original) {
2932                 SPObject *item = SP_OBJECT (i->data);
2933                 items_to_delete = g_slist_prepend (items_to_delete, item);
2934             }
2935         }
2936     } else if (!topmost) {
2937         // topmost item is used as a mask, which is applied to other items in a selection
2938         GSList *i = items;
2939         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2940         mask_items = g_slist_prepend (mask_items, dup);
2942         if (remove_original) {
2943             SPObject *item = SP_OBJECT (i->data);
2944             items_to_delete = g_slist_prepend (items_to_delete, item);
2945         }
2947         for (i = i->next; i != NULL; i = i->next) {
2948             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2949         }
2950     } else {
2951         GSList *i = NULL;
2952         for (i = items; NULL != i->next; i = i->next) {
2953             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2954         }
2956         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2957         mask_items = g_slist_prepend (mask_items, dup);
2959         if (remove_original) {
2960             SPObject *item = SP_OBJECT (i->data);
2961             items_to_delete = g_slist_prepend (items_to_delete, item);
2962         }
2963     }
2965     g_slist_free (items);
2966     items = NULL;
2968     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2969     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2970         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2971         // inverted object transform should be applied to a mask object,
2972         // as mask is calculated in user space (after applying transform)
2973         NR::Matrix maskTransform (item->transform.inverse());
2975         GSList *mask_items_dup = NULL;
2976         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2977             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2978             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2979         }
2981         gchar const *mask_id = NULL;
2982         if (apply_clip_path) {
2983             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2984         } else {
2985             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2986         }
2988         g_slist_free (mask_items_dup);
2989         mask_items_dup = NULL;
2991         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2992     }
2994     g_slist_free (mask_items);
2995     g_slist_free (apply_to_items);
2997     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2998         SPObject *item = SP_OBJECT (i->data);
2999         item->deleteObject (false);
3000     }
3001     g_slist_free (items_to_delete);
3003     if (apply_clip_path)
3004         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3005     else
3006         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3009 void sp_selection_unset_mask(bool apply_clip_path) {
3010     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
3011     if (desktop == NULL)
3012         return;
3014     SPDocument *doc = sp_desktop_document(desktop);
3015     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3016     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3018     // check if something is selected
3019     if (selection->isEmpty()) {
3020         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3021         return;
3022     }
3024     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
3025     sp_document_ensure_up_to_date(doc);
3027     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3028     std::map<SPObject*,SPItem*> referenced_objects;
3029     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3030         if (remove_original) {
3031             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3032             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3033             Inkscape::URIReference *uri_ref = NULL;
3035             if (apply_clip_path) {
3036                 uri_ref = item->clip_ref;
3037             } else {
3038                 uri_ref = item->mask_ref;
3039             }
3041             // collect distinct mask object (and associate with item to apply transform)
3042             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3043                 referenced_objects[uri_ref->getObject()] = item;
3044             }
3045         }
3047         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3048     }
3050     // restore mask objects into a document
3051     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3052         SPObject *obj = (*it).first;
3053         GSList *items_to_move = NULL;
3054         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3055             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3056             items_to_move = g_slist_prepend (items_to_move, copy);
3057         }
3059         if (!obj->isReferenced()) {
3060             // delete from defs if no other object references this mask
3061             obj->deleteObject(false);
3062         }
3064         // remember parent and position of the item to which the clippath/mask was applied
3065         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3066         gint pos = SP_OBJECT_REPR((*it).second)->position();
3068         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3069             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3071             // insert into parent, restore pos
3072             parent->appendChild(repr);
3073             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3075             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
3076             selection->add(repr);
3078             // transform mask, so it is moved the same spot where mask was applied
3079             NR::Matrix transform (mask_item->transform);
3080             transform *= (*it).second->transform;
3081             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3082         }
3084         g_slist_free (items_to_move);
3085     }
3087     if (apply_clip_path)
3088         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3089     else
3090         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3093 void fit_canvas_to_selection(SPDesktop *desktop) {
3094     g_return_if_fail(desktop != NULL);
3095     SPDocument *doc = sp_desktop_document(desktop);
3097     g_return_if_fail(doc != NULL);
3098     g_return_if_fail(desktop->selection != NULL);
3100     if (desktop->selection->isEmpty()) {
3101         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3102         return;
3103     }
3104     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
3105     if (bbox && !bbox->isEmpty()) {
3106         doc->fitToRect(*bbox);
3107     }
3108 };
3110 void fit_canvas_to_drawing(SPDocument *doc) {
3111     g_return_if_fail(doc != NULL);
3113     sp_document_ensure_up_to_date(doc);
3114     SPItem const *const root = SP_ITEM(doc->root);
3115     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
3116     if (bbox && !bbox->isEmpty()) {
3117         doc->fitToRect(*bbox);
3118     }
3119 };
3121 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3122     g_return_if_fail(desktop != NULL);
3123     SPDocument *doc = sp_desktop_document(desktop);
3125     g_return_if_fail(doc != NULL);
3126     g_return_if_fail(desktop->selection != NULL);
3128     if (desktop->selection->isEmpty()) {
3129         fit_canvas_to_drawing(doc);
3130     } else {
3131         fit_canvas_to_selection(desktop);
3132     }
3134     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
3135                      _("Fit page to selection"));
3136 };
3138 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3139     // don't operate on layers
3140     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3141         f(SP_ITEM(root), desktop);
3142     }
3143     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3144         //don't recurse into locked layers
3145         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3146             itemtree_map(f, iter, desktop);
3147         }
3148     }
3151 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3152     if (item->isLocked()) {
3153         item->setLocked(FALSE);
3154     }
3157 static void unhide(SPItem *item, SPDesktop *desktop) {
3158     if (desktop->itemIsHidden(item)) {
3159         item->setExplicitlyHidden(FALSE);
3160     }
3163 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3164     if (!dt) return;
3166     SPObject *root;
3167     if (layer_only) {
3168         root = dt->currentLayer();
3169     } else {
3170         root = dt->currentRoot();
3171     }
3173     itemtree_map(f, root, dt);
3176 void unlock_all(SPDesktop *dt) {
3177     process_all(&unlock, dt, true);
3180 void unlock_all_in_all_layers(SPDesktop *dt) {
3181     process_all(&unlock, dt, false);
3184 void unhide_all(SPDesktop *dt) {
3185     process_all(&unhide, dt, true);
3188 void unhide_all_in_all_layers(SPDesktop *dt) {
3189     process_all(&unhide, dt, false);
3193 GSList * sp_selection_get_clipboard() {
3194     return clipboard;
3198 /*
3199   Local Variables:
3200   mode:c++
3201   c-file-style:"stroustrup"
3202   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3203   indent-tabs-mode:nil
3204   fill-column:99
3205   End:
3206 */
3207 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :