Code

Patch by Martin Sucha to add preferences to for grouping on Clip/Mask
[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  *
12  * Copyright (C) 1999-2010 authors
13  * Copyright (C) 2001-2002 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
22 #include "selection-chemistry.h"
24 // TOOD fixme: This should be moved into preference repr
25 SPCycleType SP_CYCLING = SP_CYCLE_FOCUS;
28 #include <gtkmm/clipboard.h>
30 #include "svg/svg.h"
31 #include "desktop.h"
32 #include "desktop-style.h"
33 #include "dir-util.h"
34 #include "selection.h"
35 #include "tools-switch.h"
36 #include "desktop-handles.h"
37 #include "message-stack.h"
38 #include "sp-item-transform.h"
39 #include "marker.h"
40 #include "sp-use.h"
41 #include "sp-textpath.h"
42 #include "sp-tspan.h"
43 #include "sp-tref.h"
44 #include "sp-flowtext.h"
45 #include "sp-flowregion.h"
46 #include "text-editing.h"
47 #include "text-context.h"
48 #include "connector-context.h"
49 #include "sp-path.h"
50 #include "sp-conn-end.h"
51 #include "dropper-context.h"
52 #include <glibmm/i18n.h>
53 #include "libnr/nr-matrix-rotate-ops.h"
54 #include "libnr/nr-matrix-translate-ops.h"
55 #include "libnr/nr-scale-ops.h"
56 #include <libnr/nr-matrix-ops.h>
57 #include <2geom/transforms.h>
58 #include "xml/repr.h"
59 #include "xml/rebase-hrefs.h"
60 #include "style.h"
61 #include "document-private.h"
62 #include "sp-gradient.h"
63 #include "sp-gradient-reference.h"
64 #include "sp-linear-gradient-fns.h"
65 #include "sp-pattern.h"
66 #include "sp-radial-gradient-fns.h"
67 #include "gradient-context.h"
68 #include "sp-namedview.h"
69 #include "preferences.h"
70 #include "sp-offset.h"
71 #include "sp-clippath.h"
72 #include "sp-mask.h"
73 #include "file.h"
74 #include "helper/png-write.h"
75 #include "layer-fns.h"
76 #include "context-fns.h"
77 #include <map>
78 #include <cstring>
79 #include <string>
80 #include "helper/units.h"
81 #include "sp-item.h"
82 #include "box3d.h"
83 #include "persp3d.h"
84 #include "unit-constants.h"
85 #include "xml/simple-document.h"
86 #include "sp-filter-reference.h"
87 #include "gradient-drag.h"
88 #include "uri-references.h"
89 #include "libnr/nr-convert2geom.h"
90 #include "display/curve.h"
91 #include "display/canvas-bpath.h"
92 #include "inkscape-private.h"
93 #include "path-chemistry.h"
94 #include "ui/tool/control-point-selection.h"
95 #include "ui/tool/multi-path-manipulator.h"
97 #include "enums.h"
98 #include "sp-item-group.h"
100 // For clippath editing
101 #include "tools-switch.h"
102 #include "ui/tool/node-tool.h"
104 #include "ui/clipboard.h"
106 using Geom::X;
107 using Geom::Y;
109 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
110 because the layer manipulation code uses them. It should be rewritten specifically
111 for that purpose. */
115 namespace Inkscape {
117 void SelectionHelper::selectAll(SPDesktop *dt)
119     if (tools_isactive(dt, TOOLS_NODES)) {
120         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
121         nt->_multipath->selectSubpaths();
122     } else {
123         sp_edit_select_all(dt);
124     }
127 void SelectionHelper::selectAllInAll(SPDesktop *dt)
129     if (tools_isactive(dt, TOOLS_NODES)) {
130         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
131         nt->_selected_nodes->selectAll();
132     } else {
133         sp_edit_select_all_in_all_layers(dt);
134     }
137 void SelectionHelper::selectNone(SPDesktop *dt)
139     if (tools_isactive(dt, TOOLS_NODES)) {
140         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
141         nt->_selected_nodes->clear();
142     } else {
143         sp_desktop_selection(dt)->clear();
144     }
147 void SelectionHelper::invert(SPDesktop *dt)
149     if (tools_isactive(dt, TOOLS_NODES)) {
150         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
151         nt->_multipath->invertSelectionInSubpaths();
152     } else {
153         sp_edit_invert(dt);
154     }
157 void SelectionHelper::invertAllInAll(SPDesktop *dt)
159     if (tools_isactive(dt, TOOLS_NODES)) {
160         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
161         nt->_selected_nodes->invertSelection();
162     } else {
163         sp_edit_invert_in_all_layers(dt);
164     }
167 void SelectionHelper::reverse(SPDesktop *dt)
169     // TODO make this a virtual method of event context!
170     if (tools_isactive(dt, TOOLS_NODES)) {
171         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
172         nt->_multipath->reverseSubpaths();
173     } else {
174         sp_selected_path_reverse(dt);
175     }
178 void SelectionHelper::selectNext(SPDesktop *dt)
180     SPEventContext *ec = dt->event_context;
181     if (tools_isactive(dt, TOOLS_NODES)) {
182         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
183         nt->_multipath->shiftSelection(1);
184     } else if (tools_isactive(dt, TOOLS_GRADIENT)
185                && ec->_grdrag->isNonEmpty()) {
186         sp_gradient_context_select_next(ec);
187     } else {
188         sp_selection_item_next(dt);
189     }
192 void SelectionHelper::selectPrev(SPDesktop *dt)
194     SPEventContext *ec = dt->event_context;
195     if (tools_isactive(dt, TOOLS_NODES)) {
196         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
197         nt->_multipath->shiftSelection(-1);
198     } else if (tools_isactive(dt, TOOLS_GRADIENT)
199                && ec->_grdrag->isNonEmpty()) {
200         sp_gradient_context_select_prev(ec);
201     } else {
202         sp_selection_item_prev(dt);
203     }
206 } // namespace Inkscape
209 /**
210  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
211  * then prepends the copy to 'clip'.
212  */
213 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
215     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
217     // copy complete inherited style
218     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
219     sp_repr_css_set(copy, css, "style");
220     sp_repr_css_attr_unref(css);
222     // write the complete accumulated transform passed to us
223     // (we're dealing with unattached repr, so we write to its attr
224     // instead of using sp_item_set_transform)
225     gchar *affinestr=sp_svg_transform_write(full_t);
226     copy->setAttribute("transform", affinestr);
227     g_free(affinestr);
229     *clip = g_slist_prepend(*clip, copy);
232 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
234     // Sort items:
235     GSList *sorted_items = g_slist_copy((GSList *) items);
236     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
238     // Copy item reprs:
239     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
240         sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
241     }
243     *clip = g_slist_reverse(*clip);
244     g_slist_free((GSList *) sorted_items);
247 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
249     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
251     GSList *copied = NULL;
252     // add objects to document
253     for (GSList *l = *clip; l != NULL; l = l->next) {
254         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
255         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
257         // premultiply the item transform by the accumulated parent transform in the paste layer
258         Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
259         if (!local.isIdentity()) {
260             gchar const *t_str = copy->attribute("transform");
261             Geom::Matrix item_t(Geom::identity());
262             if (t_str)
263                 sp_svg_transform_read(t_str, &item_t);
264             item_t *= local.inverse();
265             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
266             gchar *affinestr=sp_svg_transform_write(item_t);
267             copy->setAttribute("transform", affinestr);
268             g_free(affinestr);
269         }
271         parent->appendChildRepr(copy);
272         copied = g_slist_prepend(copied, copy);
273         Inkscape::GC::release(copy);
274     }
275     return copied;
278 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
280     for (GSList const *i = items ; i ; i = i->next ) {
281         sp_object_ref((SPObject *)i->data, NULL);
282     }
283     for (GSList const *i = items; i != NULL; i = i->next) {
284         SPItem *item = (SPItem *) i->data;
285         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
286         sp_object_unref((SPObject *)item, NULL);
287     }
291 void sp_selection_delete(SPDesktop *desktop)
293     if (desktop == NULL) {
294         return;
295     }
297     if (tools_isactive(desktop, TOOLS_TEXT))
298         if (sp_text_delete_selection(desktop->event_context)) {
299             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
300                              _("Delete text"));
301             return;
302         }
304     Inkscape::Selection *selection = sp_desktop_selection(desktop);
306     // check if something is selected
307     if (selection->isEmpty()) {
308         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
309         return;
310     }
312     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
313     selection->clear();
314     sp_selection_delete_impl(selected);
315     g_slist_free((GSList *) selected);
317     /* a tool may have set up private information in it's selection context
318      * that depends on desktop items.  I think the only sane way to deal with
319      * this currently is to reset the current tool, which will reset it's
320      * associated selection context.  For example: deleting an object
321      * while moving it around the canvas.
322      */
323     tools_switch( desktop, tools_active( desktop ) );
325     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
326                      _("Delete"));
329 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
331     if (!obj)
332         return;
334     ids.push_back(SP_OBJECT_ID(obj));
336     if (SP_IS_GROUP(obj)) {
337         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
338             add_ids_recursive(ids, child);
339         }
340     }
343 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
345     if (desktop == NULL)
346         return;
348     SPDocument *doc = desktop->doc();
349     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
350     Inkscape::Selection *selection = sp_desktop_selection(desktop);
352     // check if something is selected
353     if (selection->isEmpty()) {
354         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
355         return;
356     }
358     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
360     selection->clear();
362     // sorting items from different parents sorts each parent's subset without possibly mixing
363     // them, just what we need
364     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
366     GSList *newsel = NULL;
368     std::vector<const gchar *> old_ids;
369     std::vector<const gchar *> new_ids;
370     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
371     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
373     while (reprs) {
374         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
375         Inkscape::XML::Node *parent = old_repr->parent();
376         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
378         parent->appendChild(copy);
380         if (relink_clones) {
381             SPObject *old_obj = doc->getObjectByRepr(old_repr);
382             SPObject *new_obj = doc->getObjectByRepr(copy);
383             add_ids_recursive(old_ids, old_obj);
384             add_ids_recursive(new_ids, new_obj);
385         }
387         newsel = g_slist_prepend(newsel, copy);
388         reprs = g_slist_remove(reprs, reprs->data);
389         Inkscape::GC::release(copy);
390     }
392     if (relink_clones) {
394         g_assert(old_ids.size() == new_ids.size());
396         for (unsigned int i = 0; i < old_ids.size(); i++) {
397             const gchar *id = old_ids[i];
398             SPObject *old_clone = doc->getObjectById(id);
399             if (SP_IS_USE(old_clone)) {
400                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
401                 if (!orig) // orphaned
402                     continue;
403                 for (unsigned int j = 0; j < old_ids.size(); j++) {
404                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
405                         // we have both orig and clone in selection, relink
406                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
407                         gchar *newref = g_strdup_printf("#%s", new_ids[j]);
408                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
409                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
410                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
411                         g_free(newref);
412                     }
413                 }
414             }
415         }
416     }
419     if ( !suppressDone ) {
420         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
421                          _("Duplicate"));
422     }
424     selection->setReprList(newsel);
426     g_slist_free(newsel);
429 void sp_edit_clear_all(SPDesktop *dt)
431     if (!dt)
432         return;
434     SPDocument *doc = sp_desktop_document(dt);
435     sp_desktop_selection(dt)->clear();
437     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
438     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
440     while (items) {
441         SP_OBJECT(items->data)->deleteObject();
442         items = g_slist_remove(items, items->data);
443     }
445     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
446                      _("Delete all"));
449 GSList *
450 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
452     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
453         if (SP_IS_ITEM(child) &&
454             !desktop->isLayer(SP_ITEM(child)) &&
455             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
456             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
457             (!exclude || !g_slist_find((GSList *) exclude, child))
458             )
459         {
460             list = g_slist_prepend(list, SP_ITEM(child));
461         }
463         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
464             list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
465         }
466     }
468     return list;
471 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
473     if (!dt)
474         return;
476     Inkscape::Selection *selection = sp_desktop_selection(dt);
478     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
480     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
481     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
482     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
483     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
485     GSList *items = NULL;
487     GSList const *exclude = NULL;
488     if (invert) {
489         exclude = selection->itemList();
490     }
492     if (force_all_layers)
493         inlayer = PREFS_SELECTION_ALL;
495     switch (inlayer) {
496         case PREFS_SELECTION_LAYER: {
497         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
498              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
499         return;
501         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
503         for (GSList *i = all_items; i; i = i->next) {
504             SPItem *item = SP_ITEM(i->data);
506             if (item && (!onlysensitive || !item->isLocked())) {
507                 if (!onlyvisible || !dt->itemIsHidden(item)) {
508                     if (!dt->isLayer(item)) {
509                         if (!invert || !g_slist_find((GSList *) exclude, item)) {
510                             items = g_slist_prepend(items, item); // leave it in the list
511                         }
512                     }
513                 }
514             }
515         }
517         g_slist_free(all_items);
518             break;
519         }
520         case PREFS_SELECTION_LAYER_RECURSIVE: {
521             items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
522             break;
523         }
524         default: {
525         items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
526             break;
527     }
528     }
530     selection->setList(items);
532     if (items) {
533         g_slist_free(items);
534     }
537 void sp_edit_select_all(SPDesktop *desktop)
539     sp_edit_select_all_full(desktop, false, false);
542 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
544     sp_edit_select_all_full(desktop, true, false);
547 void sp_edit_invert(SPDesktop *desktop)
549     sp_edit_select_all_full(desktop, false, true);
552 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
554     sp_edit_select_all_full(desktop, true, true);
557 void sp_selection_group_impl(GSList const *reprs_to_group, Inkscape::XML::Node *group, Inkscape::XML::Document *xml_doc, SPDocument *doc) {
558     GSList *p = g_slist_copy((GSList *) reprs_to_group);
559     
560     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
561     
562     // Remember the position and parent of the topmost object.
563     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
564     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
565     
566     while (p) {
567         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
569         if (current->parent() == topmost_parent) {
570             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
571             sp_repr_unparent(current);
572             group->appendChild(spnew);
573             Inkscape::GC::release(spnew);
574             topmost --; // only reduce count for those items deleted from topmost_parent
575         } else { // move it to topmost_parent first
576             GSList *temp_clip = NULL;
578             // At this point, current may already have no item, due to its being a clone whose original is already moved away
579             // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
580             gchar const *t_str = current->attribute("transform");
581             Geom::Matrix item_t(Geom::identity());
582             if (t_str)
583                 sp_svg_transform_read(t_str, &item_t);
584             item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
585             // FIXME: when moving both clone and original from a transformed group (either by
586             // grouping into another parent, or by cut/paste) the transform from the original's
587             // parent becomes embedded into original itself, and this affects its clones. Fix
588             // this by remembering the transform diffs we write to each item into an array and
589             // then, if this is clone, looking up its original in that array and pre-multiplying
590             // it by the inverse of that original's transform diff.
592             sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
593             sp_repr_unparent(current);
595             // paste into topmost_parent (temporarily)
596             GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
597             if (temp_clip) g_slist_free(temp_clip);
598             if (copied) { // if success,
599                 // take pasted object (now in topmost_parent)
600                 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
601                 // make a copy
602                 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
603                 // remove pasted
604                 sp_repr_unparent(in_topmost);
605                 // put its copy into group
606                 group->appendChild(spnew);
607                 Inkscape::GC::release(spnew);
608                 g_slist_free(copied);
609             }
610         }
611         p = g_slist_remove(p, current);
612     }
614     // Add the new group to the topmost members' parent
615     topmost_parent->appendChild(group);
617     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
618     group->setPosition(topmost + 1);
621 void sp_selection_group(SPDesktop *desktop)
623     if (desktop == NULL)
624         return;
626     SPDocument *doc = sp_desktop_document(desktop);
627     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
629     Inkscape::Selection *selection = sp_desktop_selection(desktop);
631     // Check if something is selected.
632     if (selection->isEmpty()) {
633         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
634         return;
635     }
637     GSList const *l = (GSList *) selection->reprList();
639     
640     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
641     
642     sp_selection_group_impl(l, group, xml_doc, doc);    
644     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
645                      _("Group"));
647     selection->clear();
648     selection->set(group);
649     Inkscape::GC::release(group);
652 void sp_selection_ungroup(SPDesktop *desktop)
654     if (desktop == NULL)
655         return;
657     Inkscape::Selection *selection = sp_desktop_selection(desktop);
659     if (selection->isEmpty()) {
660         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
661         return;
662     }
664     GSList *items = g_slist_copy((GSList *) selection->itemList());
665     selection->clear();
667     // Get a copy of current selection.
668     GSList *new_select = NULL;
669     bool ungrouped = false;
670     for (GSList *i = items;
671          i != NULL;
672          i = i->next)
673     {
674         SPItem *group = (SPItem *) i->data;
676         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
677         if (!SP_IS_OBJECT(group)) {
678             continue;
679         }
681         /* We do not allow ungrouping <svg> etc. (lauris) */
682         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
683             // keep the non-group item in the new selection
684             selection->add(group);
685             continue;
686         }
688         GSList *children = NULL;
689         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
690         sp_item_group_ungroup(SP_GROUP(group), &children, false);
691         ungrouped = true;
692         // Add ungrouped items to the new selection.
693         new_select = g_slist_concat(new_select, children);
694     }
696     if (new_select) { // Set new selection.
697         selection->addList(new_select);
698         g_slist_free(new_select);
699     }
700     if (!ungrouped) {
701         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
702     }
704     g_slist_free(items);
706     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
707                      _("Ungroup"));
710 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
711 GSList *
712 sp_degroup_list(GSList *items)
714     GSList *out = NULL;
715     bool has_groups = false;
716     for (GSList *item = items; item; item = item->next) {
717         if (!SP_IS_GROUP(item->data)) {
718             out = g_slist_prepend(out, item->data);
719         } else {
720             has_groups = true;
721             GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
722             for (GSList *member = members; member; member = member->next) {
723                 out = g_slist_prepend(out, member->data);
724             }
725             g_slist_free(members);
726         }
727     }
728     out = g_slist_reverse(out);
729     g_slist_free(items);
731     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
732         out = sp_degroup_list(out);
733     }
735     return out;
739 /** If items in the list have a common parent, return it, otherwise return NULL */
740 static SPGroup *
741 sp_item_list_common_parent_group(GSList const *items)
743     if (!items) {
744         return NULL;
745     }
746     SPObject *parent = SP_OBJECT_PARENT(items->data);
747     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
748     if (!SP_IS_GROUP(parent)) {
749         return NULL;
750     }
751     for (items = items->next; items; items = items->next) {
752         if (SP_OBJECT_PARENT(items->data) != parent) {
753             return NULL;
754         }
755     }
757     return SP_GROUP(parent);
760 /** Finds out the minimum common bbox of the selected items. */
761 static Geom::OptRect
762 enclose_items(GSList const *items)
764     g_assert(items != NULL);
766     Geom::OptRect r;
767     for (GSList const *i = items; i; i = i->next) {
768         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
769     }
770     return r;
773 SPObject *
774 prev_sibling(SPObject *child)
776     SPObject *parent = SP_OBJECT_PARENT(child);
777     if (!SP_IS_GROUP(parent)) {
778         return NULL;
779     }
780     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
781         if (i->next == child)
782             return i;
783     }
784     return NULL;
787 void
788 sp_selection_raise(SPDesktop *desktop)
790     if (!desktop)
791         return;
793     Inkscape::Selection *selection = sp_desktop_selection(desktop);
795     GSList const *items = (GSList *) selection->itemList();
796     if (!items) {
797         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
798         return;
799     }
801     SPGroup const *group = sp_item_list_common_parent_group(items);
802     if (!group) {
803         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
804         return;
805     }
807     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
809     /* Construct reverse-ordered list of selected children. */
810     GSList *rev = g_slist_copy((GSList *) items);
811     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
813     // Determine the common bbox of the selected items.
814     Geom::OptRect selected = enclose_items(items);
816     // Iterate over all objects in the selection (starting from top).
817     if (selected) {
818         while (rev) {
819             SPObject *child = SP_OBJECT(rev->data);
820             // for each selected object, find the next sibling
821             for (SPObject *newref = child->next; newref; newref = newref->next) {
822                 // if the sibling is an item AND overlaps our selection,
823                 if (SP_IS_ITEM(newref)) {
824                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
825                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
826                         // AND if it's not one of our selected objects,
827                         if (!g_slist_find((GSList *) items, newref)) {
828                             // move the selected object after that sibling
829                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
830                         }
831                         break;
832                     }
833                 }
834             }
835             rev = g_slist_remove(rev, child);
836         }
837     } else {
838         g_slist_free(rev);
839     }
841     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
842                      //TRANSLATORS: only translate "string" in "context|string".
843                      // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
844                      // "Raise" means "to raise an object" in the undo history
845                      Q_("undo_action|Raise"));
848 void sp_selection_raise_to_top(SPDesktop *desktop)
850     if (desktop == NULL)
851         return;
853     SPDocument *document = sp_desktop_document(desktop);
854     Inkscape::Selection *selection = sp_desktop_selection(desktop);
856     if (selection->isEmpty()) {
857         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
858         return;
859     }
861     GSList const *items = (GSList *) selection->itemList();
863     SPGroup const *group = sp_item_list_common_parent_group(items);
864     if (!group) {
865         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
866         return;
867     }
869     GSList *rl = g_slist_copy((GSList *) selection->reprList());
870     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
872     for (GSList *l = rl; l != NULL; l = l->next) {
873         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
874         repr->setPosition(-1);
875     }
877     g_slist_free(rl);
879     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
880                      _("Raise to top"));
883 void
884 sp_selection_lower(SPDesktop *desktop)
886     if (desktop == NULL)
887         return;
889     Inkscape::Selection *selection = sp_desktop_selection(desktop);
891     GSList const *items = (GSList *) selection->itemList();
892     if (!items) {
893         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
894         return;
895     }
897     SPGroup const *group = sp_item_list_common_parent_group(items);
898     if (!group) {
899         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
900         return;
901     }
903     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
905     // Determine the common bbox of the selected items.
906     Geom::OptRect selected = enclose_items(items);
908     /* Construct direct-ordered list of selected children. */
909     GSList *rev = g_slist_copy((GSList *) items);
910     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
911     rev = g_slist_reverse(rev);
913     // Iterate over all objects in the selection (starting from top).
914     if (selected) {
915         while (rev) {
916             SPObject *child = SP_OBJECT(rev->data);
917             // for each selected object, find the prev sibling
918             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
919                 // if the sibling is an item AND overlaps our selection,
920                 if (SP_IS_ITEM(newref)) {
921                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
922                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
923                         // AND if it's not one of our selected objects,
924                         if (!g_slist_find((GSList *) items, newref)) {
925                             // move the selected object before that sibling
926                             SPObject *put_after = prev_sibling(newref);
927                             if (put_after)
928                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
929                             else
930                                 SP_OBJECT_REPR(child)->setPosition(0);
931                         }
932                         break;
933                     }
934                 }
935             }
936             rev = g_slist_remove(rev, child);
937         }
938     } else {
939         g_slist_free(rev);
940     }
942     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
943                      _("Lower"));
946 void sp_selection_lower_to_bottom(SPDesktop *desktop)
948     if (desktop == NULL)
949         return;
951     SPDocument *document = sp_desktop_document(desktop);
952     Inkscape::Selection *selection = sp_desktop_selection(desktop);
954     if (selection->isEmpty()) {
955         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
956         return;
957     }
959     GSList const *items = (GSList *) selection->itemList();
961     SPGroup const *group = sp_item_list_common_parent_group(items);
962     if (!group) {
963         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
964         return;
965     }
967     GSList *rl;
968     rl = g_slist_copy((GSList *) selection->reprList());
969     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
970     rl = g_slist_reverse(rl);
972     for (GSList *l = rl; l != NULL; l = l->next) {
973         gint minpos;
974         SPObject *pp, *pc;
975         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
976         pp = document->getObjectByRepr(sp_repr_parent(repr));
977         minpos = 0;
978         g_assert(SP_IS_GROUP(pp));
979         pc = sp_object_first_child(pp);
980         while (!SP_IS_ITEM(pc)) {
981             minpos += 1;
982             pc = pc->next;
983         }
984         repr->setPosition(minpos);
985     }
987     g_slist_free(rl);
989     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
990                      _("Lower to bottom"));
993 void
994 sp_undo(SPDesktop *desktop, SPDocument *)
996         if (!sp_document_undo(sp_desktop_document(desktop)))
997             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
1000 void
1001 sp_redo(SPDesktop *desktop, SPDocument *)
1003         if (!sp_document_redo(sp_desktop_document(desktop)))
1004             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
1007 void sp_selection_cut(SPDesktop *desktop)
1009     sp_selection_copy();
1010     sp_selection_delete(desktop);
1013 /**
1014  * \pre item != NULL
1015  */
1016 SPCSSAttr *
1017 take_style_from_item(SPItem *item)
1019     // write the complete cascaded style, context-free
1020     SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1021     if (css == NULL)
1022         return NULL;
1024     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1025         (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1026         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1027         // If this is a group, merge the style of its topmost (last) child with style
1028         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
1029             if (SP_OBJECT_STYLE(last_element) != NULL) {
1030                 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1031                 if (temp) {
1032                     sp_repr_css_merge(css, temp);
1033                     sp_repr_css_attr_unref(temp);
1034                 }
1035                 break;
1036             }
1037         }
1038     }
1039     if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1040         // do not copy text properties from non-text objects, it's confusing
1041         css = sp_css_attr_unset_text(css);
1042     }
1044     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1045     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
1046     if (ex != 1.0) {
1047         css = sp_css_attr_scale(css, ex);
1048     }
1050     return css;
1054 void sp_selection_copy()
1056     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1057     cm->copy();
1060 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1062     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1063     if (cm->paste(in_place))
1064         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1067 void sp_selection_paste_style(SPDesktop *desktop)
1069     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1070     if (cm->pasteStyle())
1071         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1075 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1077     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1078     if (cm->pastePathEffect())
1079         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1080                          _("Paste live path effect"));
1084 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1086     if ( item && SP_IS_LPE_ITEM(item) &&
1087          sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1088         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1089     }
1092 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1094     if (desktop == NULL) return;
1096     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1098     // check if something is selected
1099     if (selection->isEmpty()) {
1100         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1101         return;
1102     }
1104     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1105         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1107         sp_selection_remove_livepatheffect_impl(item);
1109     }
1111     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1112                      _("Remove live path effect"));
1115 void sp_selection_remove_filter(SPDesktop *desktop)
1117     if (desktop == NULL) return;
1119     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1121     // check if something is selected
1122     if (selection->isEmpty()) {
1123         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1124         return;
1125     }
1127     SPCSSAttr *css = sp_repr_css_attr_new();
1128     sp_repr_css_unset_property(css, "filter");
1129     sp_desktop_set_style(desktop, css);
1130     sp_repr_css_attr_unref(css);
1132     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1133                      _("Remove filter"));
1137 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1139     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1140     if (cm->pasteSize(false, apply_x, apply_y))
1141         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1142                          _("Paste size"));
1145 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1147     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1148     if (cm->pasteSize(true, apply_x, apply_y))
1149         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1150                          _("Paste size separately"));
1153 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1155     Inkscape::Selection *selection = sp_desktop_selection(dt);
1157     // check if something is selected
1158     if (selection->isEmpty()) {
1159         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1160         return;
1161     }
1163     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1165     bool no_more = false; // Set to true, if no more layers above
1166     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1167     if (next) {
1168         GSList *temp_clip = NULL;
1169         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1170         sp_selection_delete_impl(items, false, false);
1171         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1172         GSList *copied;
1173         if (next) {
1174             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1175         } else {
1176             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1177             no_more = true;
1178         }
1179         selection->setReprList((GSList const *) copied);
1180         g_slist_free(copied);
1181         if (temp_clip) g_slist_free(temp_clip);
1182         if (next) dt->setCurrentLayer(next);
1183         if ( !suppressDone ) {
1184             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1185                              _("Raise to next layer"));
1186         }
1187     } else {
1188         no_more = true;
1189     }
1191     if (no_more) {
1192         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1193     }
1195     g_slist_free((GSList *) items);
1198 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1200     Inkscape::Selection *selection = sp_desktop_selection(dt);
1202     // check if something is selected
1203     if (selection->isEmpty()) {
1204         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1205         return;
1206     }
1208     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1210     bool no_more = false; // Set to true, if no more layers below
1211     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1212     if (next) {
1213         GSList *temp_clip = NULL;
1214         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
1215         sp_selection_delete_impl(items, false, false);
1216         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1217         GSList *copied;
1218         if (next) {
1219             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1220         } else {
1221             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1222             no_more = true;
1223         }
1224         selection->setReprList((GSList const *) copied);
1225         g_slist_free(copied);
1226         if (temp_clip) g_slist_free(temp_clip);
1227         if (next) dt->setCurrentLayer(next);
1228         if ( !suppressDone ) {
1229             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1230                              _("Lower to previous layer"));
1231         }
1232     } else {
1233         no_more = true;
1234     }
1236     if (no_more) {
1237         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1238     }
1240     g_slist_free((GSList *) items);
1243 bool
1244 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1246     bool contains_original = false;
1248     bool is_use = SP_IS_USE(item);
1249     SPItem *item_use = item;
1250     SPItem *item_use_first = item;
1251     while (is_use && item_use && !contains_original)
1252     {
1253         item_use = sp_use_get_original(SP_USE(item_use));
1254         contains_original |= selection->includes(item_use);
1255         if (item_use == item_use_first)
1256             break;
1257         is_use = SP_IS_USE(item_use);
1258     }
1260     // If it's a tref, check whether the object containing the character
1261     // data is part of the selection
1262     if (!contains_original && SP_IS_TREF(item)) {
1263         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1264     }
1266     return contains_original;
1270 bool
1271 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1273     bool clone_with_original = false;
1274     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1275         SPItem *item = SP_ITEM(l->data);
1276         clone_with_original |= selection_contains_original(item, selection);
1277         if (clone_with_original)
1278             break;
1279     }
1280     return clone_with_original;
1283 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1284 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1285 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1286 that case, items are already in the new position, but the repr is in the old, and this function
1287 then simply updates the repr from item->transform.
1288  */
1289 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1291     if (selection->isEmpty())
1292         return;
1294     // For each perspective with a box in selection, check whether all boxes are selected and
1295     // unlink all non-selected boxes.
1296     Persp3D *persp;
1297     Persp3D *transf_persp;
1298     std::list<Persp3D *> plist = selection->perspList();
1299     for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1300         persp = (Persp3D *) (*i);
1302         if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1303             std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1305             // create a new perspective as a copy of the current one and link the selected boxes to it
1306             transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1308             for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1309                 box3d_switch_perspectives(*b, persp, transf_persp);
1310         } else {
1311             transf_persp = persp;
1312         }
1314         persp3d_apply_affine_transformation(transf_persp, affine);
1315     }
1317     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1318         SPItem *item = SP_ITEM(l->data);
1320         Geom::Point old_center(0,0);
1321         if (set_i2d && item->isCenterSet())
1322             old_center = item->getCenter();
1324 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1325          At the time of writing, this is the only place to re-enable. */
1326         sp_item_update_cns(*item, selection->desktop());
1327 #endif
1329         // we're moving both a clone and its original or any ancestor in clone chain?
1330         bool transform_clone_with_original = selection_contains_original(item, selection);
1331         // ...both a text-on-path and its path?
1332         bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item)))) ));
1333         // ...both a flowtext and its frame?
1334         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)
1335         // ...both an offset and its source?
1336         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1338         // If we're moving a connector, we want to detach it
1339         // from shapes that aren't part of the selection, but
1340         // leave it attached if they are
1341         if (cc_item_is_connector(item)) {
1342             SPItem *attItem[2];
1343             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1345             for (int n = 0; n < 2; ++n) {
1346                 if (!selection->includes(attItem[n])) {
1347                     sp_conn_end_detach(item, n);
1348                 }
1349             }
1350         }
1352         // "clones are unmoved when original is moved" preference
1353         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1354         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1355         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1356         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1358         /* If this is a clone and it's selected along with its original, do not move it;
1359          * it will feel the transform of its original and respond to it itself.
1360          * Without this, a clone is doubly transformed, very unintuitive.
1361          *
1362          * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1363          * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1364          * Same for linked offset if we are also moving its source: do not move it. */
1365         if (transform_textpath_with_path || transform_offset_with_source) {
1366             // Restore item->transform field from the repr, in case it was changed by seltrans.
1367             sp_object_read_attr(SP_OBJECT(item), "transform");
1368         } else if (transform_flowtext_with_frame) {
1369             // apply the inverse of the region's transform to the <use> so that the flow remains
1370             // the same (even though the output itself gets transformed)
1371             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1372                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1373                     continue;
1374                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1375                     if (!SP_IS_USE(use)) continue;
1376                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1377                 }
1378             }
1379         } else if (transform_clone_with_original) {
1380             // We are transforming a clone along with its original. The below matrix juggling is
1381             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1382             // transform and its move compensation are both cancelled out.
1384             // restore item->transform field from the repr, in case it was changed by seltrans
1385             sp_object_read_attr(SP_OBJECT(item), "transform");
1387             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1388             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1389             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1390             Geom::Matrix t_inv = t.inverse();
1391             Geom::Matrix result = t_inv * item->transform * t;
1393             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1394                 // we need to cancel out the move compensation, too
1396                 // find out the clone move, same as in sp_use_move_compensate
1397                 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1398                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1400                 if (prefs_parallel) {
1401                     Geom::Matrix move = result * clone_move * t_inv;
1402                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1404                 } else if (prefs_unmoved) {
1405                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1406                     //    clone_move = Geom::identity();
1407                     Geom::Matrix move = result * clone_move;
1408                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1409                 }
1411             } else {
1412                 // just apply the result
1413                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1414             }
1416         } else {
1417             if (set_i2d) {
1418                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1419             }
1420             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1421         }
1423         // if we're moving the actual object, not just updating the repr, we can transform the
1424         // center by the same matrix (only necessary for non-translations)
1425         if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1426             item->setCenter(old_center * affine);
1427             SP_OBJECT(item)->updateRepr();
1428         }
1429     }
1432 void sp_selection_remove_transform(SPDesktop *desktop)
1434     if (desktop == NULL)
1435         return;
1437     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1439     GSList const *l = (GSList *) selection->reprList();
1440     while (l != NULL) {
1441         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1442         l = l->next;
1443     }
1445     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1446                      _("Remove transform"));
1449 void
1450 sp_selection_scale_absolute(Inkscape::Selection *selection,
1451                             double const x0, double const x1,
1452                             double const y0, double const y1)
1454     if (selection->isEmpty())
1455         return;
1457     Geom::OptRect const bbox(selection->bounds());
1458     if ( !bbox ) {
1459         return;
1460     }
1462     Geom::Translate const p2o(-bbox->min());
1464     Geom::Scale const newSize(x1 - x0,
1465                               y1 - y0);
1466     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1467     Geom::Translate const o2n(x0, y0);
1468     Geom::Matrix const final( p2o * scale * o2n );
1470     sp_selection_apply_affine(selection, final);
1474 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1476     if (selection->isEmpty())
1477         return;
1479     Geom::OptRect const bbox(selection->bounds());
1481     if ( !bbox ) {
1482         return;
1483     }
1485     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1486     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1487          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1488     {
1489         return;
1490     }
1492     Geom::Translate const n2d(-align);
1493     Geom::Translate const d2n(align);
1494     Geom::Matrix const final( n2d * scale * d2n );
1495     sp_selection_apply_affine(selection, final);
1498 void
1499 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1501     Geom::Translate const d2n(center);
1502     Geom::Translate const n2d(-center);
1503     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1504     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1505     sp_selection_apply_affine(selection, final);
1508 void
1509 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1511     Geom::Translate const d2n(align);
1512     Geom::Translate const n2d(-align);
1513     Geom::Matrix const skew(1, dy,
1514                             dx, 1,
1515                             0, 0);
1516     Geom::Matrix const final( n2d * skew * d2n );
1517     sp_selection_apply_affine(selection, final);
1520 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1522     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1525 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1527     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1530 /**
1531  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1532  */
1533 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1535     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1537     if (selection->isEmpty())
1538         return;
1540     GSList const *l = selection->itemList();
1541     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1542     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1543         SPItem *item = SP_ITEM(l2->data);
1544         sp_item_rotate_rel(item, rot_90);
1545     }
1547     sp_document_done(sp_desktop_document(desktop),
1548                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1549                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1552 void
1553 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1555     if (selection->isEmpty())
1556         return;
1558     boost::optional<Geom::Point> center = selection->center();
1559     if (!center) {
1560         return;
1561     }
1563     sp_selection_rotate_relative(selection, *center, angle_degrees);
1565     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1566                            ( ( angle_degrees > 0 )
1567                              ? "selector:rotate:ccw"
1568                              : "selector:rotate:cw" ),
1569                            SP_VERB_CONTEXT_SELECT,
1570                            _("Rotate"));
1573 // helper function:
1574 static
1575 Geom::Point
1576 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1577     Geom::Point m = r.midpoint();
1578     unsigned i = 0;
1579     if (p[X] < m[X]) {
1580         i = 1;
1581     }
1582     if (p[Y] < m[Y]) {
1583         i = 3 - i;
1584     }
1585     return r.corner(i);
1588 /**
1589 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1590 */
1591 void
1592 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1594     if (selection->isEmpty())
1595         return;
1597     Geom::OptRect const bbox(selection->bounds());
1598     boost::optional<Geom::Point> center = selection->center();
1600     if ( !bbox || !center ) {
1601         return;
1602     }
1604     gdouble const zoom = selection->desktop()->current_zoom();
1605     gdouble const zmove = angle / zoom;
1606     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1608     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1610     sp_selection_rotate_relative(selection, *center, zangle);
1612     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1613                            ( (angle > 0)
1614                              ? "selector:rotate:ccw"
1615                              : "selector:rotate:cw" ),
1616                            SP_VERB_CONTEXT_SELECT,
1617                            _("Rotate by pixels"));
1620 void
1621 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1623     if (selection->isEmpty())
1624         return;
1626     Geom::OptRect const bbox(selection->bounds());
1627     if (!bbox) {
1628         return;
1629     }
1631     Geom::Point const center(bbox->midpoint());
1633     // you can't scale "do nizhe pola" (below zero)
1634     double const max_len = bbox->maxExtent();
1635     if ( max_len + grow <= 1e-3 ) {
1636         return;
1637     }
1639     double const times = 1.0 + grow / max_len;
1640     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1642     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1643                            ( (grow > 0)
1644                              ? "selector:scale:larger"
1645                              : "selector:scale:smaller" ),
1646                            SP_VERB_CONTEXT_SELECT,
1647                            _("Scale"));
1650 void
1651 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1653     sp_selection_scale(selection,
1654                        grow_pixels / selection->desktop()->current_zoom());
1657 void
1658 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1660     if (selection->isEmpty())
1661         return;
1663     Geom::OptRect sel_bbox = selection->bounds();
1665     if (!sel_bbox) {
1666         return;
1667     }
1669     Geom::Point const center(sel_bbox->midpoint());
1670     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1671     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1672                      _("Scale by whole factor"));
1675 void
1676 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1678     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1679     if (selection->isEmpty()) {
1680         return;
1681     }
1683     sp_selection_move_relative(selection, dx, dy);
1685     if (dx == 0) {
1686         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1687                                _("Move vertically"));
1688     } else if (dy == 0) {
1689         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1690                                _("Move horizontally"));
1691     } else {
1692         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1693                          _("Move"));
1694     }
1697 void
1698 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1700     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1701     if (selection->isEmpty()) {
1702         return;
1703     }
1705     // same as sp_selection_move but divide deltas by zoom factor
1706     gdouble const zoom = desktop->current_zoom();
1707     gdouble const zdx = dx / zoom;
1708     gdouble const zdy = dy / zoom;
1709     sp_selection_move_relative(selection, zdx, zdy);
1711     if (dx == 0) {
1712         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1713                                _("Move vertically by pixels"));
1714     } else if (dy == 0) {
1715         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1716                                _("Move horizontally by pixels"));
1717     } else {
1718         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1719                          _("Move"));
1720     }
1723 namespace {
1725 template <typename D>
1726 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1727                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1729 template <typename D>
1730 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1731                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1733 struct Forward {
1734     typedef SPObject *Iterator;
1736     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1737     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1738     static void dispose(Iterator /*i*/) {}
1740     static SPObject *object(Iterator i) { return i; }
1741     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1742 };
1744 struct Reverse {
1745     typedef GSList *Iterator;
1747     static Iterator children(SPObject *o) {
1748         return make_list(o->firstChild(), NULL);
1749     }
1750     static Iterator siblings_after(SPObject *o) {
1751         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1752     }
1753     static void dispose(Iterator i) {
1754         g_slist_free(i);
1755     }
1757     static SPObject *object(Iterator i) {
1758         return reinterpret_cast<SPObject *>(i->data);
1759     }
1760     static Iterator next(Iterator i) { return i->next; }
1762 private:
1763     static GSList *make_list(SPObject *object, SPObject *limit) {
1764         GSList *list=NULL;
1765         while ( object != limit ) {
1766             list = g_slist_prepend(list, object);
1767             object = SP_OBJECT_NEXT(object);
1768         }
1769         return list;
1770     }
1771 };
1775 void
1776 sp_selection_item_next(SPDesktop *desktop)
1778     g_return_if_fail(desktop != NULL);
1779     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1781     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1782     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1783     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1784     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1786     SPObject *root;
1787     if (PREFS_SELECTION_ALL != inlayer) {
1788         root = selection->activeContext();
1789     } else {
1790         root = desktop->currentRoot();
1791     }
1793     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1795     if (item) {
1796         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1797         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1798             scroll_to_show_item(desktop, item);
1799         }
1800     }
1803 void
1804 sp_selection_item_prev(SPDesktop *desktop)
1806     SPDocument *document = sp_desktop_document(desktop);
1807     g_return_if_fail(document != NULL);
1808     g_return_if_fail(desktop != NULL);
1809     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1811     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1812     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1813     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1814     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1816     SPObject *root;
1817     if (PREFS_SELECTION_ALL != inlayer) {
1818         root = selection->activeContext();
1819     } else {
1820         root = desktop->currentRoot();
1821     }
1823     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1825     if (item) {
1826         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1827         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1828             scroll_to_show_item(desktop, item);
1829         }
1830     }
1833 void sp_selection_next_patheffect_param(SPDesktop * dt)
1835     if (!dt) return;
1837     Inkscape::Selection *selection = sp_desktop_selection(dt);
1838     if ( selection && !selection->isEmpty() ) {
1839         SPItem *item = selection->singleItem();
1840         if ( item && SP_IS_SHAPE(item)) {
1841             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1842                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1843             } else {
1844                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1845             }
1846         }
1847     }
1850 /*bool has_path_recursive(SPObject *obj)
1852     if (!obj) return false;
1853     if (SP_IS_PATH(obj)) {
1854         return true;
1855     }
1856     if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1857         for (SPObject *c = obj->children; c; c = c->next) {
1858             if (has_path_recursive(c)) return true;
1859         }
1860     }
1861     return false;
1862 }*/
1864 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1866     return;
1867     /*if (!dt) return;
1868     using namespace Inkscape::UI;
1870     Inkscape::Selection *selection = sp_desktop_selection(dt);
1871     if (!selection || selection->isEmpty()) return;
1873     GSList const *items = selection->itemList();
1874     bool has_path = false;
1875     for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1876         SPItem *item = SP_ITEM(i->data);
1877         SPObject *search = clip
1878             ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1879             : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1880         has_path |= has_path_recursive(search);
1881         if (has_path) break;
1882     }
1883     if (has_path) {
1884         if (!tools_isactive(dt, TOOLS_NODES)) {
1885             tools_switch(dt, TOOLS_NODES);
1886         }
1887         ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1888             clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1889     } else if (clip) {
1890         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1891             _("The selection has no applied clip path."));
1892     } else {
1893         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1894             _("The selection has no applied mask."));
1895     }*/
1899 namespace {
1901 template <typename D>
1902 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1903                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1905     SPObject *current=root;
1906     while (items) {
1907         SPItem *item=SP_ITEM(items->data);
1908         if ( root->isAncestorOf(item) &&
1909              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1910         {
1911             current = item;
1912             break;
1913         }
1914         items = items->next;
1915     }
1917     GSList *path=NULL;
1918     while ( current != root ) {
1919         path = g_slist_prepend(path, current);
1920         current = SP_OBJECT_PARENT(current);
1921     }
1923     SPItem *next;
1924     // first, try from the current object
1925     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1926     g_slist_free(path);
1928     if (!next) { // if we ran out of objects, start over at the root
1929         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1930     }
1932     return next;
1935 template <typename D>
1936 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1937                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1939     typename D::Iterator children;
1940     typename D::Iterator iter;
1942     SPItem *found=NULL;
1944     if (path) {
1945         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1946         g_assert(SP_OBJECT_PARENT(object) == root);
1947         if (desktop->isLayer(object)) {
1948             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1949         }
1950         iter = children = D::siblings_after(object);
1951     } else {
1952         iter = children = D::children(root);
1953     }
1955     while ( iter && !found ) {
1956         SPObject *object=D::object(iter);
1957         if (desktop->isLayer(object)) {
1958             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1959                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1960             }
1961         } else if ( SP_IS_ITEM(object) &&
1962                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1963                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1964                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1965                     !desktop->isLayer(SP_ITEM(object)) )
1966         {
1967             found = SP_ITEM(object);
1968         }
1969         iter = D::next(iter);
1970     }
1972     D::dispose(children);
1974     return found;
1979 /**
1980  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1981  * \a item.
1982  */
1983 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1985     Geom::Rect dbox = desktop->get_display_area();
1986     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1988     if ( sbox && dbox.contains(*sbox) == false ) {
1989         Geom::Point const s_dt = sbox->midpoint();
1990         Geom::Point const s_w = desktop->d2w(s_dt);
1991         Geom::Point const d_dt = dbox.midpoint();
1992         Geom::Point const d_w = desktop->d2w(d_dt);
1993         Geom::Point const moved_w( d_w - s_w );
1994         gint const dx = (gint) moved_w[X];
1995         gint const dy = (gint) moved_w[Y];
1996         desktop->scroll_world(dx, dy);
1997     }
2001 void
2002 sp_selection_clone(SPDesktop *desktop)
2004     if (desktop == NULL)
2005         return;
2007     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2009     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2011     // check if something is selected
2012     if (selection->isEmpty()) {
2013         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2014         return;
2015     }
2017     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2019     selection->clear();
2021     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2022     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2024     GSList *newsel = NULL;
2026     while (reprs) {
2027         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2028         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2030         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2031         clone->setAttribute("x", "0", false);
2032         clone->setAttribute("y", "0", false);
2033         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2035         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2036         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2038         // add the new clone to the top of the original's parent
2039         parent->appendChild(clone);
2041         newsel = g_slist_prepend(newsel, clone);
2042         reprs = g_slist_remove(reprs, sel_repr);
2043         Inkscape::GC::release(clone);
2044     }
2046     // TRANSLATORS: only translate "string" in "context|string".
2047     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2048     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2049                      Q_("action|Clone"));
2051     selection->setReprList(newsel);
2053     g_slist_free(newsel);
2056 void
2057 sp_selection_relink(SPDesktop *desktop)
2059     if (!desktop)
2060         return;
2062     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2064     if (selection->isEmpty()) {
2065         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2066         return;
2067     }
2069     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2070     const gchar *newid = cm->getFirstObjectID();
2071     if (!newid) {
2072         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2073         return;
2074     }
2075     gchar *newref = g_strdup_printf("#%s", newid);
2077     // Get a copy of current selection.
2078     bool relinked = false;
2079     for (GSList *items = (GSList *) selection->itemList();
2080          items != NULL;
2081          items = items->next)
2082     {
2083         SPItem *item = (SPItem *) items->data;
2085         if (!SP_IS_USE(item))
2086             continue;
2088         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2089         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2090         relinked = true;
2091     }
2093     g_free(newref);
2095     if (!relinked) {
2096         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2097     } else {
2098         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2099                          _("Relink clone"));
2100     }
2104 void
2105 sp_selection_unlink(SPDesktop *desktop)
2107     if (!desktop)
2108         return;
2110     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2112     if (selection->isEmpty()) {
2113         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2114         return;
2115     }
2117     // Get a copy of current selection.
2118     GSList *new_select = NULL;
2119     bool unlinked = false;
2120     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2121          items != NULL;
2122          items = items->next)
2123     {
2124         SPItem *item = (SPItem *) items->data;
2126         if (SP_IS_TEXT(item)) {
2127             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2129             if (tspan) {
2130                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2131             }
2133             // Set unlink to true, and fall into the next if which
2134             // will include this text item in the new selection
2135             unlinked = true;
2136         }
2138         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2139             // keep the non-use item in the new selection
2140             new_select = g_slist_prepend(new_select, item);
2141             continue;
2142         }
2144         SPItem *unlink;
2145         if (SP_IS_USE(item)) {
2146             unlink = sp_use_unlink(SP_USE(item));
2147         } else /*if (SP_IS_TREF(use))*/ {
2148             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2149         }
2151         unlinked = true;
2152         // Add ungrouped items to the new selection.
2153         new_select = g_slist_prepend(new_select, unlink);
2154     }
2156     if (new_select) { // set new selection
2157         selection->clear();
2158         selection->setList(new_select);
2159         g_slist_free(new_select);
2160     }
2161     if (!unlinked) {
2162         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2163     }
2165     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2166                      _("Unlink clone"));
2169 void
2170 sp_select_clone_original(SPDesktop *desktop)
2172     if (desktop == NULL)
2173         return;
2175     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2177     SPItem *item = selection->singleItem();
2179     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.");
2181     // Check if other than two objects are selected
2182     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2183         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2184         return;
2185     }
2187     SPItem *original = NULL;
2188     if (SP_IS_USE(item)) {
2189         original = sp_use_get_original(SP_USE(item));
2190     } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2191         original = sp_offset_get_source(SP_OFFSET(item));
2192     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2193         original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2194     } else if (SP_IS_FLOWTEXT(item)) {
2195         original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2196     } else { // it's an object that we don't know what to do with
2197         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2198         return;
2199     }
2201     if (!original) {
2202         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2203         return;
2204     }
2206     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2207         if (SP_IS_DEFS(o)) {
2208             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2209             return;
2210         }
2211     }
2213     if (original) {
2214         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2215         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2216         if (highlight) {
2217             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2218             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2219             if ( a && b ) {
2220                 // draw a flashing line between the objects
2221                 SPCurve *curve = new SPCurve();
2222                 curve->moveto(a->midpoint());
2223                 curve->lineto(b->midpoint());
2225                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2226                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2227                 sp_canvas_item_show(canvasitem);
2228                 curve->unref();
2229                 desktop->add_temporary_canvasitem(canvasitem, 1000);
2230             }
2231         }
2233         selection->clear();
2234         selection->set(original);
2235         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2236             scroll_to_show_item(desktop, original);
2237         }
2238     }
2242 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2244     if (desktop == NULL)
2245         return;
2247     SPDocument *doc = sp_desktop_document(desktop);
2248     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2250     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2252     // check if something is selected
2253     if (selection->isEmpty()) {
2254         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2255         return;
2256     }
2258     sp_document_ensure_up_to_date(doc);
2259     Geom::OptRect r = selection->bounds();
2260     boost::optional<Geom::Point> c = selection->center();
2261     if ( !r || !c ) {
2262         return;
2263     }
2265     // calculate the transform to be applied to objects to move them to 0,0
2266     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2267     move_p[Geom::Y] = -move_p[Geom::Y];
2268     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2270     GSList *items = g_slist_copy((GSList *) selection->itemList());
2272     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2274     // bottommost object, after sorting
2275     SPObject *parent = SP_OBJECT_PARENT(items->data);
2277     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2279     // remember the position of the first item
2280     gint pos = SP_OBJECT_REPR(items->data)->position();
2281     (void)pos; // TODO check why this was remembered
2283     // create a list of duplicates
2284     GSList *repr_copies = NULL;
2285     for (GSList *i = items; i != NULL; i = i->next) {
2286         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2287         repr_copies = g_slist_prepend(repr_copies, dup);
2288     }
2290     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2292     if (apply) {
2293         // delete objects so that their clones don't get alerted; this object will be restored shortly
2294         for (GSList *i = items; i != NULL; i = i->next) {
2295             SPObject *item = SP_OBJECT(i->data);
2296             item->deleteObject(false);
2297         }
2298     }
2300     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2301     // without disturbing clones.
2302     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2303     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2304     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2305     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2307     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2308                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2309                                                                               Geom::Point(r->min()[Geom::X],
2310                                                                                           r->max()[Geom::Y]))))
2311                                              * parent_transform.inverse() ),
2312                                            parent_transform * move);
2313     (void)mark_id;
2315     // restore compensation setting
2316     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2319     g_slist_free(items);
2321     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2322                      _("Objects to marker"));
2325 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2326     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2327         for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2328             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2329         }
2330     } else {
2331         sp_item_convert_item_to_guides(item);
2333         if (deleteitem) {
2334             SP_OBJECT(item)->deleteObject(true);
2335         }
2336     }
2339 void sp_selection_to_guides(SPDesktop *desktop)
2341     if (desktop == NULL)
2342         return;
2344     SPDocument *doc = sp_desktop_document(desktop);
2345     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2346     // we need to copy the list because it gets reset when objects are deleted
2347     GSList *items = g_slist_copy((GSList *) selection->itemList());
2349     if (!items) {
2350         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2351         return;
2352     }
2354     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2355     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2356     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2358     for (GSList const *i = items; i != NULL; i = i->next) {
2359         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2360     }
2362     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2365 void
2366 sp_selection_tile(SPDesktop *desktop, bool apply)
2368     if (desktop == NULL)
2369         return;
2371     SPDocument *doc = sp_desktop_document(desktop);
2372     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2374     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2376     // check if something is selected
2377     if (selection->isEmpty()) {
2378         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2379         return;
2380     }
2382     sp_document_ensure_up_to_date(doc);
2383     Geom::OptRect r = selection->bounds();
2384     if ( !r ) {
2385         return;
2386     }
2388     // calculate the transform to be applied to objects to move them to 0,0
2389     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2390     move_p[Geom::Y] = -move_p[Geom::Y];
2391     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2393     GSList *items = g_slist_copy((GSList *) selection->itemList());
2395     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2397     // bottommost object, after sorting
2398     SPObject *parent = SP_OBJECT_PARENT(items->data);
2400     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2402     // remember the position of the first item
2403     gint pos = SP_OBJECT_REPR(items->data)->position();
2405     // create a list of duplicates
2406     GSList *repr_copies = NULL;
2407     for (GSList *i = items; i != NULL; i = i->next) {
2408         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2409         repr_copies = g_slist_prepend(repr_copies, dup);
2410     }
2411     // restore the z-order after prepends
2412     repr_copies = g_slist_reverse(repr_copies);
2414     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2416     if (apply) {
2417         // delete objects so that their clones don't get alerted; this object will be restored shortly
2418         for (GSList *i = items; i != NULL; i = i->next) {
2419             SPObject *item = SP_OBJECT(i->data);
2420             item->deleteObject(false);
2421         }
2422     }
2424     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2425     // without disturbing clones.
2426     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2427     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2428     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2429     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2431     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2432                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2433                                                                                             r->max()[Geom::Y]))))
2434                                          * to_2geom(parent_transform.inverse()) ),
2435                                        parent_transform * move);
2437     // restore compensation setting
2438     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2440     if (apply) {
2441         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2442         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2444         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2445         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2447         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2448         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2449         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2450         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2452         // restore parent and position
2453         SP_OBJECT_REPR(parent)->appendChild(rect);
2454         rect->setPosition(pos > 0 ? pos : 0);
2455         SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2457         Inkscape::GC::release(rect);
2459         selection->clear();
2460         selection->set(rectangle);
2461     }
2463     g_slist_free(items);
2465     sp_document_done(doc, SP_VERB_EDIT_TILE,
2466                      _("Objects to pattern"));
2469 void
2470 sp_selection_untile(SPDesktop *desktop)
2472     if (desktop == NULL)
2473         return;
2475     SPDocument *doc = sp_desktop_document(desktop);
2476     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2478     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2480     // check if something is selected
2481     if (selection->isEmpty()) {
2482         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2483         return;
2484     }
2486     GSList *new_select = NULL;
2488     bool did = false;
2490     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2491          items != NULL;
2492          items = items->next) {
2494         SPItem *item = (SPItem *) items->data;
2496         SPStyle *style = SP_OBJECT_STYLE(item);
2498         if (!style || !style->fill.isPaintserver())
2499             continue;
2501         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2503         if (!SP_IS_PATTERN(server))
2504             continue;
2506         did = true;
2508         SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2510         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2511         pat_transform *= item->transform;
2513         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2514             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2515             SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2517            // FIXME: relink clones to the new canvas objects
2518            // use SPObject::setid when mental finishes it to steal ids of
2520             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2521             sp_document_ensure_up_to_date(doc);
2523             Geom::Matrix transform( i->transform * pat_transform );
2524             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2526             new_select = g_slist_prepend(new_select, i);
2527         }
2529         SPCSSAttr *css = sp_repr_css_attr_new();
2530         sp_repr_css_set_property(css, "fill", "none");
2531         sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2532     }
2534     if (!did) {
2535         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2536     } else {
2537         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2538                          _("Pattern to objects"));
2539         selection->setList(new_select);
2540     }
2543 void
2544 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2546     if (selection->isEmpty()) {
2547         return;
2548     }
2550     GSList const *reprlst = selection->reprList();
2551     bool filename_search = TRUE;
2552     bool xdpi_search = TRUE;
2553     bool ydpi_search = TRUE;
2555     for (; reprlst != NULL &&
2556             filename_search &&
2557             xdpi_search &&
2558             ydpi_search;
2559         reprlst = reprlst->next) {
2560         gchar const *dpi_string;
2561         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2563         if (filename_search) {
2564             *filename = repr->attribute("inkscape:export-filename");
2565             if (*filename != NULL)
2566                 filename_search = FALSE;
2567         }
2569         if (xdpi_search) {
2570             dpi_string = NULL;
2571             dpi_string = repr->attribute("inkscape:export-xdpi");
2572             if (dpi_string != NULL) {
2573                 *xdpi = atof(dpi_string);
2574                 xdpi_search = FALSE;
2575             }
2576         }
2578         if (ydpi_search) {
2579             dpi_string = NULL;
2580             dpi_string = repr->attribute("inkscape:export-ydpi");
2581             if (dpi_string != NULL) {
2582                 *ydpi = atof(dpi_string);
2583                 ydpi_search = FALSE;
2584             }
2585         }
2586     }
2589 void
2590 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2592     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2593     gchar const *dpi_string;
2595     *filename = repr->attribute("inkscape:export-filename");
2597     dpi_string = NULL;
2598     dpi_string = repr->attribute("inkscape:export-xdpi");
2599     if (dpi_string != NULL) {
2600         *xdpi = atof(dpi_string);
2601     }
2603     dpi_string = NULL;
2604     dpi_string = repr->attribute("inkscape:export-ydpi");
2605     if (dpi_string != NULL) {
2606         *ydpi = atof(dpi_string);
2607     }
2610 void
2611 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2613     if (desktop == NULL)
2614         return;
2616     SPDocument *document = sp_desktop_document(desktop);
2617     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2619     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2621     // check if something is selected
2622     if (selection->isEmpty()) {
2623         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2624         return;
2625     }
2627     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2628     // set "busy" cursor
2629     desktop->setWaitingCursor();
2631     // Get the bounding box of the selection
2632     NRRect bbox;
2633     sp_document_ensure_up_to_date(document);
2634     selection->bounds(&bbox);
2635     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2636         desktop->clearWaitingCursor();
2637         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2638     }
2640     // List of the items to show; all others will be hidden
2641     GSList *items = g_slist_copy((GSList *) selection->itemList());
2643     // Sort items so that the topmost comes last
2644     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2646     // Generate a random value from the current time (you may create bitmap from the same object(s)
2647     // multiple times, and this is done so that they don't clash)
2648     GTimeVal cu;
2649     g_get_current_time(&cu);
2650     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2652     // Create the filename.
2653     gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2654                                             document->name,
2655                                             SP_OBJECT_REPR(items->data)->attribute("id"),
2656                                             current);
2657     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2658     // digits, and a few other chars, with "_"
2659     g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2661     // Build the complete path by adding document base dir, if set, otherwise home dir
2662     gchar * directory = NULL;
2663     if (SP_DOCUMENT_URI(document)) {
2664         directory = g_dirname(SP_DOCUMENT_URI(document));
2665     }
2666     if (directory == NULL) {
2667         directory = homedir_path(NULL);
2668     }
2669     gchar *filepath = g_build_filename(directory, basename, NULL);
2671     //g_print("%s\n", filepath);
2673     // Remember parent and z-order of the topmost one
2674     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2675     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2676     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2678     // Calculate resolution
2679     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2680     double res;
2681     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2682     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2683     if (0 < prefs_res) {
2684         // If it's given explicitly in prefs, take it
2685         res = prefs_res;
2686     } else if (0 < prefs_min) {
2687         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2688         res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2689     } else {
2690         float hint_xdpi = 0, hint_ydpi = 0;
2691         char const *hint_filename;
2692         // take resolution hint from the selected objects
2693         sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2694         if (hint_xdpi != 0) {
2695             res = hint_xdpi;
2696         } else {
2697             // take resolution hint from the document
2698             sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2699             if (hint_xdpi != 0) {
2700                 res = hint_xdpi;
2701             } else {
2702                 // if all else fails, take the default 90 dpi
2703                 res = PX_PER_IN;
2704             }
2705         }
2706     }
2708     // The width and height of the bitmap in pixels
2709     unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2710     unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2712     // Find out if we have to run an external filter
2713     gchar const *run = NULL;
2714     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2715     if (!filter.empty()) {
2716         // filter command is given;
2717         // see if we have a parameter to pass to it
2718         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2719         if (!param1.empty()) {
2720             if (param1[param1.length() - 1] == '%') {
2721                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2722                 gchar p1[256];
2723                 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2724                 // the first param is always the image filename, the second is param1
2725                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2726             } else {
2727                 // otherwise pass the param1 unchanged
2728                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2729             }
2730         } else {
2731             // run without extra parameter
2732             run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2733         }
2734     }
2736     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2737     Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2738     Geom::Matrix t;
2740     double shift_x = bbox.x0;
2741     double shift_y = bbox.y1;
2742     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2743         shift_x = round(shift_x);
2744         shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2745     }
2746     t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2748     // Do the export
2749     sp_export_png_file(document, filepath,
2750                        bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2751                        width, height, res, res,
2752                        (guint32) 0xffffff00,
2753                        NULL, NULL,
2754                        true,  /*bool force_overwrite,*/
2755                        items);
2757     g_slist_free(items);
2759     // Run filter, if any
2760     if (run) {
2761         g_print("Running external filter: %s\n", run);
2762         int retval;
2763         retval = system(run);
2764     }
2766     // Import the image back
2767     GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2768     if (pb) {
2769         // Create the repr for the image
2770         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2771         {
2772             repr->setAttribute("sodipodi:absref", filepath);
2773             gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2774             repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2775             g_free(abs_base);
2776         }
2777         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2778             sp_repr_set_svg_double(repr, "width", width);
2779             sp_repr_set_svg_double(repr, "height", height);
2780         } else {
2781             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2782             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2783         }
2785         // Write transform
2786         gchar *c=sp_svg_transform_write(t);
2787         repr->setAttribute("transform", c);
2788         g_free(c);
2790         // add the new repr to the parent
2791         parent->appendChild(repr);
2793         // move to the saved position
2794         repr->setPosition(pos > 0 ? pos + 1 : 1);
2796         // Set selection to the new image
2797         selection->clear();
2798         selection->add(repr);
2800         // Clean up
2801         Inkscape::GC::release(repr);
2802         gdk_pixbuf_unref(pb);
2804         // Complete undoable transaction
2805         sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2806                          _("Create bitmap"));
2807     }
2809     desktop->clearWaitingCursor();
2811     g_free(basename);
2812     g_free(filepath);
2815 /**
2816  * \brief Creates a mask or clipPath from selection
2817  * Two different modes:
2818  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2819  *       and is applied to current layer
2820  *  otherwise, topmost object is used as mask for other objects
2821  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2822  *
2823  */
2824 void
2825 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2827     if (desktop == NULL)
2828         return;
2830     SPDocument *doc = sp_desktop_document(desktop);
2831     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2833     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2835     // check if something is selected
2836     bool is_empty = selection->isEmpty();
2837     if ( apply_to_layer && is_empty) {
2838         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2839         return;
2840     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2841         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2842         return;
2843     }
2845     // FIXME: temporary patch to prevent crash!
2846     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2847     bool clone_with_original = selection_contains_both_clone_and_original(selection);
2848     if (clone_with_original) {
2849         return; // in this version, you cannot clip/mask an object with its own clone
2850     }
2851     // /END FIXME
2853     sp_document_ensure_up_to_date(doc);
2855     GSList *items = g_slist_copy((GSList *) selection->itemList());
2857     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2859     // create a list of duplicates
2860     GSList *mask_items = NULL;
2861     GSList *apply_to_items = NULL;
2862     GSList *items_to_delete = NULL;
2863     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2864     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2865     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2866     int grouping = prefs->getInt("/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE);
2868     if (apply_to_layer) {
2869         // all selected items are used for mask, which is applied to a layer
2870         apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2872         for (GSList *i = items; i != NULL; i = i->next) {
2873             Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2874             mask_items = g_slist_prepend(mask_items, dup);
2876             if (remove_original) {
2877                 SPObject *item = SP_OBJECT(i->data);
2878                 items_to_delete = g_slist_prepend(items_to_delete, item);
2879             }
2880         }
2881     } else if (!topmost) {
2882         // topmost item is used as a mask, which is applied to other items in a selection
2883         GSList *i = items;
2884         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2885         mask_items = g_slist_prepend(mask_items, dup);
2887         if (remove_original) {
2888             SPObject *item = SP_OBJECT(i->data);
2889             items_to_delete = g_slist_prepend(items_to_delete, item);
2890         }
2892         for (i = i->next; i != NULL; i = i->next) {
2893             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2894         }
2895     } else {
2896         GSList *i = NULL;
2897         for (i = items; NULL != i->next; i = i->next) {
2898             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2899         }
2901         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2902         mask_items = g_slist_prepend(mask_items, dup);
2904         if (remove_original) {
2905             SPObject *item = SP_OBJECT(i->data);
2906             items_to_delete = g_slist_prepend(items_to_delete, item);
2907         }
2908     }
2910     g_slist_free(items);
2911     items = NULL;
2912     
2913     if (apply_to_items && grouping == PREFS_MASKOBJECT_GROUPING_ALL) {
2914         // group all those objects into one group
2915         // and apply mask to that
2916         Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2917         
2918         // make a note we should ungroup this when unsetting mask
2919         group->setAttribute("inkscape:groupmode", "maskhelper");
2920         
2921         GSList *reprs_to_group = NULL;
2922         
2923         for (GSList *i = apply_to_items ; NULL != i ; i = i->next) {
2924                 reprs_to_group = g_slist_prepend(reprs_to_group, SP_OBJECT_REPR(i->data));
2925                 selection->remove(SP_OBJECT(i->data));
2926         }
2927         reprs_to_group = g_slist_reverse(reprs_to_group);
2928         
2929         sp_selection_group_impl(reprs_to_group, group, xml_doc, doc);
2930         
2931         g_slist_free(reprs_to_group);
2932         
2933         // apply clip/mask only to newly created group
2934         g_slist_free(apply_to_items);
2935         apply_to_items = NULL;
2936         apply_to_items = g_slist_prepend(apply_to_items, doc->getObjectByRepr(group));
2937         
2938         selection->add(group);
2939         
2940         Inkscape::GC::release(group);
2941     }
2943     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2944     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2945         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2946         // inverted object transform should be applied to a mask object,
2947         // as mask is calculated in user space (after applying transform)
2948         Geom::Matrix maskTransform(item->transform.inverse());
2950         GSList *mask_items_dup = NULL;
2951         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2952             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2953             mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2954         }
2956         gchar const *mask_id = NULL;
2957         if (apply_clip_path) {
2958             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2959         } else {
2960             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2961         }
2963         g_slist_free(mask_items_dup);
2964         mask_items_dup = NULL;
2966         Inkscape::XML::Node *current = SP_OBJECT_REPR(i->data);
2967         // Node to apply mask to
2968         Inkscape::XML::Node *apply_mask_to = current;
2969         
2970         if (grouping == PREFS_MASKOBJECT_GROUPING_SEPARATE) {
2971             // enclose current node in group, and apply crop/mask on that
2972             Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2973             // make a note we should ungroup this when unsetting mask
2974             group->setAttribute("inkscape:groupmode", "maskhelper");
2975             
2976             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
2977             gint position = current->position();
2978             selection->remove(current);
2979             current->parent()->appendChild(group);
2980             sp_repr_unparent(current);
2981             group->appendChild(spnew);
2982             group->setPosition(position);
2983             
2984             // Apply clip/mask to group instead
2985             apply_mask_to = group;
2986             
2987             selection->add(group);
2988             Inkscape::GC::release(spnew); 
2989             Inkscape::GC::release(group);
2990         }
2991         
2992         apply_mask_to->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2993         
2994     }
2996     g_slist_free(mask_items);
2997     g_slist_free(apply_to_items);
2999     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3000         SPObject *item = SP_OBJECT(i->data);
3001         item->deleteObject(false);
3002     }
3003     g_slist_free(items_to_delete);
3005     if (apply_clip_path)
3006         sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3007     else
3008         sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3011 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
3012     if (desktop == NULL)
3013         return;
3015     SPDocument *doc = sp_desktop_document(desktop);
3016     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3017     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3019     // check if something is selected
3020     if (selection->isEmpty()) {
3021         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3022         return;
3023     }
3025     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
3026     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
3027     bool ungroup_masked = prefs->getBool("/options/maskobject/ungrouping", true);
3028     sp_document_ensure_up_to_date(doc);
3030     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3031     std::map<SPObject*,SPItem*> referenced_objects;
3032     
3033     GSList *items_to_ungroup = NULL;
3034     
3035     // SPObject* refers to a group containing the clipped path or mask itself,
3036     // whereas SPItem* refers to the item being clipped or masked
3037     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3038         if (remove_original) {
3039             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3040             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3041             Inkscape::URIReference *uri_ref = NULL;
3043             if (apply_clip_path) {
3044                 uri_ref = item->clip_ref;
3045             } else {
3046                 uri_ref = item->mask_ref;
3047             }
3049             // collect distinct mask object (and associate with item to apply transform)
3050             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3051                 referenced_objects[uri_ref->getObject()] = item;
3052             }
3053         }
3055         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3056         
3057         if (ungroup_masked && SP_IS_GROUP(i->data)) {
3058                 // if we had previously enclosed masked object in group,
3059                 // add it to list so we can ungroup it later
3060                 SPGroup *item = SP_GROUP(i->data);
3061                 
3062                 // ungroup only groups we created when setting clip/mask
3063                 if (item->layerMode() == SPGroup::MASK_HELPER) {
3064                     items_to_ungroup = g_slist_prepend(items_to_ungroup, item);
3065                 }
3066                 
3067         }
3068     }
3070     // restore mask objects into a document
3071     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3072         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
3073         GSList *items_to_move = NULL;
3074         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3075             // Collect all clipped paths and masks within a single group
3076             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3077             items_to_move = g_slist_prepend(items_to_move, copy);
3078         }
3080         if (!obj->isReferenced()) {
3081             // delete from defs if no other object references this mask
3082             obj->deleteObject(false);
3083         }
3085         // remember parent and position of the item to which the clippath/mask was applied
3086         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3087         gint pos = SP_OBJECT_REPR((*it).second)->position();
3089         // Iterate through all clipped paths / masks
3090         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3091             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3093             // insert into parent, restore pos
3094             parent->appendChild(repr);
3095             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3097             SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3098             selection->add(repr);
3100             // transform mask, so it is moved the same spot where mask was applied
3101             Geom::Matrix transform(mask_item->transform);
3102             transform *= (*it).second->transform;
3103             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3104         }
3106         g_slist_free(items_to_move);
3107     }
3108     
3109     // ungroup marked groups added when setting mask
3110     for (GSList *i = items_to_ungroup ; NULL != i ; i = i->next) {
3111         selection->remove(SP_GROUP(i->data));
3112         GSList *children = NULL;
3113         sp_item_group_ungroup(SP_GROUP(i->data), &children, false);
3114         selection->addList(children);
3115         g_slist_free(children);
3116     }
3117     
3118     g_slist_free(items_to_ungroup);
3120     if (apply_clip_path)
3121         sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3122     else
3123         sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3126 /**
3127  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3128  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3129  * \return true if an undoable change should be recorded.
3130  */
3131 bool
3132 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3134     g_return_val_if_fail(desktop != NULL, false);
3135     SPDocument *doc = sp_desktop_document(desktop);
3137     g_return_val_if_fail(doc != NULL, false);
3138     g_return_val_if_fail(desktop->selection != NULL, false);
3140     if (desktop->selection->isEmpty()) {
3141         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3142         return false;
3143     }
3144     Geom::OptRect const bbox(desktop->selection->bounds());
3145     if (bbox) {
3146         doc->fitToRect(*bbox, with_margins);
3147         return true;
3148     } else {
3149         return false;
3150     }
3153 /**
3154  * Fit canvas to the bounding box of the selection, as an undoable action.
3155  */
3156 void
3157 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3159     if (fit_canvas_to_selection(desktop)) {
3160         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3161                          _("Fit Page to Selection"));
3162     }
3165 /**
3166  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3167  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3168  */
3169 bool
3170 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3172     g_return_val_if_fail(doc != NULL, false);
3174     sp_document_ensure_up_to_date(doc);
3175     SPItem const *const root = SP_ITEM(doc->root);
3176     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
3177     if (bbox) {
3178         doc->fitToRect(*bbox, with_margins);
3179         return true;
3180     } else {
3181         return false;
3182     }
3185 void
3186 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3188     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3189         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3190                          _("Fit Page to Drawing"));
3191     }
3194 /**
3195  * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3196  * "fit-margin-..." attributes.  See SPDocument::fitToRect and
3197  * ui/dialog/page-sizer.
3198  */
3199 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3200     g_return_if_fail(desktop != NULL);
3201     SPDocument *doc = sp_desktop_document(desktop);
3203     g_return_if_fail(doc != NULL);
3204     g_return_if_fail(desktop->selection != NULL);
3206     bool const changed = ( desktop->selection->isEmpty()
3207                            ? fit_canvas_to_drawing(doc, true)
3208                            : fit_canvas_to_selection(desktop, true) );
3209     if (changed) {
3210         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3211                          _("Fit Page to Selection or Drawing"));
3212     }
3213 };
3215 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3216     // don't operate on layers
3217     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3218         f(SP_ITEM(root), desktop);
3219     }
3220     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3221         //don't recurse into locked layers
3222         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3223             itemtree_map(f, iter, desktop);
3224         }
3225     }
3228 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3229     if (item->isLocked()) {
3230         item->setLocked(FALSE);
3231     }
3234 static void unhide(SPItem *item, SPDesktop *desktop) {
3235     if (desktop->itemIsHidden(item)) {
3236         item->setExplicitlyHidden(FALSE);
3237     }
3240 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3241     if (!dt) return;
3243     SPObject *root;
3244     if (layer_only) {
3245         root = dt->currentLayer();
3246     } else {
3247         root = dt->currentRoot();
3248     }
3250     itemtree_map(f, root, dt);
3253 void unlock_all(SPDesktop *dt) {
3254     process_all(&unlock, dt, true);
3257 void unlock_all_in_all_layers(SPDesktop *dt) {
3258     process_all(&unlock, dt, false);
3261 void unhide_all(SPDesktop *dt) {
3262     process_all(&unhide, dt, true);
3265 void unhide_all_in_all_layers(SPDesktop *dt) {
3266     process_all(&unhide, dt, false);
3270 /*
3271   Local Variables:
3272   mode:c++
3273   c-file-style:"stroustrup"
3274   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3275   indent-tabs-mode:nil
3276   fill-column:99
3277   End:
3278 */
3279 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :