Code

A simple layout document as to what, why and how is cppification.
[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(i->data)->i2doc_affine(), 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(parent)->i2doc_affine());
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 = (SPItem *) i->data;
289         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
290         sp_object_unref((SPObject *)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             SPDocumentUndo::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     SPDocumentUndo::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 = obj->first_child() ; 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             }
419         }
420     }
423     if ( !suppressDone ) {
424         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
425                          _("Duplicate"));
426     }
428     selection->setReprList(newsel);
430     g_slist_free(newsel);
433 void sp_edit_clear_all(SPDesktop *dt)
435     if (!dt)
436         return;
438     SPDocument *doc = sp_desktop_document(dt);
439     sp_desktop_selection(dt)->clear();
441     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
442     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
444     while (items) {
445         SP_OBJECT(items->data)->deleteObject();
446         items = g_slist_remove(items, items->data);
447     }
449     SPDocumentUndo::done(doc, SP_VERB_EDIT_CLEAR_ALL,
450                      _("Delete all"));
453 GSList *
454 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
456     for (SPObject *child = SP_OBJECT(from)->first_child() ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
457         if (SP_IS_ITEM(child) &&
458             !desktop->isLayer(SP_ITEM(child)) &&
459             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
460             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
461             (!exclude || !g_slist_find((GSList *) exclude, child))
462             )
463         {
464             list = g_slist_prepend(list, SP_ITEM(child));
465         }
467         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
468             list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
469         }
470     }
472     return list;
475 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
477     if (!dt)
478         return;
480     Inkscape::Selection *selection = sp_desktop_selection(dt);
482     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
484     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
485     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
486     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
487     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
489     GSList *items = NULL;
491     GSList const *exclude = NULL;
492     if (invert) {
493         exclude = selection->itemList();
494     }
496     if (force_all_layers)
497         inlayer = PREFS_SELECTION_ALL;
499     switch (inlayer) {
500         case PREFS_SELECTION_LAYER: {
501         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
502              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
503         return;
505         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
507         for (GSList *i = all_items; i; i = i->next) {
508             SPItem *item = SP_ITEM(i->data);
510             if (item && (!onlysensitive || !item->isLocked())) {
511                 if (!onlyvisible || !dt->itemIsHidden(item)) {
512                     if (!dt->isLayer(item)) {
513                         if (!invert || !g_slist_find((GSList *) exclude, item)) {
514                             items = g_slist_prepend(items, item); // leave it in the list
515                         }
516                     }
517                 }
518             }
519         }
521         g_slist_free(all_items);
522             break;
523         }
524         case PREFS_SELECTION_LAYER_RECURSIVE: {
525             items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
526             break;
527         }
528         default: {
529         items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
530             break;
531     }
532     }
534     selection->setList(items);
536     if (items) {
537         g_slist_free(items);
538     }
541 void sp_edit_select_all(SPDesktop *desktop)
543     sp_edit_select_all_full(desktop, false, false);
546 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
548     sp_edit_select_all_full(desktop, true, false);
551 void sp_edit_invert(SPDesktop *desktop)
553     sp_edit_select_all_full(desktop, false, true);
556 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
558     sp_edit_select_all_full(desktop, true, true);
561 void sp_selection_group_impl(GSList *p, Inkscape::XML::Node *group, Inkscape::XML::Document *xml_doc, SPDocument *doc) {
562     
563     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
565     // Remember the position and parent of the topmost object.
566     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
567     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
569     while (p) {
570         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
572         if (current->parent() == topmost_parent) {
573             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
574             sp_repr_unparent(current);
575             group->appendChild(spnew);
576             Inkscape::GC::release(spnew);
577             topmost --; // only reduce count for those items deleted from topmost_parent
578         } else { // move it to topmost_parent first
579             GSList *temp_clip = NULL;
581             // At this point, current may already have no item, due to its being a clone whose original is already moved away
582             // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
583             gchar const *t_str = current->attribute("transform");
584             Geom::Matrix item_t(Geom::identity());
585             if (t_str)
586                 sp_svg_transform_read(t_str, &item_t);
587             item_t *= SP_ITEM(doc->getObjectByRepr(current->parent()))->i2doc_affine();
588             // FIXME: when moving both clone and original from a transformed group (either by
589             // grouping into another parent, or by cut/paste) the transform from the original's
590             // parent becomes embedded into original itself, and this affects its clones. Fix
591             // this by remembering the transform diffs we write to each item into an array and
592             // then, if this is clone, looking up its original in that array and pre-multiplying
593             // it by the inverse of that original's transform diff.
595             sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
596             sp_repr_unparent(current);
598             // paste into topmost_parent (temporarily)
599             GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
600             if (temp_clip) g_slist_free(temp_clip);
601             if (copied) { // if success,
602                 // take pasted object (now in topmost_parent)
603                 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
604                 // make a copy
605                 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
606                 // remove pasted
607                 sp_repr_unparent(in_topmost);
608                 // put its copy into group
609                 group->appendChild(spnew);
610                 Inkscape::GC::release(spnew);
611                 g_slist_free(copied);
612             }
613         }
614         p = g_slist_remove(p, current);
615     }
617     // Add the new group to the topmost members' parent
618     topmost_parent->appendChild(group);
620     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
621     group->setPosition(topmost + 1);
624 void sp_selection_group(SPDesktop *desktop)
626     if (desktop == NULL)
627         return;
629     SPDocument *doc = sp_desktop_document(desktop);
630     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
632     Inkscape::Selection *selection = sp_desktop_selection(desktop);
634     // Check if something is selected.
635     if (selection->isEmpty()) {
636         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
637         return;
638     }
640     GSList const *l = (GSList *) selection->reprList();
641     
642     GSList *p = g_slist_copy((GSList *) l);
643     
644     selection->clear();
646     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
648     sp_selection_group_impl(p, group, xml_doc, doc);
650     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
651                      _("Group"));
653     selection->set(group);
654     Inkscape::GC::release(group);
657 void sp_selection_ungroup(SPDesktop *desktop)
659     if (desktop == NULL)
660         return;
662     Inkscape::Selection *selection = sp_desktop_selection(desktop);
664     if (selection->isEmpty()) {
665         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
666         return;
667     }
669     GSList *items = g_slist_copy((GSList *) selection->itemList());
670     selection->clear();
672     // Get a copy of current selection.
673     GSList *new_select = NULL;
674     bool ungrouped = false;
675     for (GSList *i = items;
676          i != NULL;
677          i = i->next)
678     {
679         SPItem *group = (SPItem *) i->data;
681         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
682         if (!SP_IS_OBJECT(group)) {
683             continue;
684         }
686         /* We do not allow ungrouping <svg> etc. (lauris) */
687         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
688             // keep the non-group item in the new selection
689             new_select = g_slist_append(new_select, group);
690             continue;
691         }
693         GSList *children = NULL;
694         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
695         sp_item_group_ungroup(SP_GROUP(group), &children, false);
696         ungrouped = true;
697         // Add ungrouped items to the new selection.
698         new_select = g_slist_concat(new_select, children);
699     }
701     if (new_select) { // Set new selection.
702         selection->addList(new_select);
703         g_slist_free(new_select);
704     }
705     if (!ungrouped) {
706         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
707     }
709     g_slist_free(items);
711     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
712                      _("Ungroup"));
715 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
716 GSList *
717 sp_degroup_list(GSList *items)
719     GSList *out = NULL;
720     bool has_groups = false;
721     for (GSList *item = items; item; item = item->next) {
722         if (!SP_IS_GROUP(item->data)) {
723             out = g_slist_prepend(out, item->data);
724         } else {
725             has_groups = true;
726             GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
727             for (GSList *member = members; member; member = member->next) {
728                 out = g_slist_prepend(out, member->data);
729             }
730             g_slist_free(members);
731         }
732     }
733     out = g_slist_reverse(out);
734     g_slist_free(items);
736     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
737         out = sp_degroup_list(out);
738     }
740     return out;
744 /** If items in the list have a common parent, return it, otherwise return NULL */
745 static SPGroup *
746 sp_item_list_common_parent_group(GSList const *items)
748     if (!items) {
749         return NULL;
750     }
751     SPObject *parent = SP_OBJECT_PARENT(items->data);
752     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
753     if (!SP_IS_GROUP(parent)) {
754         return NULL;
755     }
756     for (items = items->next; items; items = items->next) {
757         if (SP_OBJECT_PARENT(items->data) != parent) {
758             return NULL;
759         }
760     }
762     return SP_GROUP(parent);
765 /** Finds out the minimum common bbox of the selected items. */
766 static Geom::OptRect
767 enclose_items(GSList const *items)
769     g_assert(items != NULL);
771     Geom::OptRect r;
772     for (GSList const *i = items; i; i = i->next) {
773         r = Geom::unify(r, ((SPItem *) i->data)->getBboxDesktop());
774     }
775     return r;
778 SPObject *
779 prev_sibling(SPObject *child)
781     SPObject *parent = SP_OBJECT_PARENT(child);
782     if (!SP_IS_GROUP(parent)) {
783         return NULL;
784     }
785     for ( SPObject *i = parent->first_child() ; i; i = SP_OBJECT_NEXT(i) ) {
786         if (i->next == child)
787             return i;
788     }
789     return NULL;
792 void
793 sp_selection_raise(SPDesktop *desktop)
795     if (!desktop)
796         return;
798     Inkscape::Selection *selection = sp_desktop_selection(desktop);
800     GSList const *items = (GSList *) selection->itemList();
801     if (!items) {
802         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
803         return;
804     }
806     SPGroup const *group = sp_item_list_common_parent_group(items);
807     if (!group) {
808         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
809         return;
810     }
812     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
814     /* Construct reverse-ordered list of selected children. */
815     GSList *rev = g_slist_copy((GSList *) items);
816     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
818     // Determine the common bbox of the selected items.
819     Geom::OptRect selected = enclose_items(items);
821     // Iterate over all objects in the selection (starting from top).
822     if (selected) {
823         while (rev) {
824             SPObject *child = SP_OBJECT(rev->data);
825             // for each selected object, find the next sibling
826             for (SPObject *newref = child->next; newref; newref = newref->next) {
827                 // if the sibling is an item AND overlaps our selection,
828                 if (SP_IS_ITEM(newref)) {
829                     Geom::OptRect newref_bbox = SP_ITEM(newref)->getBboxDesktop();
830                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
831                         // AND if it's not one of our selected objects,
832                         if (!g_slist_find((GSList *) items, newref)) {
833                             // move the selected object after that sibling
834                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
835                         }
836                         break;
837                     }
838                 }
839             }
840             rev = g_slist_remove(rev, child);
841         }
842     } else {
843         g_slist_free(rev);
844     }
846     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
847                      //TRANSLATORS: only translate "string" in "context|string".
848                      // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
849                      // "Raise" means "to raise an object" in the undo history
850                      Q_("undo action|Raise"));
853 void sp_selection_raise_to_top(SPDesktop *desktop)
855     if (desktop == NULL)
856         return;
858     SPDocument *document = sp_desktop_document(desktop);
859     Inkscape::Selection *selection = sp_desktop_selection(desktop);
861     if (selection->isEmpty()) {
862         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
863         return;
864     }
866     GSList const *items = (GSList *) selection->itemList();
868     SPGroup const *group = sp_item_list_common_parent_group(items);
869     if (!group) {
870         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
871         return;
872     }
874     GSList *rl = g_slist_copy((GSList *) selection->reprList());
875     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
877     for (GSList *l = rl; l != NULL; l = l->next) {
878         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
879         repr->setPosition(-1);
880     }
882     g_slist_free(rl);
884     SPDocumentUndo::done(document, SP_VERB_SELECTION_TO_FRONT,
885                      _("Raise to top"));
888 void
889 sp_selection_lower(SPDesktop *desktop)
891     if (desktop == NULL)
892         return;
894     Inkscape::Selection *selection = sp_desktop_selection(desktop);
896     GSList const *items = (GSList *) selection->itemList();
897     if (!items) {
898         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
899         return;
900     }
902     SPGroup const *group = sp_item_list_common_parent_group(items);
903     if (!group) {
904         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
905         return;
906     }
908     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
910     // Determine the common bbox of the selected items.
911     Geom::OptRect selected = enclose_items(items);
913     /* Construct direct-ordered list of selected children. */
914     GSList *rev = g_slist_copy((GSList *) items);
915     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
916     rev = g_slist_reverse(rev);
918     // Iterate over all objects in the selection (starting from top).
919     if (selected) {
920         while (rev) {
921             SPObject *child = SP_OBJECT(rev->data);
922             // for each selected object, find the prev sibling
923             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
924                 // if the sibling is an item AND overlaps our selection,
925                 if (SP_IS_ITEM(newref)) {
926                     Geom::OptRect ref_bbox = SP_ITEM(newref)->getBboxDesktop();
927                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
928                         // AND if it's not one of our selected objects,
929                         if (!g_slist_find((GSList *) items, newref)) {
930                             // move the selected object before that sibling
931                             SPObject *put_after = prev_sibling(newref);
932                             if (put_after)
933                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
934                             else
935                                 SP_OBJECT_REPR(child)->setPosition(0);
936                         }
937                         break;
938                     }
939                 }
940             }
941             rev = g_slist_remove(rev, child);
942         }
943     } else {
944         g_slist_free(rev);
945     }
947     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
948                      _("Lower"));
951 void sp_selection_lower_to_bottom(SPDesktop *desktop)
953     if (desktop == NULL)
954         return;
956     SPDocument *document = sp_desktop_document(desktop);
957     Inkscape::Selection *selection = sp_desktop_selection(desktop);
959     if (selection->isEmpty()) {
960         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
961         return;
962     }
964     GSList const *items = (GSList *) selection->itemList();
966     SPGroup const *group = sp_item_list_common_parent_group(items);
967     if (!group) {
968         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
969         return;
970     }
972     GSList *rl;
973     rl = g_slist_copy((GSList *) selection->reprList());
974     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
975     rl = g_slist_reverse(rl);
977     for (GSList *l = rl; l != NULL; l = l->next) {
978         gint minpos;
979         SPObject *pp, *pc;
980         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
981         pp = document->getObjectByRepr(sp_repr_parent(repr));
982         minpos = 0;
983         g_assert(SP_IS_GROUP(pp));
984         pc = pp->first_child();
985         while (!SP_IS_ITEM(pc)) {
986             minpos += 1;
987             pc = pc->next;
988         }
989         repr->setPosition(minpos);
990     }
992     g_slist_free(rl);
994     SPDocumentUndo::done(document, SP_VERB_SELECTION_TO_BACK,
995                      _("Lower to bottom"));
998 void
999 sp_undo(SPDesktop *desktop, SPDocument *)
1001         if (!SPDocumentUndo::undo(sp_desktop_document(desktop)))
1002             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
1005 void
1006 sp_redo(SPDesktop *desktop, SPDocument *)
1008         if (!SPDocumentUndo::redo(sp_desktop_document(desktop)))
1009             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
1012 void sp_selection_cut(SPDesktop *desktop)
1014     sp_selection_copy(desktop);
1015     sp_selection_delete(desktop);
1018 /**
1019  * \pre item != NULL
1020  */
1021 SPCSSAttr *
1022 take_style_from_item(SPItem *item)
1024     // write the complete cascaded style, context-free
1025     SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1026     if (css == NULL)
1027         return NULL;
1029     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1030         (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1031         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1032         // If this is a group, merge the style of its topmost (last) child with style
1033         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
1034             if (SP_OBJECT_STYLE(last_element) != NULL) {
1035                 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1036                 if (temp) {
1037                     sp_repr_css_merge(css, temp);
1038                     sp_repr_css_attr_unref(temp);
1039                 }
1040                 break;
1041             }
1042         }
1043     }
1044     if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1045         // do not copy text properties from non-text objects, it's confusing
1046         css = sp_css_attr_unset_text(css);
1047     }
1049     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1050     double ex = to_2geom(item->i2doc_affine()).descrim();
1051     if (ex != 1.0) {
1052         css = sp_css_attr_scale(css, ex);
1053     }
1055     return css;
1059 void sp_selection_copy(SPDesktop *desktop)
1061     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1062     cm->copy(desktop);
1065 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1067     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1068     if (cm->paste(desktop, in_place)) {
1069         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1070     }
1073 void sp_selection_paste_style(SPDesktop *desktop)
1075     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1076     if (cm->pasteStyle(desktop)) {
1077         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1078     }
1082 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1084     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1085     if (cm->pastePathEffect(desktop)) {
1086         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1087                          _("Paste live path effect"));
1088     }
1092 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1094     if ( item && SP_IS_LPE_ITEM(item) &&
1095          sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1096         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1097     }
1100 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1102     if (desktop == NULL) return;
1104     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1106     // check if something is selected
1107     if (selection->isEmpty()) {
1108         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1109         return;
1110     }
1112     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1113         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1115         sp_selection_remove_livepatheffect_impl(item);
1117     }
1119     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1120                      _("Remove live path effect"));
1123 void sp_selection_remove_filter(SPDesktop *desktop)
1125     if (desktop == NULL) return;
1127     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1129     // check if something is selected
1130     if (selection->isEmpty()) {
1131         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1132         return;
1133     }
1135     SPCSSAttr *css = sp_repr_css_attr_new();
1136     sp_repr_css_unset_property(css, "filter");
1137     sp_desktop_set_style(desktop, css);
1138     sp_repr_css_attr_unref(css);
1140     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1141                      _("Remove filter"));
1145 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1147     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1148     if (cm->pasteSize(desktop, false, apply_x, apply_y)) {
1149         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1150                          _("Paste size"));
1151     }
1154 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1156     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1157     if (cm->pasteSize(desktop, true, apply_x, apply_y)) {
1158         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1159                          _("Paste size separately"));
1160     }
1163 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1165     Inkscape::Selection *selection = sp_desktop_selection(dt);
1167     // check if something is selected
1168     if (selection->isEmpty()) {
1169         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1170         return;
1171     }
1173     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1175     bool no_more = false; // Set to true, if no more layers above
1176     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1177     if (next) {
1178         GSList *temp_clip = NULL;
1179         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1180         sp_selection_delete_impl(items, false, false);
1181         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1182         GSList *copied;
1183         if (next) {
1184             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1185         } else {
1186             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1187             no_more = true;
1188         }
1189         selection->setReprList((GSList const *) copied);
1190         g_slist_free(copied);
1191         if (temp_clip) g_slist_free(temp_clip);
1192         if (next) dt->setCurrentLayer(next);
1193         if ( !suppressDone ) {
1194             SPDocumentUndo::done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1195                              _("Raise to next layer"));
1196         }
1197     } else {
1198         no_more = true;
1199     }
1201     if (no_more) {
1202         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1203     }
1205     g_slist_free((GSList *) items);
1208 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1210     Inkscape::Selection *selection = sp_desktop_selection(dt);
1212     // check if something is selected
1213     if (selection->isEmpty()) {
1214         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1215         return;
1216     }
1218     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1220     bool no_more = false; // Set to true, if no more layers below
1221     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1222     if (next) {
1223         GSList *temp_clip = NULL;
1224         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
1225         sp_selection_delete_impl(items, false, false);
1226         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1227         GSList *copied;
1228         if (next) {
1229             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1230         } else {
1231             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1232             no_more = true;
1233         }
1234         selection->setReprList((GSList const *) copied);
1235         g_slist_free(copied);
1236         if (temp_clip) g_slist_free(temp_clip);
1237         if (next) dt->setCurrentLayer(next);
1238         if ( !suppressDone ) {
1239             SPDocumentUndo::done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1240                              _("Lower to previous layer"));
1241         }
1242     } else {
1243         no_more = true;
1244     }
1246     if (no_more) {
1247         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1248     }
1250     g_slist_free((GSList *) items);
1253 bool
1254 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1256     bool contains_original = false;
1258     bool is_use = SP_IS_USE(item);
1259     SPItem *item_use = item;
1260     SPItem *item_use_first = item;
1261     while (is_use && item_use && !contains_original)
1262     {
1263         item_use = sp_use_get_original(SP_USE(item_use));
1264         contains_original |= selection->includes(item_use);
1265         if (item_use == item_use_first)
1266             break;
1267         is_use = SP_IS_USE(item_use);
1268     }
1270     // If it's a tref, check whether the object containing the character
1271     // data is part of the selection
1272     if (!contains_original && SP_IS_TREF(item)) {
1273         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1274     }
1276     return contains_original;
1280 bool
1281 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1283     bool clone_with_original = false;
1284     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1285         SPItem *item = SP_ITEM(l->data);
1286         clone_with_original |= selection_contains_original(item, selection);
1287         if (clone_with_original)
1288             break;
1289     }
1290     return clone_with_original;
1293 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1294 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1295 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1296 that case, items are already in the new position, but the repr is in the old, and this function
1297 then simply updates the repr from item->transform.
1298  */
1299 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1301     if (selection->isEmpty())
1302         return;
1304     // For each perspective with a box in selection, check whether all boxes are selected and
1305     // unlink all non-selected boxes.
1306     Persp3D *persp;
1307     Persp3D *transf_persp;
1308     std::list<Persp3D *> plist = selection->perspList();
1309     for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1310         persp = (Persp3D *) (*i);
1312         if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1313             std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1315             // create a new perspective as a copy of the current one and link the selected boxes to it
1316             transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1318             for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1319                 box3d_switch_perspectives(*b, persp, transf_persp);
1320         } else {
1321             transf_persp = persp;
1322         }
1324         persp3d_apply_affine_transformation(transf_persp, affine);
1325     }
1327     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1328         SPItem *item = SP_ITEM(l->data);
1330         Geom::Point old_center(0,0);
1331         if (set_i2d && item->isCenterSet())
1332             old_center = item->getCenter();
1334 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1335          At the time of writing, this is the only place to re-enable. */
1336         sp_item_update_cns(*item, selection->desktop());
1337 #endif
1339         // we're moving both a clone and its original or any ancestor in clone chain?
1340         bool transform_clone_with_original = selection_contains_original(item, selection);
1341         // ...both a text-on-path and its path?
1342         bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item(SP_TEXTPATH(SP_OBJECT(item)->first_child())) ));
1343         // ...both a flowtext and its frame?
1344         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)
1345         // ...both an offset and its source?
1346         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1348         // If we're moving a connector, we want to detach it
1349         // from shapes that aren't part of the selection, but
1350         // leave it attached if they are
1351         if (cc_item_is_connector(item)) {
1352             SPItem *attItem[2];
1353             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1355             for (int n = 0; n < 2; ++n) {
1356                 if (!selection->includes(attItem[n])) {
1357                     sp_conn_end_detach(item, n);
1358                 }
1359             }
1360         }
1362         // "clones are unmoved when original is moved" preference
1363         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1364         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1365         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1366         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1368         /* If this is a clone and it's selected along with its original, do not move it;
1369          * it will feel the transform of its original and respond to it itself.
1370          * Without this, a clone is doubly transformed, very unintuitive.
1371          *
1372          * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1373          * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1374          * Same for linked offset if we are also moving its source: do not move it. */
1375         if (transform_textpath_with_path || transform_offset_with_source) {
1376             // Restore item->transform field from the repr, in case it was changed by seltrans.
1377             SP_OBJECT(item)->readAttr( "transform");
1378         } else if (transform_flowtext_with_frame) {
1379             // apply the inverse of the region's transform to the <use> so that the flow remains
1380             // the same (even though the output itself gets transformed)
1381             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1382                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1383                     continue;
1384                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1385                     if (!SP_IS_USE(use)) continue;
1386                     SP_USE(use)->doWriteTransform(SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1387                 }
1388             }
1389         } else if (transform_clone_with_original) {
1390             // We are transforming a clone along with its original. The below matrix juggling is
1391             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1392             // transform and its move compensation are both cancelled out.
1394             // restore item->transform field from the repr, in case it was changed by seltrans
1395             SP_OBJECT(item)->readAttr( "transform");
1397             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1398             Geom::Matrix parent2dt = SP_ITEM(SP_OBJECT_PARENT(item))->i2d_affine();
1399             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1400             Geom::Matrix t_inv = t.inverse();
1401             Geom::Matrix result = t_inv * item->transform * t;
1403             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1404                 // we need to cancel out the move compensation, too
1406                 // find out the clone move, same as in sp_use_move_compensate
1407                 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1408                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1410                 if (prefs_parallel) {
1411                     Geom::Matrix move = result * clone_move * t_inv;
1412                     item->doWriteTransform(SP_OBJECT_REPR(item), move, &move, compensate);
1414                 } else if (prefs_unmoved) {
1415                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1416                     //    clone_move = Geom::identity();
1417                     Geom::Matrix move = result * clone_move;
1418                     item->doWriteTransform(SP_OBJECT_REPR(item), move, &t, compensate);
1419                 }
1421             } else {
1422                 // just apply the result
1423                 item->doWriteTransform(SP_OBJECT_REPR(item), result, &t, compensate);
1424             }
1426         } else {
1427             if (set_i2d) {
1428                 item->set_i2d_affine(item->i2d_affine() * (Geom::Matrix)affine);
1429             }
1430             item->doWriteTransform(SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1431         }
1433         // if we're moving the actual object, not just updating the repr, we can transform the
1434         // center by the same matrix (only necessary for non-translations)
1435         if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1436             item->setCenter(old_center * affine);
1437             SP_OBJECT(item)->updateRepr();
1438         }
1439     }
1442 void sp_selection_remove_transform(SPDesktop *desktop)
1444     if (desktop == NULL)
1445         return;
1447     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1449     GSList const *l = (GSList *) selection->reprList();
1450     while (l != NULL) {
1451         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1452         l = l->next;
1453     }
1455     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1456                      _("Remove transform"));
1459 void
1460 sp_selection_scale_absolute(Inkscape::Selection *selection,
1461                             double const x0, double const x1,
1462                             double const y0, double const y1)
1464     if (selection->isEmpty())
1465         return;
1467     Geom::OptRect const bbox(selection->bounds());
1468     if ( !bbox ) {
1469         return;
1470     }
1472     Geom::Translate const p2o(-bbox->min());
1474     Geom::Scale const newSize(x1 - x0,
1475                               y1 - y0);
1476     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1477     Geom::Translate const o2n(x0, y0);
1478     Geom::Matrix const final( p2o * scale * o2n );
1480     sp_selection_apply_affine(selection, final);
1484 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1486     if (selection->isEmpty())
1487         return;
1489     Geom::OptRect const bbox(selection->bounds());
1491     if ( !bbox ) {
1492         return;
1493     }
1495     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1496     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1497          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1498     {
1499         return;
1500     }
1502     Geom::Translate const n2d(-align);
1503     Geom::Translate const d2n(align);
1504     Geom::Matrix const final( n2d * scale * d2n );
1505     sp_selection_apply_affine(selection, final);
1508 void
1509 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1511     Geom::Translate const d2n(center);
1512     Geom::Translate const n2d(-center);
1513     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1514     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1515     sp_selection_apply_affine(selection, final);
1518 void
1519 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1521     Geom::Translate const d2n(align);
1522     Geom::Translate const n2d(-align);
1523     Geom::Matrix const skew(1, dy,
1524                             dx, 1,
1525                             0, 0);
1526     Geom::Matrix const final( n2d * skew * d2n );
1527     sp_selection_apply_affine(selection, final);
1530 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1532     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1535 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1537     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1540 /**
1541  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1542  */
1543 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1545     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1547     if (selection->isEmpty())
1548         return;
1550     GSList const *l = selection->itemList();
1551     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1552     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1553         SPItem *item = SP_ITEM(l2->data);
1554         sp_item_rotate_rel(item, rot_90);
1555     }
1557     SPDocumentUndo::done(sp_desktop_document(desktop),
1558                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1559                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1562 void
1563 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1565     if (selection->isEmpty())
1566         return;
1568     boost::optional<Geom::Point> center = selection->center();
1569     if (!center) {
1570         return;
1571     }
1573     sp_selection_rotate_relative(selection, *center, angle_degrees);
1575     SPDocumentUndo::maybe_done(sp_desktop_document(selection->desktop()),
1576                            ( ( angle_degrees > 0 )
1577                              ? "selector:rotate:ccw"
1578                              : "selector:rotate:cw" ),
1579                            SP_VERB_CONTEXT_SELECT,
1580                            _("Rotate"));
1583 // helper function:
1584 static
1585 Geom::Point
1586 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1587     Geom::Point m = r.midpoint();
1588     unsigned i = 0;
1589     if (p[X] < m[X]) {
1590         i = 1;
1591     }
1592     if (p[Y] < m[Y]) {
1593         i = 3 - i;
1594     }
1595     return r.corner(i);
1598 /**
1599 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1600 */
1601 void
1602 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1604     if (selection->isEmpty())
1605         return;
1607     Geom::OptRect const bbox(selection->bounds());
1608     boost::optional<Geom::Point> center = selection->center();
1610     if ( !bbox || !center ) {
1611         return;
1612     }
1614     gdouble const zoom = selection->desktop()->current_zoom();
1615     gdouble const zmove = angle / zoom;
1616     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1618     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1620     sp_selection_rotate_relative(selection, *center, zangle);
1622     SPDocumentUndo::maybe_done(sp_desktop_document(selection->desktop()),
1623                            ( (angle > 0)
1624                              ? "selector:rotate:ccw"
1625                              : "selector:rotate:cw" ),
1626                            SP_VERB_CONTEXT_SELECT,
1627                            _("Rotate by pixels"));
1630 void
1631 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1633     if (selection->isEmpty())
1634         return;
1636     Geom::OptRect const bbox(selection->bounds());
1637     if (!bbox) {
1638         return;
1639     }
1641     Geom::Point const center(bbox->midpoint());
1643     // you can't scale "do nizhe pola" (below zero)
1644     double const max_len = bbox->maxExtent();
1645     if ( max_len + grow <= 1e-3 ) {
1646         return;
1647     }
1649     double const times = 1.0 + grow / max_len;
1650     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1652     SPDocumentUndo::maybe_done(sp_desktop_document(selection->desktop()),
1653                            ( (grow > 0)
1654                              ? "selector:scale:larger"
1655                              : "selector:scale:smaller" ),
1656                            SP_VERB_CONTEXT_SELECT,
1657                            _("Scale"));
1660 void
1661 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1663     sp_selection_scale(selection,
1664                        grow_pixels / selection->desktop()->current_zoom());
1667 void
1668 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1670     if (selection->isEmpty())
1671         return;
1673     Geom::OptRect sel_bbox = selection->bounds();
1675     if (!sel_bbox) {
1676         return;
1677     }
1679     Geom::Point const center(sel_bbox->midpoint());
1680     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1681     SPDocumentUndo::done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1682                      _("Scale by whole factor"));
1685 void
1686 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1688     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1689     if (selection->isEmpty()) {
1690         return;
1691     }
1693     sp_selection_move_relative(selection, dx, dy);
1695     if (dx == 0) {
1696         SPDocumentUndo::maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1697                                _("Move vertically"));
1698     } else if (dy == 0) {
1699         SPDocumentUndo::maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1700                                _("Move horizontally"));
1701     } else {
1702         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1703                          _("Move"));
1704     }
1707 void
1708 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1710     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1711     if (selection->isEmpty()) {
1712         return;
1713     }
1715     // same as sp_selection_move but divide deltas by zoom factor
1716     gdouble const zoom = desktop->current_zoom();
1717     gdouble const zdx = dx / zoom;
1718     gdouble const zdy = dy / zoom;
1719     sp_selection_move_relative(selection, zdx, zdy);
1721     if (dx == 0) {
1722         SPDocumentUndo::maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1723                                _("Move vertically by pixels"));
1724     } else if (dy == 0) {
1725         SPDocumentUndo::maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1726                                _("Move horizontally by pixels"));
1727     } else {
1728         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1729                          _("Move"));
1730     }
1733 namespace {
1735 template <typename D>
1736 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1737                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1739 template <typename D>
1740 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1741                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1743 struct Forward {
1744     typedef SPObject *Iterator;
1746     static Iterator children(SPObject *o) { return o->first_child(); }
1747     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1748     static void dispose(Iterator /*i*/) {}
1750     static SPObject *object(Iterator i) { return i; }
1751     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1752 };
1754 struct ListReverse {
1755     typedef GSList *Iterator;
1757     static Iterator children(SPObject *o) {
1758         return make_list(o->firstChild(), NULL);
1759     }
1760     static Iterator siblings_after(SPObject *o) {
1761         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1762     }
1763     static void dispose(Iterator i) {
1764         g_slist_free(i);
1765     }
1767     static SPObject *object(Iterator i) {
1768         return reinterpret_cast<SPObject *>(i->data);
1769     }
1770     static Iterator next(Iterator i) { return i->next; }
1772 private:
1773     static GSList *make_list(SPObject *object, SPObject *limit) {
1774         GSList *list=NULL;
1775         while ( object != limit ) {
1776             list = g_slist_prepend(list, object);
1777             object = SP_OBJECT_NEXT(object);
1778         }
1779         return list;
1780     }
1781 };
1785 void
1786 sp_selection_item_next(SPDesktop *desktop)
1788     g_return_if_fail(desktop != NULL);
1789     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1791     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1792     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1793     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1794     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1796     SPObject *root;
1797     if (PREFS_SELECTION_ALL != inlayer) {
1798         root = selection->activeContext();
1799     } else {
1800         root = desktop->currentRoot();
1801     }
1803     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1805     if (item) {
1806         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1807         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1808             scroll_to_show_item(desktop, item);
1809         }
1810     }
1813 void
1814 sp_selection_item_prev(SPDesktop *desktop)
1816     SPDocument *document = sp_desktop_document(desktop);
1817     g_return_if_fail(document != NULL);
1818     g_return_if_fail(desktop != NULL);
1819     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1821     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1822     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1823     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1824     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1826     SPObject *root;
1827     if (PREFS_SELECTION_ALL != inlayer) {
1828         root = selection->activeContext();
1829     } else {
1830         root = desktop->currentRoot();
1831     }
1833     SPItem *item=next_item_from_list<ListReverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1835     if (item) {
1836         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1837         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1838             scroll_to_show_item(desktop, item);
1839         }
1840     }
1843 void sp_selection_next_patheffect_param(SPDesktop * dt)
1845     if (!dt) return;
1847     Inkscape::Selection *selection = sp_desktop_selection(dt);
1848     if ( selection && !selection->isEmpty() ) {
1849         SPItem *item = selection->singleItem();
1850         if ( item && SP_IS_SHAPE(item)) {
1851             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1852                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1853             } else {
1854                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1855             }
1856         }
1857     }
1860 /*bool has_path_recursive(SPObject *obj)
1862     if (!obj) return false;
1863     if (SP_IS_PATH(obj)) {
1864         return true;
1865     }
1866     if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1867         for (SPObject *c = obj->children; c; c = c->next) {
1868             if (has_path_recursive(c)) return true;
1869         }
1870     }
1871     return false;
1872 }*/
1874 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1876     return;
1877     /*if (!dt) return;
1878     using namespace Inkscape::UI;
1880     Inkscape::Selection *selection = sp_desktop_selection(dt);
1881     if (!selection || selection->isEmpty()) return;
1883     GSList const *items = selection->itemList();
1884     bool has_path = false;
1885     for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1886         SPItem *item = SP_ITEM(i->data);
1887         SPObject *search = clip
1888             ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1889             : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1890         has_path |= has_path_recursive(search);
1891         if (has_path) break;
1892     }
1893     if (has_path) {
1894         if (!tools_isactive(dt, TOOLS_NODES)) {
1895             tools_switch(dt, TOOLS_NODES);
1896         }
1897         ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1898             clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1899     } else if (clip) {
1900         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1901             _("The selection has no applied clip path."));
1902     } else {
1903         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1904             _("The selection has no applied mask."));
1905     }*/
1909 namespace {
1911 template <typename D>
1912 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1913                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1915     SPObject *current=root;
1916     while (items) {
1917         SPItem *item=SP_ITEM(items->data);
1918         if ( root->isAncestorOf(item) &&
1919              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1920         {
1921             current = item;
1922             break;
1923         }
1924         items = items->next;
1925     }
1927     GSList *path=NULL;
1928     while ( current != root ) {
1929         path = g_slist_prepend(path, current);
1930         current = SP_OBJECT_PARENT(current);
1931     }
1933     SPItem *next;
1934     // first, try from the current object
1935     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1936     g_slist_free(path);
1938     if (!next) { // if we ran out of objects, start over at the root
1939         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1940     }
1942     return next;
1945 template <typename D>
1946 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1947                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1949     typename D::Iterator children;
1950     typename D::Iterator iter;
1952     SPItem *found=NULL;
1954     if (path) {
1955         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1956         g_assert(SP_OBJECT_PARENT(object) == root);
1957         if (desktop->isLayer(object)) {
1958             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1959         }
1960         iter = children = D::siblings_after(object);
1961     } else {
1962         iter = children = D::children(root);
1963     }
1965     while ( iter && !found ) {
1966         SPObject *object=D::object(iter);
1967         if (desktop->isLayer(object)) {
1968             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1969                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1970             }
1971         } else if ( SP_IS_ITEM(object) &&
1972                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1973                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1974                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1975                     !desktop->isLayer(SP_ITEM(object)) )
1976         {
1977             found = SP_ITEM(object);
1978         }
1979         iter = D::next(iter);
1980     }
1982     D::dispose(children);
1984     return found;
1989 /**
1990  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1991  * \a item.
1992  */
1993 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1995     Geom::Rect dbox = desktop->get_display_area();
1996     Geom::OptRect sbox = item->getBboxDesktop();
1998     if ( sbox && dbox.contains(*sbox) == false ) {
1999         Geom::Point const s_dt = sbox->midpoint();
2000         Geom::Point const s_w = desktop->d2w(s_dt);
2001         Geom::Point const d_dt = dbox.midpoint();
2002         Geom::Point const d_w = desktop->d2w(d_dt);
2003         Geom::Point const moved_w( d_w - s_w );
2004         gint const dx = (gint) moved_w[X];
2005         gint const dy = (gint) moved_w[Y];
2006         desktop->scroll_world(dx, dy);
2007     }
2011 void
2012 sp_selection_clone(SPDesktop *desktop)
2014     if (desktop == NULL)
2015         return;
2017     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2019     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2021     // check if something is selected
2022     if (selection->isEmpty()) {
2023         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2024         return;
2025     }
2027     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2029     selection->clear();
2031     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2032     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2034     GSList *newsel = NULL;
2036     while (reprs) {
2037         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2038         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2040         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2041         clone->setAttribute("x", "0", false);
2042         clone->setAttribute("y", "0", false);
2043         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2045         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2046         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2048         // add the new clone to the top of the original's parent
2049         parent->appendChild(clone);
2051         newsel = g_slist_prepend(newsel, clone);
2052         reprs = g_slist_remove(reprs, sel_repr);
2053         Inkscape::GC::release(clone);
2054     }
2056     // TRANSLATORS: only translate "string" in "context|string".
2057     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2058     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2059                      Q_("action|Clone"));
2061     selection->setReprList(newsel);
2063     g_slist_free(newsel);
2066 void
2067 sp_selection_relink(SPDesktop *desktop)
2069     if (!desktop)
2070         return;
2072     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2074     if (selection->isEmpty()) {
2075         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2076         return;
2077     }
2079     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2080     const gchar *newid = cm->getFirstObjectID();
2081     if (!newid) {
2082         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2083         return;
2084     }
2085     gchar *newref = g_strdup_printf("#%s", newid);
2087     // Get a copy of current selection.
2088     bool relinked = false;
2089     for (GSList *items = (GSList *) selection->itemList();
2090          items != NULL;
2091          items = items->next)
2092     {
2093         SPItem *item = (SPItem *) items->data;
2095         if (!SP_IS_USE(item))
2096             continue;
2098         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2099         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2100         relinked = true;
2101     }
2103     g_free(newref);
2105     if (!relinked) {
2106         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2107     } else {
2108         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2109                          _("Relink clone"));
2110     }
2114 void
2115 sp_selection_unlink(SPDesktop *desktop)
2117     if (!desktop)
2118         return;
2120     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2122     if (selection->isEmpty()) {
2123         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2124         return;
2125     }
2127     // Get a copy of current selection.
2128     GSList *new_select = NULL;
2129     bool unlinked = false;
2130     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2131          items != NULL;
2132          items = items->next)
2133     {
2134         SPItem *item = (SPItem *) items->data;
2136         if (SP_IS_TEXT(item)) {
2137             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2139             if (tspan) {
2140                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2141             }
2143             // Set unlink to true, and fall into the next if which
2144             // will include this text item in the new selection
2145             unlinked = true;
2146         }
2148         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2149             // keep the non-use item in the new selection
2150             new_select = g_slist_prepend(new_select, item);
2151             continue;
2152         }
2154         SPItem *unlink;
2155         if (SP_IS_USE(item)) {
2156             unlink = sp_use_unlink(SP_USE(item));
2157         } else /*if (SP_IS_TREF(use))*/ {
2158             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2159         }
2161         unlinked = true;
2162         // Add ungrouped items to the new selection.
2163         new_select = g_slist_prepend(new_select, unlink);
2164     }
2166     if (new_select) { // set new selection
2167         selection->clear();
2168         selection->setList(new_select);
2169         g_slist_free(new_select);
2170     }
2171     if (!unlinked) {
2172         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2173     }
2175     SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2176                      _("Unlink clone"));
2179 void
2180 sp_select_clone_original(SPDesktop *desktop)
2182     if (desktop == NULL)
2183         return;
2185     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2187     SPItem *item = selection->singleItem();
2189     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.");
2191     // Check if other than two objects are selected
2192     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2193         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2194         return;
2195     }
2197     SPItem *original = NULL;
2198     if (SP_IS_USE(item)) {
2199         original = sp_use_get_original(SP_USE(item));
2200     } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2201         original = sp_offset_get_source(SP_OFFSET(item));
2202     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2203         original = sp_textpath_get_path_item(SP_TEXTPATH(SP_OBJECT(item)->first_child()));
2204     } else if (SP_IS_FLOWTEXT(item)) {
2205         original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2206     } else { // it's an object that we don't know what to do with
2207         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2208         return;
2209     }
2211     if (!original) {
2212         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2213         return;
2214     }
2216     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2217         if (SP_IS_DEFS(o)) {
2218             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2219             return;
2220         }
2221     }
2223     if (original) {
2224         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2225         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2226         if (highlight) {
2227             Geom::OptRect a = item->getBounds(item->i2d_affine());
2228             Geom::OptRect b = original->getBounds(original->i2d_affine());
2229             if ( a && b ) {
2230                 // draw a flashing line between the objects
2231                 SPCurve *curve = new SPCurve();
2232                 curve->moveto(a->midpoint());
2233                 curve->lineto(b->midpoint());
2235                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2236                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2237                 sp_canvas_item_show(canvasitem);
2238                 curve->unref();
2239                 desktop->add_temporary_canvasitem(canvasitem, 1000);
2240             }
2241         }
2243         selection->clear();
2244         selection->set(original);
2245         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2246             scroll_to_show_item(desktop, original);
2247         }
2248     }
2252 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2254     if (desktop == NULL)
2255         return;
2257     SPDocument *doc = sp_desktop_document(desktop);
2258     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2260     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2262     // check if something is selected
2263     if (selection->isEmpty()) {
2264         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2265         return;
2266     }
2268     doc->ensure_up_to_date();
2269     Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2270     boost::optional<Geom::Point> c = selection->center();
2271     if ( !r || !c ) {
2272         return;
2273     }
2275     // calculate the transform to be applied to objects to move them to 0,0
2276     Geom::Point move_p = Geom::Point(0, doc->getHeight()) - *c;
2277     move_p[Geom::Y] = -move_p[Geom::Y];
2278     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2280     GSList *items = g_slist_copy((GSList *) selection->itemList());
2282     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2284     // bottommost object, after sorting
2285     SPObject *parent = SP_OBJECT_PARENT(items->data);
2287     Geom::Matrix parent_transform(SP_ITEM(parent)->i2doc_affine());
2289     // remember the position of the first item
2290     gint pos = SP_OBJECT_REPR(items->data)->position();
2291     (void)pos; // TODO check why this was remembered
2293     // create a list of duplicates
2294     GSList *repr_copies = NULL;
2295     for (GSList *i = items; i != NULL; i = i->next) {
2296         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2297         repr_copies = g_slist_prepend(repr_copies, dup);
2298     }
2300     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2302     if (apply) {
2303         // delete objects so that their clones don't get alerted; this object will be restored shortly
2304         for (GSList *i = items; i != NULL; i = i->next) {
2305             SPObject *item = SP_OBJECT(i->data);
2306             item->deleteObject(false);
2307         }
2308     }
2310     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2311     // without disturbing clones.
2312     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2313     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2314     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2315     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2317     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2318                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2319                                                                               Geom::Point(r->min()[Geom::X],
2320                                                                                           r->max()[Geom::Y]))))
2321                                              * parent_transform.inverse() ),
2322                                            parent_transform * move);
2323     (void)mark_id;
2325     // restore compensation setting
2326     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2329     g_slist_free(items);
2331     SPDocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2332                      _("Objects to marker"));
2335 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2336     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2337         for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2338             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2339         }
2340     } else {
2341         item->convert_item_to_guides();
2343         if (deleteitem) {
2344             SP_OBJECT(item)->deleteObject(true);
2345         }
2346     }
2349 void sp_selection_to_guides(SPDesktop *desktop)
2351     if (desktop == NULL)
2352         return;
2354     SPDocument *doc = sp_desktop_document(desktop);
2355     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2356     // we need to copy the list because it gets reset when objects are deleted
2357     GSList *items = g_slist_copy((GSList *) selection->itemList());
2359     if (!items) {
2360         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2361         return;
2362     }
2364     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2365     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2366     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2368     for (GSList const *i = items; i != NULL; i = i->next) {
2369         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2370     }
2372     SPDocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2375 void
2376 sp_selection_tile(SPDesktop *desktop, bool apply)
2378     if (desktop == NULL)
2379         return;
2381     SPDocument *doc = sp_desktop_document(desktop);
2382     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2384     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2386     // check if something is selected
2387     if (selection->isEmpty()) {
2388         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2389         return;
2390     }
2392     doc->ensure_up_to_date();
2393     Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2394     if ( !r ) {
2395         return;
2396     }
2398     // calculate the transform to be applied to objects to move them to 0,0
2399     Geom::Point move_p = Geom::Point(0, doc->getHeight()) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2400     move_p[Geom::Y] = -move_p[Geom::Y];
2401     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2403     GSList *items = g_slist_copy((GSList *) selection->itemList());
2405     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2407     // bottommost object, after sorting
2408     SPObject *parent = SP_OBJECT_PARENT(items->data);
2410     Geom::Matrix parent_transform(SP_ITEM(parent)->i2doc_affine());
2412     // remember the position of the first item
2413     gint pos = SP_OBJECT_REPR(items->data)->position();
2415     // create a list of duplicates
2416     GSList *repr_copies = NULL;
2417     for (GSList *i = items; i != NULL; i = i->next) {
2418         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2419         repr_copies = g_slist_prepend(repr_copies, dup);
2420     }
2421     // restore the z-order after prepends
2422     repr_copies = g_slist_reverse(repr_copies);
2424     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2426     if (apply) {
2427         // delete objects so that their clones don't get alerted; this object will be restored shortly
2428         for (GSList *i = items; i != NULL; i = i->next) {
2429             SPObject *item = SP_OBJECT(i->data);
2430             item->deleteObject(false);
2431         }
2432     }
2434     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2435     // without disturbing clones.
2436     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2437     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2438     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2439     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2441     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2442                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2443                                                                                             r->max()[Geom::Y]))))
2444                                          * to_2geom(parent_transform.inverse()) ),
2445                                        parent_transform * move);
2447     // restore compensation setting
2448     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2450     if (apply) {
2451         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2452         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2454         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2455         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2457         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2458         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2459         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2460         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2462         // restore parent and position
2463         SP_OBJECT_REPR(parent)->appendChild(rect);
2464         rect->setPosition(pos > 0 ? pos : 0);
2465         SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2467         Inkscape::GC::release(rect);
2469         selection->clear();
2470         selection->set(rectangle);
2471     }
2473     g_slist_free(items);
2475     SPDocumentUndo::done(doc, SP_VERB_EDIT_TILE,
2476                      _("Objects to pattern"));
2479 void
2480 sp_selection_untile(SPDesktop *desktop)
2482     if (desktop == NULL)
2483         return;
2485     SPDocument *doc = sp_desktop_document(desktop);
2486     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2488     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2490     // check if something is selected
2491     if (selection->isEmpty()) {
2492         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2493         return;
2494     }
2496     GSList *new_select = NULL;
2498     bool did = false;
2500     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2501          items != NULL;
2502          items = items->next) {
2504         SPItem *item = (SPItem *) items->data;
2506         SPStyle *style = SP_OBJECT_STYLE(item);
2508         if (!style || !style->fill.isPaintserver())
2509             continue;
2511         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2513         if (!SP_IS_PATTERN(server))
2514             continue;
2516         did = true;
2518         SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2520         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2521         pat_transform *= item->transform;
2523         for (SPObject *child = SP_OBJECT(pattern)->first_child() ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2524             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2525             SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2527            // FIXME: relink clones to the new canvas objects
2528            // use SPObject::setid when mental finishes it to steal ids of
2530             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2531             doc->ensure_up_to_date();
2533             Geom::Matrix transform( i->transform * pat_transform );
2534             i->doWriteTransform(SP_OBJECT_REPR(i), transform);
2536             new_select = g_slist_prepend(new_select, i);
2537         }
2539         SPCSSAttr *css = sp_repr_css_attr_new();
2540         sp_repr_css_set_property(css, "fill", "none");
2541         sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2542     }
2544     if (!did) {
2545         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2546     } else {
2547         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2548                          _("Pattern to objects"));
2549         selection->setList(new_select);
2550     }
2553 void
2554 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2556     if (selection->isEmpty()) {
2557         return;
2558     }
2560     GSList const *reprlst = selection->reprList();
2561     bool filename_search = TRUE;
2562     bool xdpi_search = TRUE;
2563     bool ydpi_search = TRUE;
2565     for (; reprlst != NULL &&
2566             filename_search &&
2567             xdpi_search &&
2568             ydpi_search;
2569         reprlst = reprlst->next) {
2570         gchar const *dpi_string;
2571         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2573         if (filename_search) {
2574             *filename = repr->attribute("inkscape:export-filename");
2575             if (*filename != NULL)
2576                 filename_search = FALSE;
2577         }
2579         if (xdpi_search) {
2580             dpi_string = NULL;
2581             dpi_string = repr->attribute("inkscape:export-xdpi");
2582             if (dpi_string != NULL) {
2583                 *xdpi = atof(dpi_string);
2584                 xdpi_search = FALSE;
2585             }
2586         }
2588         if (ydpi_search) {
2589             dpi_string = NULL;
2590             dpi_string = repr->attribute("inkscape:export-ydpi");
2591             if (dpi_string != NULL) {
2592                 *ydpi = atof(dpi_string);
2593                 ydpi_search = FALSE;
2594             }
2595         }
2596     }
2599 void
2600 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2602     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2603     gchar const *dpi_string;
2605     *filename = repr->attribute("inkscape:export-filename");
2607     dpi_string = NULL;
2608     dpi_string = repr->attribute("inkscape:export-xdpi");
2609     if (dpi_string != NULL) {
2610         *xdpi = atof(dpi_string);
2611     }
2613     dpi_string = NULL;
2614     dpi_string = repr->attribute("inkscape:export-ydpi");
2615     if (dpi_string != NULL) {
2616         *ydpi = atof(dpi_string);
2617     }
2620 void
2621 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2623     if (desktop == NULL)
2624         return;
2626     SPDocument *document = sp_desktop_document(desktop);
2627     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2629     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2631     // check if something is selected
2632     if (selection->isEmpty()) {
2633         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2634         return;
2635     }
2637     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2638     // set "busy" cursor
2639     desktop->setWaitingCursor();
2641     // Get the bounding box of the selection
2642     NRRect bbox;
2643     document->ensure_up_to_date();
2644     selection->bounds(&bbox);
2645     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2646         desktop->clearWaitingCursor();
2647         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2648     }
2650     // List of the items to show; all others will be hidden
2651     GSList *items = g_slist_copy((GSList *) selection->itemList());
2653     // Sort items so that the topmost comes last
2654     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2656     // Generate a random value from the current time (you may create bitmap from the same object(s)
2657     // multiple times, and this is done so that they don't clash)
2658     GTimeVal cu;
2659     g_get_current_time(&cu);
2660     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2662     // Create the filename.
2663     gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2664                                             document->name,
2665                                             SP_OBJECT_REPR(items->data)->attribute("id"),
2666                                             current);
2667     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2668     // digits, and a few other chars, with "_"
2669     g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2671     // Build the complete path by adding document base dir, if set, otherwise home dir
2672     gchar * directory = NULL;
2673     if (SP_DOCUMENT_URI(document)) {
2674         directory = g_dirname(SP_DOCUMENT_URI(document));
2675     }
2676     if (directory == NULL) {
2677         directory = homedir_path(NULL);
2678     }
2679     gchar *filepath = g_build_filename(directory, basename, NULL);
2681     //g_print("%s\n", filepath);
2683     // Remember parent and z-order of the topmost one
2684     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2685     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2686     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2688     // Calculate resolution
2689     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2690     double res;
2691     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2692     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2693     if (0 < prefs_res) {
2694         // If it's given explicitly in prefs, take it
2695         res = prefs_res;
2696     } else if (0 < prefs_min) {
2697         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2698         res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2699     } else {
2700         float hint_xdpi = 0, hint_ydpi = 0;
2701         char const *hint_filename;
2702         // take resolution hint from the selected objects
2703         sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2704         if (hint_xdpi != 0) {
2705             res = hint_xdpi;
2706         } else {
2707             // take resolution hint from the document
2708             sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2709             if (hint_xdpi != 0) {
2710                 res = hint_xdpi;
2711             } else {
2712                 // if all else fails, take the default 90 dpi
2713                 res = PX_PER_IN;
2714             }
2715         }
2716     }
2718     // The width and height of the bitmap in pixels
2719     unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2720     unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2722     // Find out if we have to run an external filter
2723     gchar const *run = NULL;
2724     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2725     if (!filter.empty()) {
2726         // filter command is given;
2727         // see if we have a parameter to pass to it
2728         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2729         if (!param1.empty()) {
2730             if (param1[param1.length() - 1] == '%') {
2731                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2732                 gchar p1[256];
2733                 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2734                 // the first param is always the image filename, the second is param1
2735                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2736             } else {
2737                 // otherwise pass the param1 unchanged
2738                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2739             }
2740         } else {
2741             // run without extra parameter
2742             run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2743         }
2744     }
2746     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2747     Geom::Matrix eek(SP_ITEM(parent_object)->i2d_affine());
2748     Geom::Matrix t;
2750     double shift_x = bbox.x0;
2751     double shift_y = bbox.y1;
2752     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2753         shift_x = round(shift_x);
2754         shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2755     }
2756     t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2758     // Do the export
2759     sp_export_png_file(document, filepath,
2760                        bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2761                        width, height, res, res,
2762                        (guint32) 0xffffff00,
2763                        NULL, NULL,
2764                        true,  /*bool force_overwrite,*/
2765                        items);
2767     g_slist_free(items);
2769     // Run filter, if any
2770     if (run) {
2771         g_print("Running external filter: %s\n", run);
2772         int retval;
2773         retval = system(run);
2774     }
2776     // Import the image back
2777     GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2778     if (pb) {
2779         // Create the repr for the image
2780         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2781         sp_embed_image(repr, pb, "image/png");
2782         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2783             sp_repr_set_svg_double(repr, "width", width);
2784             sp_repr_set_svg_double(repr, "height", height);
2785         } else {
2786             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2787             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2788         }
2790         // Write transform
2791         gchar *c=sp_svg_transform_write(t);
2792         repr->setAttribute("transform", c);
2793         g_free(c);
2795         // add the new repr to the parent
2796         parent->appendChild(repr);
2798         // move to the saved position
2799         repr->setPosition(pos > 0 ? pos + 1 : 1);
2801         // Set selection to the new image
2802         selection->clear();
2803         selection->add(repr);
2805         // Clean up
2806         Inkscape::GC::release(repr);
2807         gdk_pixbuf_unref(pb);
2809         // Complete undoable transaction
2810         SPDocumentUndo::done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2811                          _("Create bitmap"));
2812     }
2814     desktop->clearWaitingCursor();
2816     g_free(basename);
2817     g_free(filepath);
2820 /**
2821  * \brief Creates a mask or clipPath from selection
2822  * Two different modes:
2823  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2824  *       and is applied to current layer
2825  *  otherwise, topmost object is used as mask for other objects
2826  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2827  *
2828  */
2829 void
2830 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2832     if (desktop == NULL)
2833         return;
2835     SPDocument *doc = sp_desktop_document(desktop);
2836     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2838     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2840     // check if something is selected
2841     bool is_empty = selection->isEmpty();
2842     if ( apply_to_layer && is_empty) {
2843         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2844         return;
2845     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2846         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2847         return;
2848     }
2850     // FIXME: temporary patch to prevent crash!
2851     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2852     bool clone_with_original = selection_contains_both_clone_and_original(selection);
2853     if (clone_with_original) {
2854         return; // in this version, you cannot clip/mask an object with its own clone
2855     }
2856     // /END FIXME
2858     doc->ensure_up_to_date();
2860     GSList *items = g_slist_copy((GSList *) selection->itemList());
2862     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2863     
2864     // See lp bug #542004
2865     selection->clear();
2867     // create a list of duplicates
2868     GSList *mask_items = NULL;
2869     GSList *apply_to_items = NULL;
2870     GSList *items_to_delete = NULL;
2871     GSList *items_to_select = NULL;
2872     
2873     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2874     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2875     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2876     int grouping = prefs->getInt("/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE);
2878     if (apply_to_layer) {
2879         // all selected items are used for mask, which is applied to a layer
2880         apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2881         
2882         for (GSList *i = items; i != NULL; i = i->next) {
2883             Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2884             mask_items = g_slist_prepend(mask_items, dup);
2886             SPObject *item = SP_OBJECT(i->data);
2887             if (remove_original) {                
2888                 items_to_delete = g_slist_prepend(items_to_delete, item);
2889             }
2890             else {
2891                 items_to_select = g_slist_prepend(items_to_select, item);
2892             }
2893         }
2894     } else if (!topmost) {
2895         // topmost item is used as a mask, which is applied to other items in a selection
2896         GSList *i = items;
2897         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2898         mask_items = g_slist_prepend(mask_items, dup);
2900         if (remove_original) {
2901             SPObject *item = SP_OBJECT(i->data);
2902             items_to_delete = g_slist_prepend(items_to_delete, item);
2903         }
2905         for (i = i->next; i != NULL; i = i->next) {
2906             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2907             items_to_select = g_slist_prepend(items_to_select, i->data);
2908         }
2909     } else {
2910         GSList *i = NULL;
2911         for (i = items; NULL != i->next; i = i->next) {
2912             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2913             items_to_select = g_slist_prepend(items_to_select, i->data);
2914         }
2916         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2917         mask_items = g_slist_prepend(mask_items, dup);
2919         if (remove_original) {
2920             SPObject *item = SP_OBJECT(i->data);
2921             items_to_delete = g_slist_prepend(items_to_delete, item);
2922         }
2923     }
2925     g_slist_free(items);
2926     items = NULL;
2928     if (apply_to_items && grouping == PREFS_MASKOBJECT_GROUPING_ALL) {
2929         // group all those objects into one group
2930         // and apply mask to that
2931         Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2933         // make a note we should ungroup this when unsetting mask
2934         group->setAttribute("inkscape:groupmode", "maskhelper");
2936         GSList *reprs_to_group = NULL;
2938         for (GSList *i = apply_to_items ; NULL != i ; i = i->next) {
2939                 reprs_to_group = g_slist_prepend(reprs_to_group, SP_OBJECT_REPR(i->data));
2940                 items_to_select = g_slist_remove(items_to_select, i->data);
2941         }
2942         reprs_to_group = g_slist_reverse(reprs_to_group);
2944         sp_selection_group_impl(reprs_to_group, group, xml_doc, doc);
2945         
2946         reprs_to_group = NULL;
2948         // apply clip/mask only to newly created group
2949         g_slist_free(apply_to_items);
2950         apply_to_items = NULL;
2951         apply_to_items = g_slist_prepend(apply_to_items, doc->getObjectByRepr(group));
2953         items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
2955         Inkscape::GC::release(group);
2956     }
2958     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2959     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2960         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2961         // inverted object transform should be applied to a mask object,
2962         // as mask is calculated in user space (after applying transform)
2963         Geom::Matrix maskTransform(item->transform.inverse());
2965         GSList *mask_items_dup = NULL;
2966         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2967             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2968             mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2969         }
2971         gchar const *mask_id = NULL;
2972         if (apply_clip_path) {
2973             mask_id = SPClipPath::create(mask_items_dup, doc, &maskTransform);
2974         } else {
2975             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2976         }
2978         g_slist_free(mask_items_dup);
2979         mask_items_dup = NULL;
2981         Inkscape::XML::Node *current = SP_OBJECT_REPR(i->data);
2982         // Node to apply mask to
2983         Inkscape::XML::Node *apply_mask_to = current;
2985         if (grouping == PREFS_MASKOBJECT_GROUPING_SEPARATE) {
2986             // enclose current node in group, and apply crop/mask on that
2987             Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2988             // make a note we should ungroup this when unsetting mask
2989             group->setAttribute("inkscape:groupmode", "maskhelper");
2991             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
2992             gint position = current->position();
2993             items_to_select = g_slist_remove(items_to_select, item);
2994             current->parent()->appendChild(group);
2995             sp_repr_unparent(current);
2996             group->appendChild(spnew);
2997             group->setPosition(position);
2999             // Apply clip/mask to group instead
3000             apply_mask_to = group;
3002             items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
3003             Inkscape::GC::release(spnew);
3004             Inkscape::GC::release(group);
3005         }
3007         apply_mask_to->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3009     }
3011     g_slist_free(mask_items);
3012     g_slist_free(apply_to_items);
3014     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3015         SPObject *item = SP_OBJECT(i->data);
3016         item->deleteObject(false);
3017         items_to_select = g_slist_remove(items_to_select, item);
3018     }
3019     g_slist_free(items_to_delete);
3020     
3021     items_to_select = g_slist_reverse(items_to_select);
3022     
3023     selection->addList(items_to_select);
3024     g_slist_free(items_to_select);
3026     if (apply_clip_path)
3027         SPDocumentUndo::done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3028     else
3029         SPDocumentUndo::done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3032 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
3033     if (desktop == NULL)
3034         return;
3036     SPDocument *doc = sp_desktop_document(desktop);
3037     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3038     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3040     // check if something is selected
3041     if (selection->isEmpty()) {
3042         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3043         return;
3044     }
3046     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
3047     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
3048     bool ungroup_masked = prefs->getBool("/options/maskobject/ungrouping", true);
3049     doc->ensure_up_to_date();
3051     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3052     std::map<SPObject*,SPItem*> referenced_objects;
3054     GSList *items = g_slist_copy((GSList *) selection->itemList());
3055     selection->clear();
3056     
3057     GSList *items_to_ungroup = NULL;
3058     GSList *items_to_select = g_slist_copy(items);
3059     items_to_select = g_slist_reverse(items_to_select);    
3060         
3062     // SPObject* refers to a group containing the clipped path or mask itself,
3063     // whereas SPItem* refers to the item being clipped or masked
3064     for (GSList const *i = items; NULL != i; i = i->next) {
3065         if (remove_original) {
3066             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3067             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3068             Inkscape::URIReference *uri_ref = NULL;
3070             if (apply_clip_path) {
3071                 uri_ref = item->clip_ref;
3072             } else {
3073                 uri_ref = item->mask_ref;
3074             }
3076             // collect distinct mask object (and associate with item to apply transform)
3077             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3078                 referenced_objects[uri_ref->getObject()] = item;
3079             }
3080         }
3082         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3084         if (ungroup_masked && SP_IS_GROUP(i->data)) {
3085                 // if we had previously enclosed masked object in group,
3086                 // add it to list so we can ungroup it later
3087                 SPGroup *item = SP_GROUP(i->data);
3089                 // ungroup only groups we created when setting clip/mask
3090                 if (item->layerMode() == SPGroup::MASK_HELPER) {
3091                     items_to_ungroup = g_slist_prepend(items_to_ungroup, item);
3092                 }
3094         }
3095     }
3096     g_slist_free(items);
3098     // restore mask objects into a document
3099     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3100         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
3101         GSList *items_to_move = NULL;
3102         for (SPObject *child = obj->first_child() ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3103             // Collect all clipped paths and masks within a single group
3104             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3105             items_to_move = g_slist_prepend(items_to_move, copy);
3106         }
3108         if (!obj->isReferenced()) {
3109             // delete from defs if no other object references this mask
3110             obj->deleteObject(false);
3111         }
3113         // remember parent and position of the item to which the clippath/mask was applied
3114         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3115         gint pos = SP_OBJECT_REPR((*it).second)->position();
3117         // Iterate through all clipped paths / masks
3118         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3119             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3121             // insert into parent, restore pos
3122             parent->appendChild(repr);
3123             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3125             SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3126             items_to_select = g_slist_prepend(items_to_select, mask_item);
3128             // transform mask, so it is moved the same spot where mask was applied
3129             Geom::Matrix transform(mask_item->transform);
3130             transform *= (*it).second->transform;
3131             mask_item->doWriteTransform(SP_OBJECT_REPR(mask_item), transform);
3132         }
3134         g_slist_free(items_to_move);
3135     }
3137     // ungroup marked groups added when setting mask
3138     for (GSList *i = items_to_ungroup ; NULL != i ; i = i->next) {
3139         items_to_select = g_slist_remove(items_to_select, SP_GROUP(i->data));
3140         GSList *children = NULL;
3141         sp_item_group_ungroup(SP_GROUP(i->data), &children, false);
3142         items_to_select = g_slist_concat(children, items_to_select);
3143     }
3145     g_slist_free(items_to_ungroup);
3146     
3147     // rebuild selection
3148     items_to_select = g_slist_reverse(items_to_select);
3149     selection->addList(items_to_select);
3150     g_slist_free(items_to_select);
3152     if (apply_clip_path)
3153         SPDocumentUndo::done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3154     else
3155         SPDocumentUndo::done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3158 /**
3159  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3160  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3161  * \return true if an undoable change should be recorded.
3162  */
3163 bool
3164 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3166     g_return_val_if_fail(desktop != NULL, false);
3167     SPDocument *doc = sp_desktop_document(desktop);
3169     g_return_val_if_fail(doc != NULL, false);
3170     g_return_val_if_fail(desktop->selection != NULL, false);
3172     if (desktop->selection->isEmpty()) {
3173         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3174         return false;
3175     }
3176     Geom::OptRect const bbox(desktop->selection->bounds(SPItem::RENDERING_BBOX));
3177     if (bbox) {
3178         doc->fitToRect(*bbox, with_margins);
3179         return true;
3180     } else {
3181         return false;
3182     }
3185 /**
3186  * Fit canvas to the bounding box of the selection, as an undoable action.
3187  */
3188 void
3189 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3191     if (fit_canvas_to_selection(desktop)) {
3192         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3193                          _("Fit Page to Selection"));
3194     }
3197 /**
3198  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3199  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3200  */
3201 bool
3202 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3204     g_return_val_if_fail(doc != NULL, false);
3206     doc->ensure_up_to_date();
3207     SPItem const *const root = SP_ITEM(doc->root);
3208     Geom::OptRect const bbox(root->getBounds(root->i2d_affine()));
3209     if (bbox) {
3210         doc->fitToRect(*bbox, with_margins);
3211         return true;
3212     } else {
3213         return false;
3214     }
3217 void
3218 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3220     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3221         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3222                          _("Fit Page to Drawing"));
3223     }
3226 /**
3227  * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3228  * "fit-margin-..." attributes.  See SPDocument::fitToRect and
3229  * ui/dialog/page-sizer.
3230  */
3231 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3232     g_return_if_fail(desktop != NULL);
3233     SPDocument *doc = sp_desktop_document(desktop);
3235     g_return_if_fail(doc != NULL);
3236     g_return_if_fail(desktop->selection != NULL);
3238     bool const changed = ( desktop->selection->isEmpty()
3239                            ? fit_canvas_to_drawing(doc, true)
3240                            : fit_canvas_to_selection(desktop, true) );
3241     if (changed) {
3242         SPDocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3243                          _("Fit Page to Selection or Drawing"));
3244     }
3245 };
3247 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3248     // don't operate on layers
3249     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3250         f(SP_ITEM(root), desktop);
3251     }
3252     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3253         //don't recurse into locked layers
3254         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3255             itemtree_map(f, iter, desktop);
3256         }
3257     }
3260 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3261     if (item->isLocked()) {
3262         item->setLocked(FALSE);
3263     }
3266 static void unhide(SPItem *item, SPDesktop *desktop) {
3267     if (desktop->itemIsHidden(item)) {
3268         item->setExplicitlyHidden(FALSE);
3269     }
3272 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3273     if (!dt) return;
3275     SPObject *root;
3276     if (layer_only) {
3277         root = dt->currentLayer();
3278     } else {
3279         root = dt->currentRoot();
3280     }
3282     itemtree_map(f, root, dt);
3285 void unlock_all(SPDesktop *dt) {
3286     process_all(&unlock, dt, true);
3289 void unlock_all_in_all_layers(SPDesktop *dt) {
3290     process_all(&unlock, dt, false);
3293 void unhide_all(SPDesktop *dt) {
3294     process_all(&unhide, dt, true);
3297 void unhide_all_in_all_layers(SPDesktop *dt) {
3298     process_all(&unhide, dt, false);
3302 /*
3303   Local Variables:
3304   mode:c++
3305   c-file-style:"stroustrup"
3306   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3307   indent-tabs-mode:nil
3308   fill-column:99
3309   End:
3310 */
3311 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :