Code

Make linked offsets respect "Relink duplicated clones" settings
[inkscape.git] / src / selection-chemistry.cpp
1 /** @file
2  * @brief Miscellanous operations on selected items
3  */
4 /* Authors:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *   Frank Felfe <innerspace@iname.com>
7  *   MenTaLguY <mental@rydia.net>
8  *   bulia byak <buliabyak@users.sf.net>
9  *   Andrius R. <knutux@gmail.com>
10  *   Jon A. Cruz <jon@joncruz.org>
11  *   Martin Sucha <martin.sucha-inkscape@jts-sro.sk>
12  *
13  * Copyright (C) 1999-2010 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 // TOOD fixme: This should be moved into preference repr
26 SPCycleType SP_CYCLING = SP_CYCLE_FOCUS;
29 #include <gtkmm/clipboard.h>
31 #include "svg/svg.h"
32 #include "desktop.h"
33 #include "desktop-style.h"
34 #include "dir-util.h"
35 #include "selection.h"
36 #include "tools-switch.h"
37 #include "desktop-handles.h"
38 #include "message-stack.h"
39 #include "sp-item-transform.h"
40 #include "marker.h"
41 #include "sp-use.h"
42 #include "sp-textpath.h"
43 #include "sp-tspan.h"
44 #include "sp-tref.h"
45 #include "sp-flowtext.h"
46 #include "sp-flowregion.h"
47 #include "sp-image.h"
48 #include "text-editing.h"
49 #include "text-context.h"
50 #include "connector-context.h"
51 #include "sp-path.h"
52 #include "sp-conn-end.h"
53 #include "dropper-context.h"
54 #include <glibmm/i18n.h>
55 #include "libnr/nr-matrix-rotate-ops.h"
56 #include "libnr/nr-matrix-translate-ops.h"
57 #include "libnr/nr-scale-ops.h"
58 #include <libnr/nr-matrix-ops.h>
59 #include <2geom/transforms.h>
60 #include "xml/repr.h"
61 #include "xml/rebase-hrefs.h"
62 #include "style.h"
63 #include "document-private.h"
64 #include "sp-gradient.h"
65 #include "sp-gradient-reference.h"
66 #include "sp-linear-gradient-fns.h"
67 #include "sp-pattern.h"
68 #include "sp-radial-gradient-fns.h"
69 #include "gradient-context.h"
70 #include "sp-namedview.h"
71 #include "preferences.h"
72 #include "sp-offset.h"
73 #include "sp-clippath.h"
74 #include "sp-mask.h"
75 #include "file.h"
76 #include "helper/png-write.h"
77 #include "layer-fns.h"
78 #include "context-fns.h"
79 #include <map>
80 #include <cstring>
81 #include <string>
82 #include "helper/units.h"
83 #include "sp-item.h"
84 #include "box3d.h"
85 #include "persp3d.h"
86 #include "unit-constants.h"
87 #include "xml/simple-document.h"
88 #include "sp-filter-reference.h"
89 #include "gradient-drag.h"
90 #include "uri-references.h"
91 #include "libnr/nr-convert2geom.h"
92 #include "display/curve.h"
93 #include "display/canvas-bpath.h"
94 #include "inkscape-private.h"
95 #include "path-chemistry.h"
96 #include "ui/tool/control-point-selection.h"
97 #include "ui/tool/multi-path-manipulator.h"
99 #include "enums.h"
100 #include "sp-item-group.h"
102 // For clippath editing
103 #include "tools-switch.h"
104 #include "ui/tool/node-tool.h"
106 #include "ui/clipboard.h"
108 using Geom::X;
109 using Geom::Y;
111 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
112 because the layer manipulation code uses them. It should be rewritten specifically
113 for that purpose. */
117 namespace Inkscape {
119 void SelectionHelper::selectAll(SPDesktop *dt)
121     if (tools_isactive(dt, TOOLS_NODES)) {
122         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
123         if (!nt->_multipath->empty()) {
124             nt->_multipath->selectSubpaths();
125             return;
126         }
127     }
128     sp_edit_select_all(dt);
131 void SelectionHelper::selectAllInAll(SPDesktop *dt)
133     if (tools_isactive(dt, TOOLS_NODES)) {
134         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
135         nt->_selected_nodes->selectAll();
136     } else {
137         sp_edit_select_all_in_all_layers(dt);
138     }
141 void SelectionHelper::selectNone(SPDesktop *dt)
143     if (tools_isactive(dt, TOOLS_NODES)) {
144         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
145         nt->_selected_nodes->clear();
146     } else {
147         sp_desktop_selection(dt)->clear();
148     }
151 void SelectionHelper::invert(SPDesktop *dt)
153     if (tools_isactive(dt, TOOLS_NODES)) {
154         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
155         nt->_multipath->invertSelectionInSubpaths();
156     } else {
157         sp_edit_invert(dt);
158     }
161 void SelectionHelper::invertAllInAll(SPDesktop *dt)
163     if (tools_isactive(dt, TOOLS_NODES)) {
164         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
165         nt->_selected_nodes->invertSelection();
166     } else {
167         sp_edit_invert_in_all_layers(dt);
168     }
171 void SelectionHelper::reverse(SPDesktop *dt)
173     // TODO make this a virtual method of event context!
174     if (tools_isactive(dt, TOOLS_NODES)) {
175         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
176         nt->_multipath->reverseSubpaths();
177     } else {
178         sp_selected_path_reverse(dt);
179     }
182 void SelectionHelper::selectNext(SPDesktop *dt)
184     SPEventContext *ec = dt->event_context;
185     if (tools_isactive(dt, TOOLS_NODES)) {
186         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
187         nt->_multipath->shiftSelection(1);
188     } else if (tools_isactive(dt, TOOLS_GRADIENT)
189                && ec->_grdrag->isNonEmpty()) {
190         sp_gradient_context_select_next(ec);
191     } else {
192         sp_selection_item_next(dt);
193     }
196 void SelectionHelper::selectPrev(SPDesktop *dt)
198     SPEventContext *ec = dt->event_context;
199     if (tools_isactive(dt, TOOLS_NODES)) {
200         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
201         nt->_multipath->shiftSelection(-1);
202     } else if (tools_isactive(dt, TOOLS_GRADIENT)
203                && ec->_grdrag->isNonEmpty()) {
204         sp_gradient_context_select_prev(ec);
205     } else {
206         sp_selection_item_prev(dt);
207     }
210 } // namespace Inkscape
213 /**
214  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
215  * then prepends the copy to 'clip'.
216  */
217 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
219     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
221     // copy complete inherited style
222     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
223     sp_repr_css_set(copy, css, "style");
224     sp_repr_css_attr_unref(css);
226     // write the complete accumulated transform passed to us
227     // (we're dealing with unattached repr, so we write to its attr
228     // instead of using sp_item_set_transform)
229     gchar *affinestr=sp_svg_transform_write(full_t);
230     copy->setAttribute("transform", affinestr);
231     g_free(affinestr);
233     *clip = g_slist_prepend(*clip, copy);
236 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
238     // Sort items:
239     GSList *sorted_items = g_slist_copy((GSList *) items);
240     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
242     // Copy item reprs:
243     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
244         sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
245     }
247     *clip = g_slist_reverse(*clip);
248     g_slist_free((GSList *) sorted_items);
251 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
253     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
255     GSList *copied = NULL;
256     // add objects to document
257     for (GSList *l = *clip; l != NULL; l = l->next) {
258         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
259         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
261         // premultiply the item transform by the accumulated parent transform in the paste layer
262         Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
263         if (!local.isIdentity()) {
264             gchar const *t_str = copy->attribute("transform");
265             Geom::Matrix item_t(Geom::identity());
266             if (t_str)
267                 sp_svg_transform_read(t_str, &item_t);
268             item_t *= local.inverse();
269             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
270             gchar *affinestr=sp_svg_transform_write(item_t);
271             copy->setAttribute("transform", affinestr);
272             g_free(affinestr);
273         }
275         parent->appendChildRepr(copy);
276         copied = g_slist_prepend(copied, copy);
277         Inkscape::GC::release(copy);
278     }
279     return copied;
282 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
284     for (GSList const *i = items ; i ; i = i->next ) {
285         sp_object_ref((SPObject *)i->data, NULL);
286     }
287     for (GSList const *i = items; i != NULL; i = i->next) {
288         SPItem *item = reinterpret_cast<SPItem *>(i->data);
289         item->deleteObject(propagate, propagate_descendants);
290         sp_object_unref(item, NULL);
291     }
295 void sp_selection_delete(SPDesktop *desktop)
297     if (desktop == NULL) {
298         return;
299     }
301     if (tools_isactive(desktop, TOOLS_TEXT))
302         if (sp_text_delete_selection(desktop->event_context)) {
303             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
304                              _("Delete text"));
305             return;
306         }
308     Inkscape::Selection *selection = sp_desktop_selection(desktop);
310     // check if something is selected
311     if (selection->isEmpty()) {
312         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
313         return;
314     }
316     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
317     selection->clear();
318     sp_selection_delete_impl(selected);
319     g_slist_free((GSList *) selected);
321     /* a tool may have set up private information in it's selection context
322      * that depends on desktop items.  I think the only sane way to deal with
323      * this currently is to reset the current tool, which will reset it's
324      * associated selection context.  For example: deleting an object
325      * while moving it around the canvas.
326      */
327     tools_switch( desktop, tools_active( desktop ) );
329     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
330                      _("Delete"));
333 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
335     if (!obj)
336         return;
338     ids.push_back(obj->getId());
340     if (SP_IS_GROUP(obj)) {
341         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
342             add_ids_recursive(ids, child);
343         }
344     }
347 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
349     if (desktop == NULL)
350         return;
352     SPDocument *doc = desktop->doc();
353     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
354     Inkscape::Selection *selection = sp_desktop_selection(desktop);
356     // check if something is selected
357     if (selection->isEmpty()) {
358         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
359         return;
360     }
362     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
364     selection->clear();
366     // sorting items from different parents sorts each parent's subset without possibly mixing
367     // them, just what we need
368     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
370     GSList *newsel = NULL;
372     std::vector<const gchar *> old_ids;
373     std::vector<const gchar *> new_ids;
374     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
375     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
377     while (reprs) {
378         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
379         Inkscape::XML::Node *parent = old_repr->parent();
380         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
382         parent->appendChild(copy);
384         if (relink_clones) {
385             SPObject *old_obj = doc->getObjectByRepr(old_repr);
386             SPObject *new_obj = doc->getObjectByRepr(copy);
387             add_ids_recursive(old_ids, old_obj);
388             add_ids_recursive(new_ids, new_obj);
389         }
391         newsel = g_slist_prepend(newsel, copy);
392         reprs = g_slist_remove(reprs, reprs->data);
393         Inkscape::GC::release(copy);
394     }
396     if (relink_clones) {
398         g_assert(old_ids.size() == new_ids.size());
400         for (unsigned int i = 0; i < old_ids.size(); i++) {
401             const gchar *id = old_ids[i];
402             SPObject *old_clone = doc->getObjectById(id);
403             if (SP_IS_USE(old_clone)) {
404                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
405                 if (!orig) // orphaned
406                     continue;
407                 for (unsigned int j = 0; j < old_ids.size(); j++) {
408                     if (!strcmp(orig->getId(), old_ids[j])) {
409                         // we have both orig and clone in selection, relink
410                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
411                         gchar *newref = g_strdup_printf("#%s", new_ids[j]);
412                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
413                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
414                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
415                         g_free(newref);
416                     }
417                 }
418             } else if (SP_IS_OFFSET(old_clone)) {
419                 for (guint j = 0; j < old_ids.size(); j++) {
420                     if (!strcmp(SP_OFFSET(old_clone)->sourceHref+1, old_ids[j])) {
421                         gchar *newref = g_strdup_printf("#%s", new_ids[j]);
422                         doc->getObjectById(new_ids[i])->repr->setAttribute("xlink:href", newref);
423                         g_free(newref);
424                     }
425                 }
426             }
427         }
428     }
431     if ( !suppressDone ) {
432         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
433                          _("Duplicate"));
434     }
436     selection->setReprList(newsel);
438     g_slist_free(newsel);
441 void sp_edit_clear_all(SPDesktop *dt)
443     if (!dt)
444         return;
446     SPDocument *doc = sp_desktop_document(dt);
447     sp_desktop_selection(dt)->clear();
449     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
450     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
452     while (items) {
453         reinterpret_cast<SPObject*>(items->data)->deleteObject();
454         items = g_slist_remove(items, items->data);
455     }
457     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
458                      _("Delete all"));
461 GSList *
462 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
464     for (SPObject *child = sp_object_first_child(from) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
465         if (SP_IS_ITEM(child) &&
466             !desktop->isLayer(SP_ITEM(child)) &&
467             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
468             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
469             (!exclude || !g_slist_find((GSList *) exclude, child))
470             )
471         {
472             list = g_slist_prepend(list, SP_ITEM(child));
473         }
475         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
476             list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
477         }
478     }
480     return list;
483 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
485     if (!dt)
486         return;
488     Inkscape::Selection *selection = sp_desktop_selection(dt);
490     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
492     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
493     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
494     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
495     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
497     GSList *items = NULL;
499     GSList const *exclude = NULL;
500     if (invert) {
501         exclude = selection->itemList();
502     }
504     if (force_all_layers)
505         inlayer = PREFS_SELECTION_ALL;
507     switch (inlayer) {
508         case PREFS_SELECTION_LAYER: {
509         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
510              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
511         return;
513         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
515         for (GSList *i = all_items; i; i = i->next) {
516             SPItem *item = SP_ITEM(i->data);
518             if (item && (!onlysensitive || !item->isLocked())) {
519                 if (!onlyvisible || !dt->itemIsHidden(item)) {
520                     if (!dt->isLayer(item)) {
521                         if (!invert || !g_slist_find((GSList *) exclude, item)) {
522                             items = g_slist_prepend(items, item); // leave it in the list
523                         }
524                     }
525                 }
526             }
527         }
529         g_slist_free(all_items);
530             break;
531         }
532         case PREFS_SELECTION_LAYER_RECURSIVE: {
533             items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
534             break;
535         }
536         default: {
537         items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
538             break;
539     }
540     }
542     selection->setList(items);
544     if (items) {
545         g_slist_free(items);
546     }
549 void sp_edit_select_all(SPDesktop *desktop)
551     sp_edit_select_all_full(desktop, false, false);
554 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
556     sp_edit_select_all_full(desktop, true, false);
559 void sp_edit_invert(SPDesktop *desktop)
561     sp_edit_select_all_full(desktop, false, true);
564 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
566     sp_edit_select_all_full(desktop, true, true);
569 void sp_selection_group_impl(GSList *p, Inkscape::XML::Node *group, Inkscape::XML::Document *xml_doc, SPDocument *doc) {
571     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
573     // Remember the position and parent of the topmost object.
574     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
575     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
577     while (p) {
578         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
580         if (current->parent() == topmost_parent) {
581             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
582             sp_repr_unparent(current);
583             group->appendChild(spnew);
584             Inkscape::GC::release(spnew);
585             topmost --; // only reduce count for those items deleted from topmost_parent
586         } else { // move it to topmost_parent first
587             GSList *temp_clip = NULL;
589             // At this point, current may already have no item, due to its being a clone whose original is already moved away
590             // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
591             gchar const *t_str = current->attribute("transform");
592             Geom::Matrix item_t(Geom::identity());
593             if (t_str)
594                 sp_svg_transform_read(t_str, &item_t);
595             item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
596             // FIXME: when moving both clone and original from a transformed group (either by
597             // grouping into another parent, or by cut/paste) the transform from the original's
598             // parent becomes embedded into original itself, and this affects its clones. Fix
599             // this by remembering the transform diffs we write to each item into an array and
600             // then, if this is clone, looking up its original in that array and pre-multiplying
601             // it by the inverse of that original's transform diff.
603             sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
604             sp_repr_unparent(current);
606             // paste into topmost_parent (temporarily)
607             GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
608             if (temp_clip) g_slist_free(temp_clip);
609             if (copied) { // if success,
610                 // take pasted object (now in topmost_parent)
611                 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
612                 // make a copy
613                 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
614                 // remove pasted
615                 sp_repr_unparent(in_topmost);
616                 // put its copy into group
617                 group->appendChild(spnew);
618                 Inkscape::GC::release(spnew);
619                 g_slist_free(copied);
620             }
621         }
622         p = g_slist_remove(p, current);
623     }
625     // Add the new group to the topmost members' parent
626     topmost_parent->appendChild(group);
628     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
629     group->setPosition(topmost + 1);
632 void sp_selection_group(SPDesktop *desktop)
634     if (desktop == NULL)
635         return;
637     SPDocument *doc = sp_desktop_document(desktop);
638     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
640     Inkscape::Selection *selection = sp_desktop_selection(desktop);
642     // Check if something is selected.
643     if (selection->isEmpty()) {
644         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
645         return;
646     }
648     GSList const *l = (GSList *) selection->reprList();
650     GSList *p = g_slist_copy((GSList *) l);
652     selection->clear();
654     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
656     sp_selection_group_impl(p, group, xml_doc, doc);
658     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
659                      _("Group"));
661     selection->set(group);
662     Inkscape::GC::release(group);
665 void sp_selection_ungroup(SPDesktop *desktop)
667     if (desktop == NULL)
668         return;
670     Inkscape::Selection *selection = sp_desktop_selection(desktop);
672     if (selection->isEmpty()) {
673         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
674         return;
675     }
677     GSList *items = g_slist_copy((GSList *) selection->itemList());
678     selection->clear();
680     // Get a copy of current selection.
681     GSList *new_select = NULL;
682     bool ungrouped = false;
683     for (GSList *i = items;
684          i != NULL;
685          i = i->next)
686     {
687         SPItem *group = (SPItem *) i->data;
689         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
690         if (!SP_IS_OBJECT(group)) {
691             continue;
692         }
694         /* We do not allow ungrouping <svg> etc. (lauris) */
695         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
696             // keep the non-group item in the new selection
697             new_select = g_slist_append(new_select, group);
698             continue;
699         }
701         GSList *children = NULL;
702         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
703         sp_item_group_ungroup(SP_GROUP(group), &children, false);
704         ungrouped = true;
705         // Add ungrouped items to the new selection.
706         new_select = g_slist_concat(new_select, children);
707     }
709     if (new_select) { // Set new selection.
710         selection->addList(new_select);
711         g_slist_free(new_select);
712     }
713     if (!ungrouped) {
714         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
715     }
717     g_slist_free(items);
719     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
720                      _("Ungroup"));
723 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
724 GSList *
725 sp_degroup_list(GSList *items)
727     GSList *out = NULL;
728     bool has_groups = false;
729     for (GSList *item = items; item; item = item->next) {
730         if (!SP_IS_GROUP(item->data)) {
731             out = g_slist_prepend(out, item->data);
732         } else {
733             has_groups = true;
734             GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
735             for (GSList *member = members; member; member = member->next) {
736                 out = g_slist_prepend(out, member->data);
737             }
738             g_slist_free(members);
739         }
740     }
741     out = g_slist_reverse(out);
742     g_slist_free(items);
744     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
745         out = sp_degroup_list(out);
746     }
748     return out;
752 /** If items in the list have a common parent, return it, otherwise return NULL */
753 static SPGroup *
754 sp_item_list_common_parent_group(GSList const *items)
756     if (!items) {
757         return NULL;
758     }
759     SPObject *parent = SP_OBJECT_PARENT(items->data);
760     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
761     if (!SP_IS_GROUP(parent)) {
762         return NULL;
763     }
764     for (items = items->next; items; items = items->next) {
765         if (SP_OBJECT_PARENT(items->data) != parent) {
766             return NULL;
767         }
768     }
770     return SP_GROUP(parent);
773 /** Finds out the minimum common bbox of the selected items. */
774 static Geom::OptRect
775 enclose_items(GSList const *items)
777     g_assert(items != NULL);
779     Geom::OptRect r;
780     for (GSList const *i = items; i; i = i->next) {
781         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
782     }
783     return r;
786 SPObject *
787 prev_sibling(SPObject *child)
789     SPObject *parent = SP_OBJECT_PARENT(child);
790     if (!SP_IS_GROUP(parent)) {
791         return NULL;
792     }
793     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
794         if (i->next == child)
795             return i;
796     }
797     return NULL;
800 void
801 sp_selection_raise(SPDesktop *desktop)
803     if (!desktop)
804         return;
806     Inkscape::Selection *selection = sp_desktop_selection(desktop);
808     GSList const *items = (GSList *) selection->itemList();
809     if (!items) {
810         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
811         return;
812     }
814     SPGroup const *group = sp_item_list_common_parent_group(items);
815     if (!group) {
816         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
817         return;
818     }
820     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
822     /* Construct reverse-ordered list of selected children. */
823     GSList *rev = g_slist_copy((GSList *) items);
824     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
826     // Determine the common bbox of the selected items.
827     Geom::OptRect selected = enclose_items(items);
829     // Iterate over all objects in the selection (starting from top).
830     if (selected) {
831         while (rev) {
832             SPObject *child = reinterpret_cast<SPObject*>(rev->data);
833             // for each selected object, find the next sibling
834             for (SPObject *newref = child->next; newref; newref = newref->next) {
835                 // if the sibling is an item AND overlaps our selection,
836                 if (SP_IS_ITEM(newref)) {
837                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
838                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
839                         // AND if it's not one of our selected objects,
840                         if (!g_slist_find((GSList *) items, newref)) {
841                             // move the selected object after that sibling
842                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
843                         }
844                         break;
845                     }
846                 }
847             }
848             rev = g_slist_remove(rev, child);
849         }
850     } else {
851         g_slist_free(rev);
852     }
854     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
855                      //TRANSLATORS: "Raise" means "to raise an object" in the undo history
856                      C_("Undo action", "Raise"));
859 void sp_selection_raise_to_top(SPDesktop *desktop)
861     if (desktop == NULL)
862         return;
864     SPDocument *document = sp_desktop_document(desktop);
865     Inkscape::Selection *selection = sp_desktop_selection(desktop);
867     if (selection->isEmpty()) {
868         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
869         return;
870     }
872     GSList const *items = (GSList *) selection->itemList();
874     SPGroup const *group = sp_item_list_common_parent_group(items);
875     if (!group) {
876         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
877         return;
878     }
880     GSList *rl = g_slist_copy((GSList *) selection->reprList());
881     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
883     for (GSList *l = rl; l != NULL; l = l->next) {
884         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
885         repr->setPosition(-1);
886     }
888     g_slist_free(rl);
890     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
891                      _("Raise to top"));
894 void
895 sp_selection_lower(SPDesktop *desktop)
897     if (desktop == NULL)
898         return;
900     Inkscape::Selection *selection = sp_desktop_selection(desktop);
902     GSList const *items = (GSList *) selection->itemList();
903     if (!items) {
904         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
905         return;
906     }
908     SPGroup const *group = sp_item_list_common_parent_group(items);
909     if (!group) {
910         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
911         return;
912     }
914     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
916     // Determine the common bbox of the selected items.
917     Geom::OptRect selected = enclose_items(items);
919     /* Construct direct-ordered list of selected children. */
920     GSList *rev = g_slist_copy((GSList *) items);
921     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
922     rev = g_slist_reverse(rev);
924     // Iterate over all objects in the selection (starting from top).
925     if (selected) {
926         while (rev) {
927             SPObject *child = reinterpret_cast<SPObject*>(rev->data);
928             // for each selected object, find the prev sibling
929             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
930                 // if the sibling is an item AND overlaps our selection,
931                 if (SP_IS_ITEM(newref)) {
932                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
933                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
934                         // AND if it's not one of our selected objects,
935                         if (!g_slist_find((GSList *) items, newref)) {
936                             // move the selected object before that sibling
937                             SPObject *put_after = prev_sibling(newref);
938                             if (put_after)
939                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
940                             else
941                                 SP_OBJECT_REPR(child)->setPosition(0);
942                         }
943                         break;
944                     }
945                 }
946             }
947             rev = g_slist_remove(rev, child);
948         }
949     } else {
950         g_slist_free(rev);
951     }
953     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
954                      _("Lower"));
957 void sp_selection_lower_to_bottom(SPDesktop *desktop)
959     if (desktop == NULL)
960         return;
962     SPDocument *document = sp_desktop_document(desktop);
963     Inkscape::Selection *selection = sp_desktop_selection(desktop);
965     if (selection->isEmpty()) {
966         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
967         return;
968     }
970     GSList const *items = (GSList *) selection->itemList();
972     SPGroup const *group = sp_item_list_common_parent_group(items);
973     if (!group) {
974         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
975         return;
976     }
978     GSList *rl;
979     rl = g_slist_copy((GSList *) selection->reprList());
980     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
981     rl = g_slist_reverse(rl);
983     for (GSList *l = rl; l != NULL; l = l->next) {
984         gint minpos;
985         SPObject *pp, *pc;
986         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
987         pp = document->getObjectByRepr(sp_repr_parent(repr));
988         minpos = 0;
989         g_assert(SP_IS_GROUP(pp));
990         pc = sp_object_first_child(pp);
991         while (!SP_IS_ITEM(pc)) {
992             minpos += 1;
993             pc = pc->next;
994         }
995         repr->setPosition(minpos);
996     }
998     g_slist_free(rl);
1000     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
1001                      _("Lower to bottom"));
1004 void
1005 sp_undo(SPDesktop *desktop, SPDocument *)
1007         if (!sp_document_undo(sp_desktop_document(desktop)))
1008             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
1011 void
1012 sp_redo(SPDesktop *desktop, SPDocument *)
1014         if (!sp_document_redo(sp_desktop_document(desktop)))
1015             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
1018 void sp_selection_cut(SPDesktop *desktop)
1020     sp_selection_copy(desktop);
1021     sp_selection_delete(desktop);
1024 /**
1025  * \pre item != NULL
1026  */
1027 SPCSSAttr *
1028 take_style_from_item(SPItem *item)
1030     // write the complete cascaded style, context-free
1031     SPCSSAttr *css = sp_css_attr_from_object(item, SP_STYLE_FLAG_ALWAYS);
1032     if (css == NULL)
1033         return NULL;
1035     if ((SP_IS_GROUP(item) && item->children) ||
1036         (SP_IS_TEXT(item) && item->children && item->children->next == NULL)) {
1037         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1038         // If this is a group, merge the style of its topmost (last) child with style
1039         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
1040             if ( last_element->style ) {
1041                 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1042                 if (temp) {
1043                     sp_repr_css_merge(css, temp);
1044                     sp_repr_css_attr_unref(temp);
1045                 }
1046                 break;
1047             }
1048         }
1049     }
1050     if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1051         // do not copy text properties from non-text objects, it's confusing
1052         css = sp_css_attr_unset_text(css);
1053     }
1055     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1056     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
1057     if (ex != 1.0) {
1058         css = sp_css_attr_scale(css, ex);
1059     }
1061     return css;
1065 void sp_selection_copy(SPDesktop *desktop)
1067     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1068     cm->copy(desktop);
1071 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1073     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1074     if (cm->paste(desktop, in_place)) {
1075         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1076     }
1079 void sp_selection_paste_style(SPDesktop *desktop)
1081     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1082     if (cm->pasteStyle(desktop)) {
1083         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1084     }
1088 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1090     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1091     if (cm->pastePathEffect(desktop)) {
1092         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1093                          _("Paste live path effect"));
1094     }
1098 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1100     if ( item && SP_IS_LPE_ITEM(item) &&
1101          sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1102         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1103     }
1106 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1108     if (desktop == NULL) return;
1110     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1112     // check if something is selected
1113     if (selection->isEmpty()) {
1114         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1115         return;
1116     }
1118     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1119         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1121         sp_selection_remove_livepatheffect_impl(item);
1123     }
1125     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1126                      _("Remove live path effect"));
1129 void sp_selection_remove_filter(SPDesktop *desktop)
1131     if (desktop == NULL) return;
1133     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1135     // check if something is selected
1136     if (selection->isEmpty()) {
1137         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1138         return;
1139     }
1141     SPCSSAttr *css = sp_repr_css_attr_new();
1142     sp_repr_css_unset_property(css, "filter");
1143     sp_desktop_set_style(desktop, css);
1144     sp_repr_css_attr_unref(css);
1146     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1147                      _("Remove filter"));
1151 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1153     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1154     if (cm->pasteSize(desktop, false, apply_x, apply_y)) {
1155         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1156                          _("Paste size"));
1157     }
1160 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1162     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1163     if (cm->pasteSize(desktop, true, apply_x, apply_y)) {
1164         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1165                          _("Paste size separately"));
1166     }
1169 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1171     Inkscape::Selection *selection = sp_desktop_selection(dt);
1173     // check if something is selected
1174     if (selection->isEmpty()) {
1175         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1176         return;
1177     }
1179     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1181     bool no_more = false; // Set to true, if no more layers above
1182     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1183     if (next) {
1184         GSList *temp_clip = NULL;
1185         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1186         sp_selection_delete_impl(items, false, false);
1187         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1188         GSList *copied;
1189         if (next) {
1190             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1191         } else {
1192             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1193             no_more = true;
1194         }
1195         selection->setReprList((GSList const *) copied);
1196         g_slist_free(copied);
1197         if (temp_clip) g_slist_free(temp_clip);
1198         if (next) dt->setCurrentLayer(next);
1199         if ( !suppressDone ) {
1200             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1201                              _("Raise to next layer"));
1202         }
1203     } else {
1204         no_more = true;
1205     }
1207     if (no_more) {
1208         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1209     }
1211     g_slist_free((GSList *) items);
1214 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1216     Inkscape::Selection *selection = sp_desktop_selection(dt);
1218     // check if something is selected
1219     if (selection->isEmpty()) {
1220         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1221         return;
1222     }
1224     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1226     bool no_more = false; // Set to true, if no more layers below
1227     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1228     if (next) {
1229         GSList *temp_clip = NULL;
1230         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1231         sp_selection_delete_impl(items, false, false);
1232         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1233         GSList *copied;
1234         if (next) {
1235             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1236         } else {
1237             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1238             no_more = true;
1239         }
1240         selection->setReprList((GSList const *) copied);
1241         g_slist_free(copied);
1242         if (temp_clip) g_slist_free(temp_clip);
1243         if (next) dt->setCurrentLayer(next);
1244         if ( !suppressDone ) {
1245             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1246                              _("Lower to previous layer"));
1247         }
1248     } else {
1249         no_more = true;
1250     }
1252     if (no_more) {
1253         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1254     }
1256     g_slist_free((GSList *) items);
1259 bool
1260 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1262     bool contains_original = false;
1264     bool is_use = SP_IS_USE(item);
1265     SPItem *item_use = item;
1266     SPItem *item_use_first = item;
1267     while (is_use && item_use && !contains_original)
1268     {
1269         item_use = sp_use_get_original(SP_USE(item_use));
1270         contains_original |= selection->includes(item_use);
1271         if (item_use == item_use_first)
1272             break;
1273         is_use = SP_IS_USE(item_use);
1274     }
1276     // If it's a tref, check whether the object containing the character
1277     // data is part of the selection
1278     if (!contains_original && SP_IS_TREF(item)) {
1279         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1280     }
1282     return contains_original;
1286 bool
1287 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1289     bool clone_with_original = false;
1290     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1291         SPItem *item = SP_ITEM(l->data);
1292         clone_with_original |= selection_contains_original(item, selection);
1293         if (clone_with_original)
1294             break;
1295     }
1296     return clone_with_original;
1299 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1300 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1301 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1302 that case, items are already in the new position, but the repr is in the old, and this function
1303 then simply updates the repr from item->transform.
1304  */
1305 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1307     if (selection->isEmpty())
1308         return;
1310     // For each perspective with a box in selection, check whether all boxes are selected and
1311     // unlink all non-selected boxes.
1312     Persp3D *persp;
1313     Persp3D *transf_persp;
1314     std::list<Persp3D *> plist = selection->perspList();
1315     for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1316         persp = (Persp3D *) (*i);
1318         if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1319             std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1321             // create a new perspective as a copy of the current one and link the selected boxes to it
1322             transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1324             for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1325                 box3d_switch_perspectives(*b, persp, transf_persp);
1326         } else {
1327             transf_persp = persp;
1328         }
1330         persp3d_apply_affine_transformation(transf_persp, affine);
1331     }
1333     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1334         SPItem *item = SP_ITEM(l->data);
1336         Geom::Point old_center(0,0);
1337         if (set_i2d && item->isCenterSet())
1338             old_center = item->getCenter();
1340 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1341          At the time of writing, this is the only place to re-enable. */
1342         sp_item_update_cns(*item, selection->desktop());
1343 #endif
1345         // we're moving both a clone and its original or any ancestor in clone chain?
1346         bool transform_clone_with_original = selection_contains_original(item, selection);
1347         // ...both a text-on-path and its path?
1348         bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(item))) ));
1349         // ...both a flowtext and its frame?
1350         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)
1351         // ...both an offset and its source?
1352         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1354         // If we're moving a connector, we want to detach it
1355         // from shapes that aren't part of the selection, but
1356         // leave it attached if they are
1357         if (cc_item_is_connector(item)) {
1358             SPItem *attItem[2];
1359             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1361             for (int n = 0; n < 2; ++n) {
1362                 if (!selection->includes(attItem[n])) {
1363                     sp_conn_end_detach(item, n);
1364                 }
1365             }
1366         }
1368         // "clones are unmoved when original is moved" preference
1369         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1370         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1371         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1372         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1374         /* If this is a clone and it's selected along with its original, do not move it;
1375          * it will feel the transform of its original and respond to it itself.
1376          * Without this, a clone is doubly transformed, very unintuitive.
1377          *
1378          * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1379          * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1380          * Same for linked offset if we are also moving its source: do not move it. */
1381         if (transform_textpath_with_path || transform_offset_with_source) {
1382             // Restore item->transform field from the repr, in case it was changed by seltrans.
1383             sp_object_read_attr(item, "transform");
1384         } else if (transform_flowtext_with_frame) {
1385             // apply the inverse of the region's transform to the <use> so that the flow remains
1386             // the same (even though the output itself gets transformed)
1387             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1388                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1389                     continue;
1390                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1391                     if (!SP_IS_USE(use)) continue;
1392                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1393                 }
1394             }
1395         } else if (transform_clone_with_original) {
1396             // We are transforming a clone along with its original. The below matrix juggling is
1397             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1398             // transform and its move compensation are both cancelled out.
1400             // restore item->transform field from the repr, in case it was changed by seltrans
1401             sp_object_read_attr(item, "transform");
1403             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1404             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1405             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1406             Geom::Matrix t_inv = t.inverse();
1407             Geom::Matrix result = t_inv * item->transform * t;
1409             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1410                 // we need to cancel out the move compensation, too
1412                 // find out the clone move, same as in sp_use_move_compensate
1413                 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1414                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1416                 if (prefs_parallel) {
1417                     Geom::Matrix move = result * clone_move * t_inv;
1418                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1420                 } else if (prefs_unmoved) {
1421                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1422                     //    clone_move = Geom::identity();
1423                     Geom::Matrix move = result * clone_move;
1424                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1425                 }
1427             } else {
1428                 // just apply the result
1429                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1430             }
1432         } else {
1433             if (set_i2d) {
1434                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1435             }
1436             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1437         }
1439         // if we're moving the actual object, not just updating the repr, we can transform the
1440         // center by the same matrix (only necessary for non-translations)
1441         if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1442             item->setCenter(old_center * affine);
1443             item->updateRepr();
1444         }
1445     }
1448 void sp_selection_remove_transform(SPDesktop *desktop)
1450     if (desktop == NULL)
1451         return;
1453     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1455     GSList const *l = (GSList *) selection->reprList();
1456     while (l != NULL) {
1457         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1458         l = l->next;
1459     }
1461     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1462                      _("Remove transform"));
1465 void
1466 sp_selection_scale_absolute(Inkscape::Selection *selection,
1467                             double const x0, double const x1,
1468                             double const y0, double const y1)
1470     if (selection->isEmpty())
1471         return;
1473     Geom::OptRect const bbox(selection->bounds());
1474     if ( !bbox ) {
1475         return;
1476     }
1478     Geom::Translate const p2o(-bbox->min());
1480     Geom::Scale const newSize(x1 - x0,
1481                               y1 - y0);
1482     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1483     Geom::Translate const o2n(x0, y0);
1484     Geom::Matrix const final( p2o * scale * o2n );
1486     sp_selection_apply_affine(selection, final);
1490 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1492     if (selection->isEmpty())
1493         return;
1495     Geom::OptRect const bbox(selection->bounds());
1497     if ( !bbox ) {
1498         return;
1499     }
1501     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1502     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1503          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1504     {
1505         return;
1506     }
1508     Geom::Translate const n2d(-align);
1509     Geom::Translate const d2n(align);
1510     Geom::Matrix const final( n2d * scale * d2n );
1511     sp_selection_apply_affine(selection, final);
1514 void
1515 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1517     Geom::Translate const d2n(center);
1518     Geom::Translate const n2d(-center);
1519     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1520     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1521     sp_selection_apply_affine(selection, final);
1524 void
1525 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1527     Geom::Translate const d2n(align);
1528     Geom::Translate const n2d(-align);
1529     Geom::Matrix const skew(1, dy,
1530                             dx, 1,
1531                             0, 0);
1532     Geom::Matrix const final( n2d * skew * d2n );
1533     sp_selection_apply_affine(selection, final);
1536 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1538     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1541 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1543     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1546 /**
1547  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1548  */
1549 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1551     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1553     if (selection->isEmpty())
1554         return;
1556     GSList const *l = selection->itemList();
1557     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1558     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1559         SPItem *item = SP_ITEM(l2->data);
1560         sp_item_rotate_rel(item, rot_90);
1561     }
1563     sp_document_done(sp_desktop_document(desktop),
1564                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1565                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1568 void
1569 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1571     if (selection->isEmpty())
1572         return;
1574     boost::optional<Geom::Point> center = selection->center();
1575     if (!center) {
1576         return;
1577     }
1579     sp_selection_rotate_relative(selection, *center, angle_degrees);
1581     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1582                            ( ( angle_degrees > 0 )
1583                              ? "selector:rotate:ccw"
1584                              : "selector:rotate:cw" ),
1585                            SP_VERB_CONTEXT_SELECT,
1586                            _("Rotate"));
1589 // helper function:
1590 static
1591 Geom::Point
1592 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1593     Geom::Point m = r.midpoint();
1594     unsigned i = 0;
1595     if (p[X] < m[X]) {
1596         i = 1;
1597     }
1598     if (p[Y] < m[Y]) {
1599         i = 3 - i;
1600     }
1601     return r.corner(i);
1604 /**
1605 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1606 */
1607 void
1608 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1610     if (selection->isEmpty())
1611         return;
1613     Geom::OptRect const bbox(selection->bounds());
1614     boost::optional<Geom::Point> center = selection->center();
1616     if ( !bbox || !center ) {
1617         return;
1618     }
1620     gdouble const zoom = selection->desktop()->current_zoom();
1621     gdouble const zmove = angle / zoom;
1622     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1624     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1626     sp_selection_rotate_relative(selection, *center, zangle);
1628     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1629                            ( (angle > 0)
1630                              ? "selector:rotate:ccw"
1631                              : "selector:rotate:cw" ),
1632                            SP_VERB_CONTEXT_SELECT,
1633                            _("Rotate by pixels"));
1636 void
1637 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1639     if (selection->isEmpty())
1640         return;
1642     Geom::OptRect const bbox(selection->bounds());
1643     if (!bbox) {
1644         return;
1645     }
1647     Geom::Point const center(bbox->midpoint());
1649     // you can't scale "do nizhe pola" (below zero)
1650     double const max_len = bbox->maxExtent();
1651     if ( max_len + grow <= 1e-3 ) {
1652         return;
1653     }
1655     double const times = 1.0 + grow / max_len;
1656     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1658     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1659                            ( (grow > 0)
1660                              ? "selector:scale:larger"
1661                              : "selector:scale:smaller" ),
1662                            SP_VERB_CONTEXT_SELECT,
1663                            _("Scale"));
1666 void
1667 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1669     sp_selection_scale(selection,
1670                        grow_pixels / selection->desktop()->current_zoom());
1673 void
1674 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1676     if (selection->isEmpty())
1677         return;
1679     Geom::OptRect sel_bbox = selection->bounds();
1681     if (!sel_bbox) {
1682         return;
1683     }
1685     Geom::Point const center(sel_bbox->midpoint());
1686     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1687     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1688                      _("Scale by whole factor"));
1691 void
1692 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1694     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1695     if (selection->isEmpty()) {
1696         return;
1697     }
1699     sp_selection_move_relative(selection, dx, dy);
1701     if (dx == 0) {
1702         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1703                                _("Move vertically"));
1704     } else if (dy == 0) {
1705         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1706                                _("Move horizontally"));
1707     } else {
1708         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1709                          _("Move"));
1710     }
1713 void
1714 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1716     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1717     if (selection->isEmpty()) {
1718         return;
1719     }
1721     // same as sp_selection_move but divide deltas by zoom factor
1722     gdouble const zoom = desktop->current_zoom();
1723     gdouble const zdx = dx / zoom;
1724     gdouble const zdy = dy / zoom;
1725     sp_selection_move_relative(selection, zdx, zdy);
1727     if (dx == 0) {
1728         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1729                                _("Move vertically by pixels"));
1730     } else if (dy == 0) {
1731         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1732                                _("Move horizontally by pixels"));
1733     } else {
1734         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1735                          _("Move"));
1736     }
1739 namespace {
1741 template <typename D>
1742 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1743                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1745 template <typename D>
1746 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1747                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1749 struct Forward {
1750     typedef SPObject *Iterator;
1752     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1753     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1754     static void dispose(Iterator /*i*/) {}
1756     static SPObject *object(Iterator i) { return i; }
1757     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1758 };
1760 struct Reverse {
1761     typedef GSList *Iterator;
1763     static Iterator children(SPObject *o) {
1764         return make_list(o->firstChild(), NULL);
1765     }
1766     static Iterator siblings_after(SPObject *o) {
1767         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1768     }
1769     static void dispose(Iterator i) {
1770         g_slist_free(i);
1771     }
1773     static SPObject *object(Iterator i) {
1774         return reinterpret_cast<SPObject *>(i->data);
1775     }
1776     static Iterator next(Iterator i) { return i->next; }
1778 private:
1779     static GSList *make_list(SPObject *object, SPObject *limit) {
1780         GSList *list=NULL;
1781         while ( object != limit ) {
1782             list = g_slist_prepend(list, object);
1783             object = SP_OBJECT_NEXT(object);
1784         }
1785         return list;
1786     }
1787 };
1791 void
1792 sp_selection_item_next(SPDesktop *desktop)
1794     g_return_if_fail(desktop != NULL);
1795     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1797     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1798     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1799     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1800     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1802     SPObject *root;
1803     if (PREFS_SELECTION_ALL != inlayer) {
1804         root = selection->activeContext();
1805     } else {
1806         root = desktop->currentRoot();
1807     }
1809     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1811     if (item) {
1812         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1813         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1814             scroll_to_show_item(desktop, item);
1815         }
1816     }
1819 void
1820 sp_selection_item_prev(SPDesktop *desktop)
1822     SPDocument *document = sp_desktop_document(desktop);
1823     g_return_if_fail(document != NULL);
1824     g_return_if_fail(desktop != NULL);
1825     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1827     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1828     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1829     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1830     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1832     SPObject *root;
1833     if (PREFS_SELECTION_ALL != inlayer) {
1834         root = selection->activeContext();
1835     } else {
1836         root = desktop->currentRoot();
1837     }
1839     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1841     if (item) {
1842         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1843         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1844             scroll_to_show_item(desktop, item);
1845         }
1846     }
1849 void sp_selection_next_patheffect_param(SPDesktop * dt)
1851     if (!dt) return;
1853     Inkscape::Selection *selection = sp_desktop_selection(dt);
1854     if ( selection && !selection->isEmpty() ) {
1855         SPItem *item = selection->singleItem();
1856         if ( item && SP_IS_SHAPE(item)) {
1857             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1858                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1859             } else {
1860                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1861             }
1862         }
1863     }
1866 /*bool has_path_recursive(SPObject *obj)
1868     if (!obj) return false;
1869     if (SP_IS_PATH(obj)) {
1870         return true;
1871     }
1872     if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1873         for (SPObject *c = obj->children; c; c = c->next) {
1874             if (has_path_recursive(c)) return true;
1875         }
1876     }
1877     return false;
1878 }*/
1880 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1882     return;
1883     /*if (!dt) return;
1884     using namespace Inkscape::UI;
1886     Inkscape::Selection *selection = sp_desktop_selection(dt);
1887     if (!selection || selection->isEmpty()) return;
1889     GSList const *items = selection->itemList();
1890     bool has_path = false;
1891     for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1892         SPItem *item = SP_ITEM(i->data);
1893         SPObject *search = clip
1894             ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1895             : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1896         has_path |= has_path_recursive(search);
1897         if (has_path) break;
1898     }
1899     if (has_path) {
1900         if (!tools_isactive(dt, TOOLS_NODES)) {
1901             tools_switch(dt, TOOLS_NODES);
1902         }
1903         ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1904             clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1905     } else if (clip) {
1906         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1907             _("The selection has no applied clip path."));
1908     } else {
1909         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1910             _("The selection has no applied mask."));
1911     }*/
1915 namespace {
1917 template <typename D>
1918 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1919                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1921     SPObject *current=root;
1922     while (items) {
1923         SPItem *item=SP_ITEM(items->data);
1924         if ( root->isAncestorOf(item) &&
1925              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1926         {
1927             current = item;
1928             break;
1929         }
1930         items = items->next;
1931     }
1933     GSList *path=NULL;
1934     while ( current != root ) {
1935         path = g_slist_prepend(path, current);
1936         current = SP_OBJECT_PARENT(current);
1937     }
1939     SPItem *next;
1940     // first, try from the current object
1941     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1942     g_slist_free(path);
1944     if (!next) { // if we ran out of objects, start over at the root
1945         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1946     }
1948     return next;
1951 template <typename D>
1952 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1953                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1955     typename D::Iterator children;
1956     typename D::Iterator iter;
1958     SPItem *found=NULL;
1960     if (path) {
1961         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1962         g_assert(SP_OBJECT_PARENT(object) == root);
1963         if (desktop->isLayer(object)) {
1964             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1965         }
1966         iter = children = D::siblings_after(object);
1967     } else {
1968         iter = children = D::children(root);
1969     }
1971     while ( iter && !found ) {
1972         SPObject *object=D::object(iter);
1973         if (desktop->isLayer(object)) {
1974             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1975                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1976             }
1977         } else if ( SP_IS_ITEM(object) &&
1978                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1979                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1980                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1981                     !desktop->isLayer(SP_ITEM(object)) )
1982         {
1983             found = SP_ITEM(object);
1984         }
1985         iter = D::next(iter);
1986     }
1988     D::dispose(children);
1990     return found;
1995 /**
1996  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1997  * \a item.
1998  */
1999 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2001     Geom::Rect dbox = desktop->get_display_area();
2002     Geom::OptRect sbox = sp_item_bbox_desktop(item);
2004     if ( sbox && dbox.contains(*sbox) == false ) {
2005         Geom::Point const s_dt = sbox->midpoint();
2006         Geom::Point const s_w = desktop->d2w(s_dt);
2007         Geom::Point const d_dt = dbox.midpoint();
2008         Geom::Point const d_w = desktop->d2w(d_dt);
2009         Geom::Point const moved_w( d_w - s_w );
2010         gint const dx = (gint) moved_w[X];
2011         gint const dy = (gint) moved_w[Y];
2012         desktop->scroll_world(dx, dy);
2013     }
2017 void
2018 sp_selection_clone(SPDesktop *desktop)
2020     if (desktop == NULL)
2021         return;
2023     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2025     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2027     // check if something is selected
2028     if (selection->isEmpty()) {
2029         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2030         return;
2031     }
2033     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2035     selection->clear();
2037     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2038     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2040     GSList *newsel = NULL;
2042     while (reprs) {
2043         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2044         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2046         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2047         clone->setAttribute("x", "0", false);
2048         clone->setAttribute("y", "0", false);
2049         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2051         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2052         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2054         // add the new clone to the top of the original's parent
2055         parent->appendChild(clone);
2057         newsel = g_slist_prepend(newsel, clone);
2058         reprs = g_slist_remove(reprs, sel_repr);
2059         Inkscape::GC::release(clone);
2060     }
2062     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2063                      C_("Action","Clone"));
2065     selection->setReprList(newsel);
2067     g_slist_free(newsel);
2070 void
2071 sp_selection_relink(SPDesktop *desktop)
2073     if (!desktop)
2074         return;
2076     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2078     if (selection->isEmpty()) {
2079         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2080         return;
2081     }
2083     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2084     const gchar *newid = cm->getFirstObjectID();
2085     if (!newid) {
2086         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2087         return;
2088     }
2089     gchar *newref = g_strdup_printf("#%s", newid);
2091     // Get a copy of current selection.
2092     bool relinked = false;
2093     for (GSList *items = (GSList *) selection->itemList();
2094          items != NULL;
2095          items = items->next)
2096     {
2097         SPItem *item = (SPItem *) items->data;
2099         if (!SP_IS_USE(item))
2100             continue;
2102         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2103         item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2104         relinked = true;
2105     }
2107     g_free(newref);
2109     if (!relinked) {
2110         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2111     } else {
2112         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2113                          _("Relink clone"));
2114     }
2118 void
2119 sp_selection_unlink(SPDesktop *desktop)
2121     if (!desktop)
2122         return;
2124     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2126     if (selection->isEmpty()) {
2127         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2128         return;
2129     }
2131     // Get a copy of current selection.
2132     GSList *new_select = NULL;
2133     bool unlinked = false;
2134     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2135          items != NULL;
2136          items = items->next)
2137     {
2138         SPItem *item = (SPItem *) items->data;
2140         if (SP_IS_TEXT(item)) {
2141             SPObject *tspan = sp_tref_convert_to_tspan(item);
2143             if (tspan) {
2144                 item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2145             }
2147             // Set unlink to true, and fall into the next if which
2148             // will include this text item in the new selection
2149             unlinked = true;
2150         }
2152         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2153             // keep the non-use item in the new selection
2154             new_select = g_slist_prepend(new_select, item);
2155             continue;
2156         }
2158         SPItem *unlink;
2159         if (SP_IS_USE(item)) {
2160             unlink = sp_use_unlink(SP_USE(item));
2161             // Unable to unlink use (external or invalid href?)
2162             if (!unlink) {
2163                 new_select = g_slist_prepend(new_select, item);
2164                 continue;
2165             }
2166         } else /*if (SP_IS_TREF(use))*/ {
2167             unlink = SP_ITEM(sp_tref_convert_to_tspan(item));
2168         }
2170         unlinked = true;
2171         // Add ungrouped items to the new selection.
2172         new_select = g_slist_prepend(new_select, unlink);
2173     }
2175     if (new_select) { // set new selection
2176         selection->clear();
2177         selection->setList(new_select);
2178         g_slist_free(new_select);
2179     }
2180     if (!unlinked) {
2181         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2182     }
2184     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2185                      _("Unlink clone"));
2188 void
2189 sp_select_clone_original(SPDesktop *desktop)
2191     if (desktop == NULL)
2192         return;
2194     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2196     SPItem *item = selection->singleItem();
2198     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.");
2200     // Check if other than two objects are selected
2201     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2202         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2203         return;
2204     }
2206     SPItem *original = NULL;
2207     if (SP_IS_USE(item)) {
2208         original = sp_use_get_original(SP_USE(item));
2209     } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2210         original = sp_offset_get_source(SP_OFFSET(item));
2211     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2212         original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(item)));
2213     } else if (SP_IS_FLOWTEXT(item)) {
2214         original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2215     } else { // it's an object that we don't know what to do with
2216         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2217         return;
2218     }
2220     if (!original) {
2221         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2222         return;
2223     }
2225     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2226         if (SP_IS_DEFS(o)) {
2227             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2228             return;
2229         }
2230     }
2232     if (original) {
2233         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2234         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2235         if (highlight) {
2236             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2237             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2238             if ( a && b ) {
2239                 // draw a flashing line between the objects
2240                 SPCurve *curve = new SPCurve();
2241                 curve->moveto(a->midpoint());
2242                 curve->lineto(b->midpoint());
2244                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2245                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2246                 sp_canvas_item_show(canvasitem);
2247                 curve->unref();
2248                 desktop->add_temporary_canvasitem(canvasitem, 1000);
2249             }
2250         }
2252         selection->clear();
2253         selection->set(original);
2254         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2255             scroll_to_show_item(desktop, original);
2256         }
2257     }
2261 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2263     if (desktop == NULL)
2264         return;
2266     SPDocument *doc = sp_desktop_document(desktop);
2267     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2269     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2271     // check if something is selected
2272     if (selection->isEmpty()) {
2273         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2274         return;
2275     }
2277     sp_document_ensure_up_to_date(doc);
2278     Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2279     boost::optional<Geom::Point> c = selection->center();
2280     if ( !r || !c ) {
2281         return;
2282     }
2284     // calculate the transform to be applied to objects to move them to 0,0
2285     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2286     move_p[Geom::Y] = -move_p[Geom::Y];
2287     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2289     GSList *items = g_slist_copy((GSList *) selection->itemList());
2291     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2293     // bottommost object, after sorting
2294     SPObject *parent = SP_OBJECT_PARENT(items->data);
2296     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2298     // remember the position of the first item
2299     gint pos = SP_OBJECT_REPR(items->data)->position();
2300     (void)pos; // TODO check why this was remembered
2302     // create a list of duplicates
2303     GSList *repr_copies = NULL;
2304     for (GSList *i = items; i != NULL; i = i->next) {
2305         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2306         repr_copies = g_slist_prepend(repr_copies, dup);
2307     }
2309     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2311     if (apply) {
2312         // delete objects so that their clones don't get alerted; this object will be restored shortly
2313         for (GSList *i = items; i != NULL; i = i->next) {
2314             SPObject *item = reinterpret_cast<SPObject*>(i->data);
2315             item->deleteObject(false);
2316         }
2317     }
2319     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2320     // without disturbing clones.
2321     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2322     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2323     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2324     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2326     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2327                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2328                                                                               Geom::Point(r->min()[Geom::X],
2329                                                                                           r->max()[Geom::Y]))))
2330                                              * parent_transform.inverse() ),
2331                                            parent_transform * move);
2332     (void)mark_id;
2334     // restore compensation setting
2335     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2338     g_slist_free(items);
2340     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2341                      _("Objects to marker"));
2344 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2345     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2346         for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2347             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2348         }
2349     } else {
2350         sp_item_convert_item_to_guides(item);
2352         if (deleteitem) {
2353             item->deleteObject(true);
2354         }
2355     }
2358 void sp_selection_to_guides(SPDesktop *desktop)
2360     if (desktop == NULL)
2361         return;
2363     SPDocument *doc = sp_desktop_document(desktop);
2364     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2365     // we need to copy the list because it gets reset when objects are deleted
2366     GSList *items = g_slist_copy((GSList *) selection->itemList());
2368     if (!items) {
2369         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2370         return;
2371     }
2373     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2374     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2375     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2377     for (GSList const *i = items; i != NULL; i = i->next) {
2378         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2379     }
2381     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2384 void
2385 sp_selection_tile(SPDesktop *desktop, bool apply)
2387     if (desktop == NULL)
2388         return;
2390     SPDocument *doc = sp_desktop_document(desktop);
2391     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2393     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2395     // check if something is selected
2396     if (selection->isEmpty()) {
2397         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2398         return;
2399     }
2401     sp_document_ensure_up_to_date(doc);
2402     Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2403     if ( !r ) {
2404         return;
2405     }
2407     // calculate the transform to be applied to objects to move them to 0,0
2408     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2409     move_p[Geom::Y] = -move_p[Geom::Y];
2410     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2412     GSList *items = g_slist_copy((GSList *) selection->itemList());
2414     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2416     // bottommost object, after sorting
2417     SPObject *parent = SP_OBJECT_PARENT(items->data);
2419     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2421     // remember the position of the first item
2422     gint pos = SP_OBJECT_REPR(items->data)->position();
2424     // create a list of duplicates
2425     GSList *repr_copies = NULL;
2426     for (GSList *i = items; i != NULL; i = i->next) {
2427         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2428         repr_copies = g_slist_prepend(repr_copies, dup);
2429     }
2430     // restore the z-order after prepends
2431     repr_copies = g_slist_reverse(repr_copies);
2433     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2435     if (apply) {
2436         // delete objects so that their clones don't get alerted; this object will be restored shortly
2437         for (GSList *i = items; i != NULL; i = i->next) {
2438             SPObject *item = reinterpret_cast<SPObject*>(i->data);
2439             item->deleteObject(false);
2440         }
2441     }
2443     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2444     // without disturbing clones.
2445     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2446     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2447     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2448     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2450     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2451                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2452                                                                                             r->max()[Geom::Y]))))
2453                                          * to_2geom(parent_transform.inverse()) ),
2454                                        parent_transform * move);
2456     // restore compensation setting
2457     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2459     if (apply) {
2460         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2461         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2463         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2464         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2466         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2467         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2468         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2469         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2471         // restore parent and position
2472         SP_OBJECT_REPR(parent)->appendChild(rect);
2473         rect->setPosition(pos > 0 ? pos : 0);
2474         SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2476         Inkscape::GC::release(rect);
2478         selection->clear();
2479         selection->set(rectangle);
2480     }
2482     g_slist_free(items);
2484     sp_document_done(doc, SP_VERB_EDIT_TILE,
2485                      _("Objects to pattern"));
2488 void
2489 sp_selection_untile(SPDesktop *desktop)
2491     if (desktop == NULL)
2492         return;
2494     SPDocument *doc = sp_desktop_document(desktop);
2495     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2497     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2499     // check if something is selected
2500     if (selection->isEmpty()) {
2501         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2502         return;
2503     }
2505     GSList *new_select = NULL;
2507     bool did = false;
2509     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2510          items != NULL;
2511          items = items->next) {
2513         SPItem *item = (SPItem *) items->data;
2515         SPStyle *style = item->style;
2517         if (!style || !style->fill.isPaintserver())
2518             continue;
2520         SPPaintServer *server = item->style->getFillPaintServer();
2522         if (!SP_IS_PATTERN(server))
2523             continue;
2525         did = true;
2527         SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2529         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2530         pat_transform *= item->transform;
2532         for (SPObject *child = sp_object_first_child(pattern) ; child != NULL; child = child->next ) {
2533             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2534             SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2536            // FIXME: relink clones to the new canvas objects
2537            // use SPObject::setid when mental finishes it to steal ids of
2539             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2540             sp_document_ensure_up_to_date(doc);
2542             Geom::Matrix transform( i->transform * pat_transform );
2543             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2545             new_select = g_slist_prepend(new_select, i);
2546         }
2548         SPCSSAttr *css = sp_repr_css_attr_new();
2549         sp_repr_css_set_property(css, "fill", "none");
2550         sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2551     }
2553     if (!did) {
2554         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2555     } else {
2556         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2557                          _("Pattern to objects"));
2558         selection->setList(new_select);
2559     }
2562 void
2563 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2565     if (selection->isEmpty()) {
2566         return;
2567     }
2569     GSList const *reprlst = selection->reprList();
2570     bool filename_search = TRUE;
2571     bool xdpi_search = TRUE;
2572     bool ydpi_search = TRUE;
2574     for (; reprlst != NULL &&
2575             filename_search &&
2576             xdpi_search &&
2577             ydpi_search;
2578         reprlst = reprlst->next) {
2579         gchar const *dpi_string;
2580         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2582         if (filename_search) {
2583             *filename = repr->attribute("inkscape:export-filename");
2584             if (*filename != NULL)
2585                 filename_search = FALSE;
2586         }
2588         if (xdpi_search) {
2589             dpi_string = NULL;
2590             dpi_string = repr->attribute("inkscape:export-xdpi");
2591             if (dpi_string != NULL) {
2592                 *xdpi = atof(dpi_string);
2593                 xdpi_search = FALSE;
2594             }
2595         }
2597         if (ydpi_search) {
2598             dpi_string = NULL;
2599             dpi_string = repr->attribute("inkscape:export-ydpi");
2600             if (dpi_string != NULL) {
2601                 *ydpi = atof(dpi_string);
2602                 ydpi_search = FALSE;
2603             }
2604         }
2605     }
2608 void
2609 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2611     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2612     gchar const *dpi_string;
2614     *filename = repr->attribute("inkscape:export-filename");
2616     dpi_string = NULL;
2617     dpi_string = repr->attribute("inkscape:export-xdpi");
2618     if (dpi_string != NULL) {
2619         *xdpi = atof(dpi_string);
2620     }
2622     dpi_string = NULL;
2623     dpi_string = repr->attribute("inkscape:export-ydpi");
2624     if (dpi_string != NULL) {
2625         *ydpi = atof(dpi_string);
2626     }
2629 void
2630 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2632     if (desktop == NULL)
2633         return;
2635     SPDocument *document = sp_desktop_document(desktop);
2636     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2638     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2640     // check if something is selected
2641     if (selection->isEmpty()) {
2642         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2643         return;
2644     }
2646     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2647     // set "busy" cursor
2648     desktop->setWaitingCursor();
2650     // Get the bounding box of the selection
2651     NRRect bbox;
2652     sp_document_ensure_up_to_date(document);
2653     selection->bounds(&bbox);
2654     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2655         desktop->clearWaitingCursor();
2656         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2657     }
2659     // List of the items to show; all others will be hidden
2660     GSList *items = g_slist_copy((GSList *) selection->itemList());
2662     // Sort items so that the topmost comes last
2663     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2665     // Generate a random value from the current time (you may create bitmap from the same object(s)
2666     // multiple times, and this is done so that they don't clash)
2667     GTimeVal cu;
2668     g_get_current_time(&cu);
2669     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2671     // Create the filename.
2672     gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2673                                             document->name,
2674                                             SP_OBJECT_REPR(items->data)->attribute("id"),
2675                                             current);
2676     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2677     // digits, and a few other chars, with "_"
2678     g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2680     // Build the complete path by adding document base dir, if set, otherwise home dir
2681     gchar * directory = NULL;
2682     if (SP_DOCUMENT_URI(document)) {
2683         directory = g_dirname(SP_DOCUMENT_URI(document));
2684     }
2685     if (directory == NULL) {
2686         directory = homedir_path(NULL);
2687     }
2688     gchar *filepath = g_build_filename(directory, basename, NULL);
2690     //g_print("%s\n", filepath);
2692     // Remember parent and z-order of the topmost one
2693     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2694     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2695     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2697     // Calculate resolution
2698     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2699     double res;
2700     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2701     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2702     if (0 < prefs_res) {
2703         // If it's given explicitly in prefs, take it
2704         res = prefs_res;
2705     } else if (0 < prefs_min) {
2706         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2707         res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2708     } else {
2709         float hint_xdpi = 0, hint_ydpi = 0;
2710         char const *hint_filename;
2711         // take resolution hint from the selected objects
2712         sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2713         if (hint_xdpi != 0) {
2714             res = hint_xdpi;
2715         } else {
2716             // take resolution hint from the document
2717             sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2718             if (hint_xdpi != 0) {
2719                 res = hint_xdpi;
2720             } else {
2721                 // if all else fails, take the default 90 dpi
2722                 res = PX_PER_IN;
2723             }
2724         }
2725     }
2727     // The width and height of the bitmap in pixels
2728     unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2729     unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2731     // Find out if we have to run an external filter
2732     gchar const *run = NULL;
2733     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2734     if (!filter.empty()) {
2735         // filter command is given;
2736         // see if we have a parameter to pass to it
2737         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2738         if (!param1.empty()) {
2739             if (param1[param1.length() - 1] == '%') {
2740                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2741                 gchar p1[256];
2742                 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2743                 // the first param is always the image filename, the second is param1
2744                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2745             } else {
2746                 // otherwise pass the param1 unchanged
2747                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2748             }
2749         } else {
2750             // run without extra parameter
2751             run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2752         }
2753     }
2755     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2756     Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2757     Geom::Matrix t;
2759     double shift_x = bbox.x0;
2760     double shift_y = bbox.y1;
2761     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2762         shift_x = round(shift_x);
2763         shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2764     }
2765     t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2767     // Do the export
2768     sp_export_png_file(document, filepath,
2769                        bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2770                        width, height, res, res,
2771                        (guint32) 0xffffff00,
2772                        NULL, NULL,
2773                        true,  /*bool force_overwrite,*/
2774                        items);
2776     g_slist_free(items);
2778     // Run filter, if any
2779     if (run) {
2780         g_print("Running external filter: %s\n", run);
2781         int retval;
2782         retval = system(run);
2783     }
2785     // Import the image back
2786     GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2787     if (pb) {
2788         // Create the repr for the image
2789         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2790         sp_embed_image(repr, pb, "image/png");
2791         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2792             sp_repr_set_svg_double(repr, "width", width);
2793             sp_repr_set_svg_double(repr, "height", height);
2794         } else {
2795             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2796             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2797         }
2799         // Write transform
2800         gchar *c=sp_svg_transform_write(t);
2801         repr->setAttribute("transform", c);
2802         g_free(c);
2804         // add the new repr to the parent
2805         parent->appendChild(repr);
2807         // move to the saved position
2808         repr->setPosition(pos > 0 ? pos + 1 : 1);
2810         // Set selection to the new image
2811         selection->clear();
2812         selection->add(repr);
2814         // Clean up
2815         Inkscape::GC::release(repr);
2816         gdk_pixbuf_unref(pb);
2818         // Complete undoable transaction
2819         sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2820                          _("Create bitmap"));
2821     }
2823     desktop->clearWaitingCursor();
2825     g_free(basename);
2826     g_free(filepath);
2829 /**
2830  * \brief Creates a mask or clipPath from selection
2831  * Two different modes:
2832  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2833  *       and is applied to current layer
2834  *  otherwise, topmost object is used as mask for other objects
2835  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2836  *
2837  */
2838 void
2839 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2841     if (desktop == NULL)
2842         return;
2844     SPDocument *doc = sp_desktop_document(desktop);
2845     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2847     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2849     // check if something is selected
2850     bool is_empty = selection->isEmpty();
2851     if ( apply_to_layer && is_empty) {
2852         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2853         return;
2854     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2855         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2856         return;
2857     }
2859     // FIXME: temporary patch to prevent crash!
2860     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2861     bool clone_with_original = selection_contains_both_clone_and_original(selection);
2862     if (clone_with_original) {
2863         return; // in this version, you cannot clip/mask an object with its own clone
2864     }
2865     // /END FIXME
2867     sp_document_ensure_up_to_date(doc);
2869     GSList *items = g_slist_copy((GSList *) selection->itemList());
2871     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2873     // See lp bug #542004
2874     selection->clear();
2876     // create a list of duplicates
2877     GSList *mask_items = NULL;
2878     GSList *apply_to_items = NULL;
2879     GSList *items_to_delete = NULL;
2880     GSList *items_to_select = NULL;
2882     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2883     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2884     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2885     int grouping = prefs->getInt("/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE);
2887     if (apply_to_layer) {
2888         // all selected items are used for mask, which is applied to a layer
2889         apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2891         for (GSList *i = items; i != NULL; i = i->next) {
2892             Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2893             mask_items = g_slist_prepend(mask_items, dup);
2895             SPObject *item = reinterpret_cast<SPObject*>(i->data);
2896             if (remove_original) {
2897                 items_to_delete = g_slist_prepend(items_to_delete, item);
2898             }
2899             else {
2900                 items_to_select = g_slist_prepend(items_to_select, item);
2901             }
2902         }
2903     } else if (!topmost) {
2904         // topmost item is used as a mask, which is applied to other items in a selection
2905         GSList *i = items;
2906         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2907         mask_items = g_slist_prepend(mask_items, dup);
2909         if (remove_original) {
2910             SPObject *item = reinterpret_cast<SPObject*>(i->data);
2911             items_to_delete = g_slist_prepend(items_to_delete, item);
2912         }
2914         for (i = i->next; i != NULL; i = i->next) {
2915             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2916             items_to_select = g_slist_prepend(items_to_select, i->data);
2917         }
2918     } else {
2919         GSList *i = NULL;
2920         for (i = items; NULL != i->next; i = i->next) {
2921             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2922             items_to_select = g_slist_prepend(items_to_select, i->data);
2923         }
2925         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2926         mask_items = g_slist_prepend(mask_items, dup);
2928         if (remove_original) {
2929             SPObject *item = reinterpret_cast<SPObject*>(i->data);
2930             items_to_delete = g_slist_prepend(items_to_delete, item);
2931         }
2932     }
2934     g_slist_free(items);
2935     items = NULL;
2937     if (apply_to_items && grouping == PREFS_MASKOBJECT_GROUPING_ALL) {
2938         // group all those objects into one group
2939         // and apply mask to that
2940         Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2942         // make a note we should ungroup this when unsetting mask
2943         group->setAttribute("inkscape:groupmode", "maskhelper");
2945         GSList *reprs_to_group = NULL;
2947         for (GSList *i = apply_to_items ; NULL != i ; i = i->next) {
2948                 reprs_to_group = g_slist_prepend(reprs_to_group, SP_OBJECT_REPR(i->data));
2949                 items_to_select = g_slist_remove(items_to_select, i->data);
2950         }
2951         reprs_to_group = g_slist_reverse(reprs_to_group);
2953         sp_selection_group_impl(reprs_to_group, group, xml_doc, doc);
2955         reprs_to_group = NULL;
2957         // apply clip/mask only to newly created group
2958         g_slist_free(apply_to_items);
2959         apply_to_items = NULL;
2960         apply_to_items = g_slist_prepend(apply_to_items, doc->getObjectByRepr(group));
2962         items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
2964         Inkscape::GC::release(group);
2965     }
2967     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2968     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2969         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2970         // inverted object transform should be applied to a mask object,
2971         // as mask is calculated in user space (after applying transform)
2972         Geom::Matrix maskTransform(item->transform.inverse());
2974         GSList *mask_items_dup = NULL;
2975         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2976             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2977             mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2978         }
2980         gchar const *mask_id = NULL;
2981         if (apply_clip_path) {
2982             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2983         } else {
2984             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2985         }
2987         g_slist_free(mask_items_dup);
2988         mask_items_dup = NULL;
2990         Inkscape::XML::Node *current = SP_OBJECT_REPR(i->data);
2991         // Node to apply mask to
2992         Inkscape::XML::Node *apply_mask_to = current;
2994         if (grouping == PREFS_MASKOBJECT_GROUPING_SEPARATE) {
2995             // enclose current node in group, and apply crop/mask on that
2996             Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2997             // make a note we should ungroup this when unsetting mask
2998             group->setAttribute("inkscape:groupmode", "maskhelper");
3000             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
3001             gint position = current->position();
3002             items_to_select = g_slist_remove(items_to_select, item);
3003             current->parent()->appendChild(group);
3004             sp_repr_unparent(current);
3005             group->appendChild(spnew);
3006             group->setPosition(position);
3008             // Apply clip/mask to group instead
3009             apply_mask_to = group;
3011             items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
3012             Inkscape::GC::release(spnew);
3013             Inkscape::GC::release(group);
3014         }
3016         apply_mask_to->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3018     }
3020     g_slist_free(mask_items);
3021     g_slist_free(apply_to_items);
3023     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3024         SPObject *item = reinterpret_cast<SPObject*>(i->data);
3025         item->deleteObject(false);
3026         items_to_select = g_slist_remove(items_to_select, item);
3027     }
3028     g_slist_free(items_to_delete);
3030     items_to_select = g_slist_reverse(items_to_select);
3032     selection->addList(items_to_select);
3033     g_slist_free(items_to_select);
3035     if (apply_clip_path)
3036         sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3037     else
3038         sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3041 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
3042     if (desktop == NULL)
3043         return;
3045     SPDocument *doc = sp_desktop_document(desktop);
3046     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3047     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3049     // check if something is selected
3050     if (selection->isEmpty()) {
3051         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3052         return;
3053     }
3055     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
3056     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
3057     bool ungroup_masked = prefs->getBool("/options/maskobject/ungrouping", true);
3058     sp_document_ensure_up_to_date(doc);
3060     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3061     std::map<SPObject*,SPItem*> referenced_objects;
3063     GSList *items = g_slist_copy((GSList *) selection->itemList());
3064     selection->clear();
3066     GSList *items_to_ungroup = NULL;
3067     GSList *items_to_select = g_slist_copy(items);
3068     items_to_select = g_slist_reverse(items_to_select);
3071     // SPObject* refers to a group containing the clipped path or mask itself,
3072     // whereas SPItem* refers to the item being clipped or masked
3073     for (GSList const *i = items; NULL != i; i = i->next) {
3074         if (remove_original) {
3075             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3076             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3077             Inkscape::URIReference *uri_ref = NULL;
3079             if (apply_clip_path) {
3080                 uri_ref = item->clip_ref;
3081             } else {
3082                 uri_ref = item->mask_ref;
3083             }
3085             // collect distinct mask object (and associate with item to apply transform)
3086             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3087                 referenced_objects[uri_ref->getObject()] = item;
3088             }
3089         }
3091         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3093         if (ungroup_masked && SP_IS_GROUP(i->data)) {
3094                 // if we had previously enclosed masked object in group,
3095                 // add it to list so we can ungroup it later
3096                 SPGroup *item = SP_GROUP(i->data);
3098                 // ungroup only groups we created when setting clip/mask
3099                 if (item->layerMode() == SPGroup::MASK_HELPER) {
3100                     items_to_ungroup = g_slist_prepend(items_to_ungroup, item);
3101                 }
3103         }
3104     }
3105     g_slist_free(items);
3107     // restore mask objects into a document
3108     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3109         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
3110         GSList *items_to_move = NULL;
3111         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3112             // Collect all clipped paths and masks within a single group
3113             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3114             items_to_move = g_slist_prepend(items_to_move, copy);
3115         }
3117         if (!obj->isReferenced()) {
3118             // delete from defs if no other object references this mask
3119             obj->deleteObject(false);
3120         }
3122         // remember parent and position of the item to which the clippath/mask was applied
3123         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3124         gint pos = SP_OBJECT_REPR((*it).second)->position();
3126         // Iterate through all clipped paths / masks
3127         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3128             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3130             // insert into parent, restore pos
3131             parent->appendChild(repr);
3132             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3134             SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3135             items_to_select = g_slist_prepend(items_to_select, mask_item);
3137             // transform mask, so it is moved the same spot where mask was applied
3138             Geom::Matrix transform(mask_item->transform);
3139             transform *= (*it).second->transform;
3140             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3141         }
3143         g_slist_free(items_to_move);
3144     }
3146     // ungroup marked groups added when setting mask
3147     for (GSList *i = items_to_ungroup ; NULL != i ; i = i->next) {
3148         items_to_select = g_slist_remove(items_to_select, SP_GROUP(i->data));
3149         GSList *children = NULL;
3150         sp_item_group_ungroup(SP_GROUP(i->data), &children, false);
3151         items_to_select = g_slist_concat(children, items_to_select);
3152     }
3154     g_slist_free(items_to_ungroup);
3156     // rebuild selection
3157     items_to_select = g_slist_reverse(items_to_select);
3158     selection->addList(items_to_select);
3159     g_slist_free(items_to_select);
3161     if (apply_clip_path)
3162         sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3163     else
3164         sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3167 /**
3168  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3169  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3170  * \return true if an undoable change should be recorded.
3171  */
3172 bool
3173 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3175     g_return_val_if_fail(desktop != NULL, false);
3176     SPDocument *doc = sp_desktop_document(desktop);
3178     g_return_val_if_fail(doc != NULL, false);
3179     g_return_val_if_fail(desktop->selection != NULL, false);
3181     if (desktop->selection->isEmpty()) {
3182         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3183         return false;
3184     }
3185     Geom::OptRect const bbox(desktop->selection->bounds(SPItem::RENDERING_BBOX));
3186     if (bbox) {
3187         doc->fitToRect(*bbox, with_margins);
3188         return true;
3189     } else {
3190         return false;
3191     }
3194 /**
3195  * Fit canvas to the bounding box of the selection, as an undoable action.
3196  */
3197 void
3198 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3200     if (fit_canvas_to_selection(desktop)) {
3201         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3202                          _("Fit Page to Selection"));
3203     }
3206 /**
3207  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3208  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3209  */
3210 bool
3211 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3213     g_return_val_if_fail(doc != NULL, false);
3215     sp_document_ensure_up_to_date(doc);
3216     SPItem const *const root = SP_ITEM(doc->root);
3217     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
3218     if (bbox) {
3219         doc->fitToRect(*bbox, with_margins);
3220         return true;
3221     } else {
3222         return false;
3223     }
3226 void
3227 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3229     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3230         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3231                          _("Fit Page to Drawing"));
3232     }
3235 /**
3236  * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3237  * "fit-margin-..." attributes.  See SPDocument::fitToRect and
3238  * ui/dialog/page-sizer.
3239  */
3240 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3241     g_return_if_fail(desktop != NULL);
3242     SPDocument *doc = sp_desktop_document(desktop);
3244     g_return_if_fail(doc != NULL);
3245     g_return_if_fail(desktop->selection != NULL);
3247     bool const changed = ( desktop->selection->isEmpty()
3248                            ? fit_canvas_to_drawing(doc, true)
3249                            : fit_canvas_to_selection(desktop, true) );
3250     if (changed) {
3251         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3252                          _("Fit Page to Selection or Drawing"));
3253     }
3254 };
3256 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3257     // don't operate on layers
3258     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3259         f(SP_ITEM(root), desktop);
3260     }
3261     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3262         //don't recurse into locked layers
3263         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3264             itemtree_map(f, iter, desktop);
3265         }
3266     }
3269 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3270     if (item->isLocked()) {
3271         item->setLocked(FALSE);
3272     }
3275 static void unhide(SPItem *item, SPDesktop *desktop) {
3276     if (desktop->itemIsHidden(item)) {
3277         item->setExplicitlyHidden(FALSE);
3278     }
3281 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3282     if (!dt) return;
3284     SPObject *root;
3285     if (layer_only) {
3286         root = dt->currentLayer();
3287     } else {
3288         root = dt->currentRoot();
3289     }
3291     itemtree_map(f, root, dt);
3294 void unlock_all(SPDesktop *dt) {
3295     process_all(&unlock, dt, true);
3298 void unlock_all_in_all_layers(SPDesktop *dt) {
3299     process_all(&unlock, dt, false);
3302 void unhide_all(SPDesktop *dt) {
3303     process_all(&unhide, dt, true);
3306 void unhide_all_in_all_layers(SPDesktop *dt) {
3307     process_all(&unhide, dt, false);
3311 /*
3312   Local Variables:
3313   mode:c++
3314   c-file-style:"stroustrup"
3315   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3316   indent-tabs-mode:nil
3317   fill-column:99
3318   End:
3319 */
3320 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :