Code

Fix multiple minor problems in the node tool
[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         if (!nt->_multipath->empty()) {
122             nt->_multipath->selectSubpaths();
123             return;
124         }
125     }
126     sp_edit_select_all(dt);
129 void SelectionHelper::selectAllInAll(SPDesktop *dt)
131     if (tools_isactive(dt, TOOLS_NODES)) {
132         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
133         nt->_selected_nodes->selectAll();
134     } else {
135         sp_edit_select_all_in_all_layers(dt);
136     }
139 void SelectionHelper::selectNone(SPDesktop *dt)
141     if (tools_isactive(dt, TOOLS_NODES)) {
142         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
143         nt->_selected_nodes->clear();
144     } else {
145         sp_desktop_selection(dt)->clear();
146     }
149 void SelectionHelper::invert(SPDesktop *dt)
151     if (tools_isactive(dt, TOOLS_NODES)) {
152         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
153         nt->_multipath->invertSelectionInSubpaths();
154     } else {
155         sp_edit_invert(dt);
156     }
159 void SelectionHelper::invertAllInAll(SPDesktop *dt)
161     if (tools_isactive(dt, TOOLS_NODES)) {
162         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
163         nt->_selected_nodes->invertSelection();
164     } else {
165         sp_edit_invert_in_all_layers(dt);
166     }
169 void SelectionHelper::reverse(SPDesktop *dt)
171     // TODO make this a virtual method of event context!
172     if (tools_isactive(dt, TOOLS_NODES)) {
173         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
174         nt->_multipath->reverseSubpaths();
175     } else {
176         sp_selected_path_reverse(dt);
177     }
180 void SelectionHelper::selectNext(SPDesktop *dt)
182     SPEventContext *ec = dt->event_context;
183     if (tools_isactive(dt, TOOLS_NODES)) {
184         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
185         nt->_multipath->shiftSelection(1);
186     } else if (tools_isactive(dt, TOOLS_GRADIENT)
187                && ec->_grdrag->isNonEmpty()) {
188         sp_gradient_context_select_next(ec);
189     } else {
190         sp_selection_item_next(dt);
191     }
194 void SelectionHelper::selectPrev(SPDesktop *dt)
196     SPEventContext *ec = dt->event_context;
197     if (tools_isactive(dt, TOOLS_NODES)) {
198         InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
199         nt->_multipath->shiftSelection(-1);
200     } else if (tools_isactive(dt, TOOLS_GRADIENT)
201                && ec->_grdrag->isNonEmpty()) {
202         sp_gradient_context_select_prev(ec);
203     } else {
204         sp_selection_item_prev(dt);
205     }
208 } // namespace Inkscape
211 /**
212  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
213  * then prepends the copy to 'clip'.
214  */
215 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
217     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
219     // copy complete inherited style
220     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
221     sp_repr_css_set(copy, css, "style");
222     sp_repr_css_attr_unref(css);
224     // write the complete accumulated transform passed to us
225     // (we're dealing with unattached repr, so we write to its attr
226     // instead of using sp_item_set_transform)
227     gchar *affinestr=sp_svg_transform_write(full_t);
228     copy->setAttribute("transform", affinestr);
229     g_free(affinestr);
231     *clip = g_slist_prepend(*clip, copy);
234 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
236     // Sort items:
237     GSList *sorted_items = g_slist_copy((GSList *) items);
238     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
240     // Copy item reprs:
241     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
242         sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
243     }
245     *clip = g_slist_reverse(*clip);
246     g_slist_free((GSList *) sorted_items);
249 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
251     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
253     GSList *copied = NULL;
254     // add objects to document
255     for (GSList *l = *clip; l != NULL; l = l->next) {
256         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
257         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
259         // premultiply the item transform by the accumulated parent transform in the paste layer
260         Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
261         if (!local.isIdentity()) {
262             gchar const *t_str = copy->attribute("transform");
263             Geom::Matrix item_t(Geom::identity());
264             if (t_str)
265                 sp_svg_transform_read(t_str, &item_t);
266             item_t *= local.inverse();
267             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
268             gchar *affinestr=sp_svg_transform_write(item_t);
269             copy->setAttribute("transform", affinestr);
270             g_free(affinestr);
271         }
273         parent->appendChildRepr(copy);
274         copied = g_slist_prepend(copied, copy);
275         Inkscape::GC::release(copy);
276     }
277     return copied;
280 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
282     for (GSList const *i = items ; i ; i = i->next ) {
283         sp_object_ref((SPObject *)i->data, NULL);
284     }
285     for (GSList const *i = items; i != NULL; i = i->next) {
286         SPItem *item = (SPItem *) i->data;
287         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
288         sp_object_unref((SPObject *)item, NULL);
289     }
293 void sp_selection_delete(SPDesktop *desktop)
295     if (desktop == NULL) {
296         return;
297     }
299     if (tools_isactive(desktop, TOOLS_TEXT))
300         if (sp_text_delete_selection(desktop->event_context)) {
301             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
302                              _("Delete text"));
303             return;
304         }
306     Inkscape::Selection *selection = sp_desktop_selection(desktop);
308     // check if something is selected
309     if (selection->isEmpty()) {
310         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
311         return;
312     }
314     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
315     selection->clear();
316     sp_selection_delete_impl(selected);
317     g_slist_free((GSList *) selected);
319     /* a tool may have set up private information in it's selection context
320      * that depends on desktop items.  I think the only sane way to deal with
321      * this currently is to reset the current tool, which will reset it's
322      * associated selection context.  For example: deleting an object
323      * while moving it around the canvas.
324      */
325     tools_switch( desktop, tools_active( desktop ) );
327     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
328                      _("Delete"));
331 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
333     if (!obj)
334         return;
336     ids.push_back(SP_OBJECT_ID(obj));
338     if (SP_IS_GROUP(obj)) {
339         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
340             add_ids_recursive(ids, child);
341         }
342     }
345 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
347     if (desktop == NULL)
348         return;
350     SPDocument *doc = desktop->doc();
351     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
352     Inkscape::Selection *selection = sp_desktop_selection(desktop);
354     // check if something is selected
355     if (selection->isEmpty()) {
356         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
357         return;
358     }
360     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
362     selection->clear();
364     // sorting items from different parents sorts each parent's subset without possibly mixing
365     // them, just what we need
366     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
368     GSList *newsel = NULL;
370     std::vector<const gchar *> old_ids;
371     std::vector<const gchar *> new_ids;
372     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
373     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
375     while (reprs) {
376         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
377         Inkscape::XML::Node *parent = old_repr->parent();
378         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
380         parent->appendChild(copy);
382         if (relink_clones) {
383             SPObject *old_obj = doc->getObjectByRepr(old_repr);
384             SPObject *new_obj = doc->getObjectByRepr(copy);
385             add_ids_recursive(old_ids, old_obj);
386             add_ids_recursive(new_ids, new_obj);
387         }
389         newsel = g_slist_prepend(newsel, copy);
390         reprs = g_slist_remove(reprs, reprs->data);
391         Inkscape::GC::release(copy);
392     }
394     if (relink_clones) {
396         g_assert(old_ids.size() == new_ids.size());
398         for (unsigned int i = 0; i < old_ids.size(); i++) {
399             const gchar *id = old_ids[i];
400             SPObject *old_clone = doc->getObjectById(id);
401             if (SP_IS_USE(old_clone)) {
402                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
403                 if (!orig) // orphaned
404                     continue;
405                 for (unsigned int j = 0; j < old_ids.size(); j++) {
406                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
407                         // we have both orig and clone in selection, relink
408                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
409                         gchar *newref = g_strdup_printf("#%s", new_ids[j]);
410                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
411                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
412                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
413                         g_free(newref);
414                     }
415                 }
416             }
417         }
418     }
421     if ( !suppressDone ) {
422         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
423                          _("Duplicate"));
424     }
426     selection->setReprList(newsel);
428     g_slist_free(newsel);
431 void sp_edit_clear_all(SPDesktop *dt)
433     if (!dt)
434         return;
436     SPDocument *doc = sp_desktop_document(dt);
437     sp_desktop_selection(dt)->clear();
439     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
440     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
442     while (items) {
443         SP_OBJECT(items->data)->deleteObject();
444         items = g_slist_remove(items, items->data);
445     }
447     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
448                      _("Delete all"));
451 GSList *
452 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
454     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
455         if (SP_IS_ITEM(child) &&
456             !desktop->isLayer(SP_ITEM(child)) &&
457             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
458             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
459             (!exclude || !g_slist_find((GSList *) exclude, child))
460             )
461         {
462             list = g_slist_prepend(list, SP_ITEM(child));
463         }
465         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
466             list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
467         }
468     }
470     return list;
473 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
475     if (!dt)
476         return;
478     Inkscape::Selection *selection = sp_desktop_selection(dt);
480     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
482     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
483     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
484     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
485     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
487     GSList *items = NULL;
489     GSList const *exclude = NULL;
490     if (invert) {
491         exclude = selection->itemList();
492     }
494     if (force_all_layers)
495         inlayer = PREFS_SELECTION_ALL;
497     switch (inlayer) {
498         case PREFS_SELECTION_LAYER: {
499         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
500              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
501         return;
503         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
505         for (GSList *i = all_items; i; i = i->next) {
506             SPItem *item = SP_ITEM(i->data);
508             if (item && (!onlysensitive || !item->isLocked())) {
509                 if (!onlyvisible || !dt->itemIsHidden(item)) {
510                     if (!dt->isLayer(item)) {
511                         if (!invert || !g_slist_find((GSList *) exclude, item)) {
512                             items = g_slist_prepend(items, item); // leave it in the list
513                         }
514                     }
515                 }
516             }
517         }
519         g_slist_free(all_items);
520             break;
521         }
522         case PREFS_SELECTION_LAYER_RECURSIVE: {
523             items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
524             break;
525         }
526         default: {
527         items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
528             break;
529     }
530     }
532     selection->setList(items);
534     if (items) {
535         g_slist_free(items);
536     }
539 void sp_edit_select_all(SPDesktop *desktop)
541     sp_edit_select_all_full(desktop, false, false);
544 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
546     sp_edit_select_all_full(desktop, true, false);
549 void sp_edit_invert(SPDesktop *desktop)
551     sp_edit_select_all_full(desktop, false, true);
554 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
556     sp_edit_select_all_full(desktop, true, true);
559 void sp_selection_group_impl(GSList const *reprs_to_group, Inkscape::XML::Node *group, Inkscape::XML::Document *xml_doc, SPDocument *doc) {
560     GSList *p = g_slist_copy((GSList *) reprs_to_group);
561     
562     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
563     
564     // Remember the position and parent of the topmost object.
565     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
566     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
567     
568     while (p) {
569         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
571         if (current->parent() == topmost_parent) {
572             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
573             sp_repr_unparent(current);
574             group->appendChild(spnew);
575             Inkscape::GC::release(spnew);
576             topmost --; // only reduce count for those items deleted from topmost_parent
577         } else { // move it to topmost_parent first
578             GSList *temp_clip = NULL;
580             // At this point, current may already have no item, due to its being a clone whose original is already moved away
581             // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
582             gchar const *t_str = current->attribute("transform");
583             Geom::Matrix item_t(Geom::identity());
584             if (t_str)
585                 sp_svg_transform_read(t_str, &item_t);
586             item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
587             // FIXME: when moving both clone and original from a transformed group (either by
588             // grouping into another parent, or by cut/paste) the transform from the original's
589             // parent becomes embedded into original itself, and this affects its clones. Fix
590             // this by remembering the transform diffs we write to each item into an array and
591             // then, if this is clone, looking up its original in that array and pre-multiplying
592             // it by the inverse of that original's transform diff.
594             sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
595             sp_repr_unparent(current);
597             // paste into topmost_parent (temporarily)
598             GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
599             if (temp_clip) g_slist_free(temp_clip);
600             if (copied) { // if success,
601                 // take pasted object (now in topmost_parent)
602                 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
603                 // make a copy
604                 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
605                 // remove pasted
606                 sp_repr_unparent(in_topmost);
607                 // put its copy into group
608                 group->appendChild(spnew);
609                 Inkscape::GC::release(spnew);
610                 g_slist_free(copied);
611             }
612         }
613         p = g_slist_remove(p, current);
614     }
616     // Add the new group to the topmost members' parent
617     topmost_parent->appendChild(group);
619     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
620     group->setPosition(topmost + 1);
623 void sp_selection_group(SPDesktop *desktop)
625     if (desktop == NULL)
626         return;
628     SPDocument *doc = sp_desktop_document(desktop);
629     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
631     Inkscape::Selection *selection = sp_desktop_selection(desktop);
633     // Check if something is selected.
634     if (selection->isEmpty()) {
635         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
636         return;
637     }
639     GSList const *l = (GSList *) selection->reprList();
641     
642     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
643     
644     sp_selection_group_impl(l, group, xml_doc, doc);    
646     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
647                      _("Group"));
649     selection->clear();
650     selection->set(group);
651     Inkscape::GC::release(group);
654 void sp_selection_ungroup(SPDesktop *desktop)
656     if (desktop == NULL)
657         return;
659     Inkscape::Selection *selection = sp_desktop_selection(desktop);
661     if (selection->isEmpty()) {
662         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
663         return;
664     }
666     GSList *items = g_slist_copy((GSList *) selection->itemList());
667     selection->clear();
669     // Get a copy of current selection.
670     GSList *new_select = NULL;
671     bool ungrouped = false;
672     for (GSList *i = items;
673          i != NULL;
674          i = i->next)
675     {
676         SPItem *group = (SPItem *) i->data;
678         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
679         if (!SP_IS_OBJECT(group)) {
680             continue;
681         }
683         /* We do not allow ungrouping <svg> etc. (lauris) */
684         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
685             // keep the non-group item in the new selection
686             selection->add(group);
687             continue;
688         }
690         GSList *children = NULL;
691         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
692         sp_item_group_ungroup(SP_GROUP(group), &children, false);
693         ungrouped = true;
694         // Add ungrouped items to the new selection.
695         new_select = g_slist_concat(new_select, children);
696     }
698     if (new_select) { // Set new selection.
699         selection->addList(new_select);
700         g_slist_free(new_select);
701     }
702     if (!ungrouped) {
703         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
704     }
706     g_slist_free(items);
708     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
709                      _("Ungroup"));
712 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
713 GSList *
714 sp_degroup_list(GSList *items)
716     GSList *out = NULL;
717     bool has_groups = false;
718     for (GSList *item = items; item; item = item->next) {
719         if (!SP_IS_GROUP(item->data)) {
720             out = g_slist_prepend(out, item->data);
721         } else {
722             has_groups = true;
723             GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
724             for (GSList *member = members; member; member = member->next) {
725                 out = g_slist_prepend(out, member->data);
726             }
727             g_slist_free(members);
728         }
729     }
730     out = g_slist_reverse(out);
731     g_slist_free(items);
733     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
734         out = sp_degroup_list(out);
735     }
737     return out;
741 /** If items in the list have a common parent, return it, otherwise return NULL */
742 static SPGroup *
743 sp_item_list_common_parent_group(GSList const *items)
745     if (!items) {
746         return NULL;
747     }
748     SPObject *parent = SP_OBJECT_PARENT(items->data);
749     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
750     if (!SP_IS_GROUP(parent)) {
751         return NULL;
752     }
753     for (items = items->next; items; items = items->next) {
754         if (SP_OBJECT_PARENT(items->data) != parent) {
755             return NULL;
756         }
757     }
759     return SP_GROUP(parent);
762 /** Finds out the minimum common bbox of the selected items. */
763 static Geom::OptRect
764 enclose_items(GSList const *items)
766     g_assert(items != NULL);
768     Geom::OptRect r;
769     for (GSList const *i = items; i; i = i->next) {
770         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
771     }
772     return r;
775 SPObject *
776 prev_sibling(SPObject *child)
778     SPObject *parent = SP_OBJECT_PARENT(child);
779     if (!SP_IS_GROUP(parent)) {
780         return NULL;
781     }
782     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
783         if (i->next == child)
784             return i;
785     }
786     return NULL;
789 void
790 sp_selection_raise(SPDesktop *desktop)
792     if (!desktop)
793         return;
795     Inkscape::Selection *selection = sp_desktop_selection(desktop);
797     GSList const *items = (GSList *) selection->itemList();
798     if (!items) {
799         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
800         return;
801     }
803     SPGroup const *group = sp_item_list_common_parent_group(items);
804     if (!group) {
805         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
806         return;
807     }
809     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
811     /* Construct reverse-ordered list of selected children. */
812     GSList *rev = g_slist_copy((GSList *) items);
813     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
815     // Determine the common bbox of the selected items.
816     Geom::OptRect selected = enclose_items(items);
818     // Iterate over all objects in the selection (starting from top).
819     if (selected) {
820         while (rev) {
821             SPObject *child = SP_OBJECT(rev->data);
822             // for each selected object, find the next sibling
823             for (SPObject *newref = child->next; newref; newref = newref->next) {
824                 // if the sibling is an item AND overlaps our selection,
825                 if (SP_IS_ITEM(newref)) {
826                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
827                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
828                         // AND if it's not one of our selected objects,
829                         if (!g_slist_find((GSList *) items, newref)) {
830                             // move the selected object after that sibling
831                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
832                         }
833                         break;
834                     }
835                 }
836             }
837             rev = g_slist_remove(rev, child);
838         }
839     } else {
840         g_slist_free(rev);
841     }
843     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
844                      //TRANSLATORS: only translate "string" in "context|string".
845                      // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
846                      // "Raise" means "to raise an object" in the undo history
847                      Q_("undo_action|Raise"));
850 void sp_selection_raise_to_top(SPDesktop *desktop)
852     if (desktop == NULL)
853         return;
855     SPDocument *document = sp_desktop_document(desktop);
856     Inkscape::Selection *selection = sp_desktop_selection(desktop);
858     if (selection->isEmpty()) {
859         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
860         return;
861     }
863     GSList const *items = (GSList *) selection->itemList();
865     SPGroup const *group = sp_item_list_common_parent_group(items);
866     if (!group) {
867         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
868         return;
869     }
871     GSList *rl = g_slist_copy((GSList *) selection->reprList());
872     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
874     for (GSList *l = rl; l != NULL; l = l->next) {
875         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
876         repr->setPosition(-1);
877     }
879     g_slist_free(rl);
881     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
882                      _("Raise to top"));
885 void
886 sp_selection_lower(SPDesktop *desktop)
888     if (desktop == NULL)
889         return;
891     Inkscape::Selection *selection = sp_desktop_selection(desktop);
893     GSList const *items = (GSList *) selection->itemList();
894     if (!items) {
895         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
896         return;
897     }
899     SPGroup const *group = sp_item_list_common_parent_group(items);
900     if (!group) {
901         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
902         return;
903     }
905     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
907     // Determine the common bbox of the selected items.
908     Geom::OptRect selected = enclose_items(items);
910     /* Construct direct-ordered list of selected children. */
911     GSList *rev = g_slist_copy((GSList *) items);
912     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
913     rev = g_slist_reverse(rev);
915     // Iterate over all objects in the selection (starting from top).
916     if (selected) {
917         while (rev) {
918             SPObject *child = SP_OBJECT(rev->data);
919             // for each selected object, find the prev sibling
920             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
921                 // if the sibling is an item AND overlaps our selection,
922                 if (SP_IS_ITEM(newref)) {
923                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
924                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
925                         // AND if it's not one of our selected objects,
926                         if (!g_slist_find((GSList *) items, newref)) {
927                             // move the selected object before that sibling
928                             SPObject *put_after = prev_sibling(newref);
929                             if (put_after)
930                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
931                             else
932                                 SP_OBJECT_REPR(child)->setPosition(0);
933                         }
934                         break;
935                     }
936                 }
937             }
938             rev = g_slist_remove(rev, child);
939         }
940     } else {
941         g_slist_free(rev);
942     }
944     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
945                      _("Lower"));
948 void sp_selection_lower_to_bottom(SPDesktop *desktop)
950     if (desktop == NULL)
951         return;
953     SPDocument *document = sp_desktop_document(desktop);
954     Inkscape::Selection *selection = sp_desktop_selection(desktop);
956     if (selection->isEmpty()) {
957         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
958         return;
959     }
961     GSList const *items = (GSList *) selection->itemList();
963     SPGroup const *group = sp_item_list_common_parent_group(items);
964     if (!group) {
965         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
966         return;
967     }
969     GSList *rl;
970     rl = g_slist_copy((GSList *) selection->reprList());
971     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
972     rl = g_slist_reverse(rl);
974     for (GSList *l = rl; l != NULL; l = l->next) {
975         gint minpos;
976         SPObject *pp, *pc;
977         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
978         pp = document->getObjectByRepr(sp_repr_parent(repr));
979         minpos = 0;
980         g_assert(SP_IS_GROUP(pp));
981         pc = sp_object_first_child(pp);
982         while (!SP_IS_ITEM(pc)) {
983             minpos += 1;
984             pc = pc->next;
985         }
986         repr->setPosition(minpos);
987     }
989     g_slist_free(rl);
991     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
992                      _("Lower to bottom"));
995 void
996 sp_undo(SPDesktop *desktop, SPDocument *)
998         if (!sp_document_undo(sp_desktop_document(desktop)))
999             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
1002 void
1003 sp_redo(SPDesktop *desktop, SPDocument *)
1005         if (!sp_document_redo(sp_desktop_document(desktop)))
1006             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
1009 void sp_selection_cut(SPDesktop *desktop)
1011     sp_selection_copy();
1012     sp_selection_delete(desktop);
1015 /**
1016  * \pre item != NULL
1017  */
1018 SPCSSAttr *
1019 take_style_from_item(SPItem *item)
1021     // write the complete cascaded style, context-free
1022     SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1023     if (css == NULL)
1024         return NULL;
1026     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1027         (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1028         // if this is a text with exactly one tspan child, merge the style of that tspan as well
1029         // If this is a group, merge the style of its topmost (last) child with style
1030         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
1031             if (SP_OBJECT_STYLE(last_element) != NULL) {
1032                 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1033                 if (temp) {
1034                     sp_repr_css_merge(css, temp);
1035                     sp_repr_css_attr_unref(temp);
1036                 }
1037                 break;
1038             }
1039         }
1040     }
1041     if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1042         // do not copy text properties from non-text objects, it's confusing
1043         css = sp_css_attr_unset_text(css);
1044     }
1046     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1047     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
1048     if (ex != 1.0) {
1049         css = sp_css_attr_scale(css, ex);
1050     }
1052     return css;
1056 void sp_selection_copy()
1058     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1059     cm->copy();
1062 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1064     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1065     if (cm->paste(in_place))
1066         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1069 void sp_selection_paste_style(SPDesktop *desktop)
1071     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1072     if (cm->pasteStyle())
1073         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1077 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1079     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1080     if (cm->pastePathEffect())
1081         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1082                          _("Paste live path effect"));
1086 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1088     if ( item && SP_IS_LPE_ITEM(item) &&
1089          sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1090         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1091     }
1094 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1096     if (desktop == NULL) return;
1098     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1100     // check if something is selected
1101     if (selection->isEmpty()) {
1102         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1103         return;
1104     }
1106     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1107         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1109         sp_selection_remove_livepatheffect_impl(item);
1111     }
1113     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1114                      _("Remove live path effect"));
1117 void sp_selection_remove_filter(SPDesktop *desktop)
1119     if (desktop == NULL) return;
1121     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1123     // check if something is selected
1124     if (selection->isEmpty()) {
1125         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1126         return;
1127     }
1129     SPCSSAttr *css = sp_repr_css_attr_new();
1130     sp_repr_css_unset_property(css, "filter");
1131     sp_desktop_set_style(desktop, css);
1132     sp_repr_css_attr_unref(css);
1134     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1135                      _("Remove filter"));
1139 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1141     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1142     if (cm->pasteSize(false, apply_x, apply_y))
1143         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1144                          _("Paste size"));
1147 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1149     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1150     if (cm->pasteSize(true, apply_x, apply_y))
1151         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1152                          _("Paste size separately"));
1155 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1157     Inkscape::Selection *selection = sp_desktop_selection(dt);
1159     // check if something is selected
1160     if (selection->isEmpty()) {
1161         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1162         return;
1163     }
1165     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1167     bool no_more = false; // Set to true, if no more layers above
1168     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1169     if (next) {
1170         GSList *temp_clip = NULL;
1171         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1172         sp_selection_delete_impl(items, false, false);
1173         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1174         GSList *copied;
1175         if (next) {
1176             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1177         } else {
1178             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1179             no_more = true;
1180         }
1181         selection->setReprList((GSList const *) copied);
1182         g_slist_free(copied);
1183         if (temp_clip) g_slist_free(temp_clip);
1184         if (next) dt->setCurrentLayer(next);
1185         if ( !suppressDone ) {
1186             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1187                              _("Raise to next layer"));
1188         }
1189     } else {
1190         no_more = true;
1191     }
1193     if (no_more) {
1194         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1195     }
1197     g_slist_free((GSList *) items);
1200 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1202     Inkscape::Selection *selection = sp_desktop_selection(dt);
1204     // check if something is selected
1205     if (selection->isEmpty()) {
1206         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1207         return;
1208     }
1210     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1212     bool no_more = false; // Set to true, if no more layers below
1213     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1214     if (next) {
1215         GSList *temp_clip = NULL;
1216         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
1217         sp_selection_delete_impl(items, false, false);
1218         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1219         GSList *copied;
1220         if (next) {
1221             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1222         } else {
1223             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1224             no_more = true;
1225         }
1226         selection->setReprList((GSList const *) copied);
1227         g_slist_free(copied);
1228         if (temp_clip) g_slist_free(temp_clip);
1229         if (next) dt->setCurrentLayer(next);
1230         if ( !suppressDone ) {
1231             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1232                              _("Lower to previous layer"));
1233         }
1234     } else {
1235         no_more = true;
1236     }
1238     if (no_more) {
1239         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1240     }
1242     g_slist_free((GSList *) items);
1245 bool
1246 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1248     bool contains_original = false;
1250     bool is_use = SP_IS_USE(item);
1251     SPItem *item_use = item;
1252     SPItem *item_use_first = item;
1253     while (is_use && item_use && !contains_original)
1254     {
1255         item_use = sp_use_get_original(SP_USE(item_use));
1256         contains_original |= selection->includes(item_use);
1257         if (item_use == item_use_first)
1258             break;
1259         is_use = SP_IS_USE(item_use);
1260     }
1262     // If it's a tref, check whether the object containing the character
1263     // data is part of the selection
1264     if (!contains_original && SP_IS_TREF(item)) {
1265         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1266     }
1268     return contains_original;
1272 bool
1273 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1275     bool clone_with_original = false;
1276     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1277         SPItem *item = SP_ITEM(l->data);
1278         clone_with_original |= selection_contains_original(item, selection);
1279         if (clone_with_original)
1280             break;
1281     }
1282     return clone_with_original;
1285 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1286 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1287 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1288 that case, items are already in the new position, but the repr is in the old, and this function
1289 then simply updates the repr from item->transform.
1290  */
1291 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1293     if (selection->isEmpty())
1294         return;
1296     // For each perspective with a box in selection, check whether all boxes are selected and
1297     // unlink all non-selected boxes.
1298     Persp3D *persp;
1299     Persp3D *transf_persp;
1300     std::list<Persp3D *> plist = selection->perspList();
1301     for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1302         persp = (Persp3D *) (*i);
1304         if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1305             std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1307             // create a new perspective as a copy of the current one and link the selected boxes to it
1308             transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1310             for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1311                 box3d_switch_perspectives(*b, persp, transf_persp);
1312         } else {
1313             transf_persp = persp;
1314         }
1316         persp3d_apply_affine_transformation(transf_persp, affine);
1317     }
1319     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1320         SPItem *item = SP_ITEM(l->data);
1322         Geom::Point old_center(0,0);
1323         if (set_i2d && item->isCenterSet())
1324             old_center = item->getCenter();
1326 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1327          At the time of writing, this is the only place to re-enable. */
1328         sp_item_update_cns(*item, selection->desktop());
1329 #endif
1331         // we're moving both a clone and its original or any ancestor in clone chain?
1332         bool transform_clone_with_original = selection_contains_original(item, selection);
1333         // ...both a text-on-path and its path?
1334         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)))) ));
1335         // ...both a flowtext and its frame?
1336         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)
1337         // ...both an offset and its source?
1338         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1340         // If we're moving a connector, we want to detach it
1341         // from shapes that aren't part of the selection, but
1342         // leave it attached if they are
1343         if (cc_item_is_connector(item)) {
1344             SPItem *attItem[2];
1345             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1347             for (int n = 0; n < 2; ++n) {
1348                 if (!selection->includes(attItem[n])) {
1349                     sp_conn_end_detach(item, n);
1350                 }
1351             }
1352         }
1354         // "clones are unmoved when original is moved" preference
1355         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1356         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1357         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1358         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1360         /* If this is a clone and it's selected along with its original, do not move it;
1361          * it will feel the transform of its original and respond to it itself.
1362          * Without this, a clone is doubly transformed, very unintuitive.
1363          *
1364          * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1365          * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1366          * Same for linked offset if we are also moving its source: do not move it. */
1367         if (transform_textpath_with_path || transform_offset_with_source) {
1368             // Restore item->transform field from the repr, in case it was changed by seltrans.
1369             sp_object_read_attr(SP_OBJECT(item), "transform");
1370         } else if (transform_flowtext_with_frame) {
1371             // apply the inverse of the region's transform to the <use> so that the flow remains
1372             // the same (even though the output itself gets transformed)
1373             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1374                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1375                     continue;
1376                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1377                     if (!SP_IS_USE(use)) continue;
1378                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1379                 }
1380             }
1381         } else if (transform_clone_with_original) {
1382             // We are transforming a clone along with its original. The below matrix juggling is
1383             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1384             // transform and its move compensation are both cancelled out.
1386             // restore item->transform field from the repr, in case it was changed by seltrans
1387             sp_object_read_attr(SP_OBJECT(item), "transform");
1389             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1390             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1391             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1392             Geom::Matrix t_inv = t.inverse();
1393             Geom::Matrix result = t_inv * item->transform * t;
1395             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1396                 // we need to cancel out the move compensation, too
1398                 // find out the clone move, same as in sp_use_move_compensate
1399                 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1400                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1402                 if (prefs_parallel) {
1403                     Geom::Matrix move = result * clone_move * t_inv;
1404                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1406                 } else if (prefs_unmoved) {
1407                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1408                     //    clone_move = Geom::identity();
1409                     Geom::Matrix move = result * clone_move;
1410                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1411                 }
1413             } else {
1414                 // just apply the result
1415                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1416             }
1418         } else {
1419             if (set_i2d) {
1420                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1421             }
1422             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1423         }
1425         // if we're moving the actual object, not just updating the repr, we can transform the
1426         // center by the same matrix (only necessary for non-translations)
1427         if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1428             item->setCenter(old_center * affine);
1429             SP_OBJECT(item)->updateRepr();
1430         }
1431     }
1434 void sp_selection_remove_transform(SPDesktop *desktop)
1436     if (desktop == NULL)
1437         return;
1439     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1441     GSList const *l = (GSList *) selection->reprList();
1442     while (l != NULL) {
1443         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1444         l = l->next;
1445     }
1447     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1448                      _("Remove transform"));
1451 void
1452 sp_selection_scale_absolute(Inkscape::Selection *selection,
1453                             double const x0, double const x1,
1454                             double const y0, double const y1)
1456     if (selection->isEmpty())
1457         return;
1459     Geom::OptRect const bbox(selection->bounds());
1460     if ( !bbox ) {
1461         return;
1462     }
1464     Geom::Translate const p2o(-bbox->min());
1466     Geom::Scale const newSize(x1 - x0,
1467                               y1 - y0);
1468     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1469     Geom::Translate const o2n(x0, y0);
1470     Geom::Matrix const final( p2o * scale * o2n );
1472     sp_selection_apply_affine(selection, final);
1476 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1478     if (selection->isEmpty())
1479         return;
1481     Geom::OptRect const bbox(selection->bounds());
1483     if ( !bbox ) {
1484         return;
1485     }
1487     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1488     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1489          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1490     {
1491         return;
1492     }
1494     Geom::Translate const n2d(-align);
1495     Geom::Translate const d2n(align);
1496     Geom::Matrix const final( n2d * scale * d2n );
1497     sp_selection_apply_affine(selection, final);
1500 void
1501 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1503     Geom::Translate const d2n(center);
1504     Geom::Translate const n2d(-center);
1505     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1506     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1507     sp_selection_apply_affine(selection, final);
1510 void
1511 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1513     Geom::Translate const d2n(align);
1514     Geom::Translate const n2d(-align);
1515     Geom::Matrix const skew(1, dy,
1516                             dx, 1,
1517                             0, 0);
1518     Geom::Matrix const final( n2d * skew * d2n );
1519     sp_selection_apply_affine(selection, final);
1522 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1524     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1527 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1529     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1532 /**
1533  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1534  */
1535 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1537     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1539     if (selection->isEmpty())
1540         return;
1542     GSList const *l = selection->itemList();
1543     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1544     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1545         SPItem *item = SP_ITEM(l2->data);
1546         sp_item_rotate_rel(item, rot_90);
1547     }
1549     sp_document_done(sp_desktop_document(desktop),
1550                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1551                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1554 void
1555 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1557     if (selection->isEmpty())
1558         return;
1560     boost::optional<Geom::Point> center = selection->center();
1561     if (!center) {
1562         return;
1563     }
1565     sp_selection_rotate_relative(selection, *center, angle_degrees);
1567     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1568                            ( ( angle_degrees > 0 )
1569                              ? "selector:rotate:ccw"
1570                              : "selector:rotate:cw" ),
1571                            SP_VERB_CONTEXT_SELECT,
1572                            _("Rotate"));
1575 // helper function:
1576 static
1577 Geom::Point
1578 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1579     Geom::Point m = r.midpoint();
1580     unsigned i = 0;
1581     if (p[X] < m[X]) {
1582         i = 1;
1583     }
1584     if (p[Y] < m[Y]) {
1585         i = 3 - i;
1586     }
1587     return r.corner(i);
1590 /**
1591 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1592 */
1593 void
1594 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1596     if (selection->isEmpty())
1597         return;
1599     Geom::OptRect const bbox(selection->bounds());
1600     boost::optional<Geom::Point> center = selection->center();
1602     if ( !bbox || !center ) {
1603         return;
1604     }
1606     gdouble const zoom = selection->desktop()->current_zoom();
1607     gdouble const zmove = angle / zoom;
1608     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1610     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1612     sp_selection_rotate_relative(selection, *center, zangle);
1614     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1615                            ( (angle > 0)
1616                              ? "selector:rotate:ccw"
1617                              : "selector:rotate:cw" ),
1618                            SP_VERB_CONTEXT_SELECT,
1619                            _("Rotate by pixels"));
1622 void
1623 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1625     if (selection->isEmpty())
1626         return;
1628     Geom::OptRect const bbox(selection->bounds());
1629     if (!bbox) {
1630         return;
1631     }
1633     Geom::Point const center(bbox->midpoint());
1635     // you can't scale "do nizhe pola" (below zero)
1636     double const max_len = bbox->maxExtent();
1637     if ( max_len + grow <= 1e-3 ) {
1638         return;
1639     }
1641     double const times = 1.0 + grow / max_len;
1642     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1644     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1645                            ( (grow > 0)
1646                              ? "selector:scale:larger"
1647                              : "selector:scale:smaller" ),
1648                            SP_VERB_CONTEXT_SELECT,
1649                            _("Scale"));
1652 void
1653 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1655     sp_selection_scale(selection,
1656                        grow_pixels / selection->desktop()->current_zoom());
1659 void
1660 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1662     if (selection->isEmpty())
1663         return;
1665     Geom::OptRect sel_bbox = selection->bounds();
1667     if (!sel_bbox) {
1668         return;
1669     }
1671     Geom::Point const center(sel_bbox->midpoint());
1672     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1673     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1674                      _("Scale by whole factor"));
1677 void
1678 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1680     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1681     if (selection->isEmpty()) {
1682         return;
1683     }
1685     sp_selection_move_relative(selection, dx, dy);
1687     if (dx == 0) {
1688         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1689                                _("Move vertically"));
1690     } else if (dy == 0) {
1691         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1692                                _("Move horizontally"));
1693     } else {
1694         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1695                          _("Move"));
1696     }
1699 void
1700 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1702     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1703     if (selection->isEmpty()) {
1704         return;
1705     }
1707     // same as sp_selection_move but divide deltas by zoom factor
1708     gdouble const zoom = desktop->current_zoom();
1709     gdouble const zdx = dx / zoom;
1710     gdouble const zdy = dy / zoom;
1711     sp_selection_move_relative(selection, zdx, zdy);
1713     if (dx == 0) {
1714         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1715                                _("Move vertically by pixels"));
1716     } else if (dy == 0) {
1717         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1718                                _("Move horizontally by pixels"));
1719     } else {
1720         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1721                          _("Move"));
1722     }
1725 namespace {
1727 template <typename D>
1728 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1729                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1731 template <typename D>
1732 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1733                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1735 struct Forward {
1736     typedef SPObject *Iterator;
1738     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1739     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1740     static void dispose(Iterator /*i*/) {}
1742     static SPObject *object(Iterator i) { return i; }
1743     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1744 };
1746 struct Reverse {
1747     typedef GSList *Iterator;
1749     static Iterator children(SPObject *o) {
1750         return make_list(o->firstChild(), NULL);
1751     }
1752     static Iterator siblings_after(SPObject *o) {
1753         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1754     }
1755     static void dispose(Iterator i) {
1756         g_slist_free(i);
1757     }
1759     static SPObject *object(Iterator i) {
1760         return reinterpret_cast<SPObject *>(i->data);
1761     }
1762     static Iterator next(Iterator i) { return i->next; }
1764 private:
1765     static GSList *make_list(SPObject *object, SPObject *limit) {
1766         GSList *list=NULL;
1767         while ( object != limit ) {
1768             list = g_slist_prepend(list, object);
1769             object = SP_OBJECT_NEXT(object);
1770         }
1771         return list;
1772     }
1773 };
1777 void
1778 sp_selection_item_next(SPDesktop *desktop)
1780     g_return_if_fail(desktop != NULL);
1781     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1783     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1784     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1785     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1786     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1788     SPObject *root;
1789     if (PREFS_SELECTION_ALL != inlayer) {
1790         root = selection->activeContext();
1791     } else {
1792         root = desktop->currentRoot();
1793     }
1795     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1797     if (item) {
1798         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1799         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1800             scroll_to_show_item(desktop, item);
1801         }
1802     }
1805 void
1806 sp_selection_item_prev(SPDesktop *desktop)
1808     SPDocument *document = sp_desktop_document(desktop);
1809     g_return_if_fail(document != NULL);
1810     g_return_if_fail(desktop != NULL);
1811     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1813     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1814     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1815     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1816     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1818     SPObject *root;
1819     if (PREFS_SELECTION_ALL != inlayer) {
1820         root = selection->activeContext();
1821     } else {
1822         root = desktop->currentRoot();
1823     }
1825     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1827     if (item) {
1828         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1829         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1830             scroll_to_show_item(desktop, item);
1831         }
1832     }
1835 void sp_selection_next_patheffect_param(SPDesktop * dt)
1837     if (!dt) return;
1839     Inkscape::Selection *selection = sp_desktop_selection(dt);
1840     if ( selection && !selection->isEmpty() ) {
1841         SPItem *item = selection->singleItem();
1842         if ( item && SP_IS_SHAPE(item)) {
1843             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1844                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1845             } else {
1846                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1847             }
1848         }
1849     }
1852 /*bool has_path_recursive(SPObject *obj)
1854     if (!obj) return false;
1855     if (SP_IS_PATH(obj)) {
1856         return true;
1857     }
1858     if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1859         for (SPObject *c = obj->children; c; c = c->next) {
1860             if (has_path_recursive(c)) return true;
1861         }
1862     }
1863     return false;
1864 }*/
1866 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1868     return;
1869     /*if (!dt) return;
1870     using namespace Inkscape::UI;
1872     Inkscape::Selection *selection = sp_desktop_selection(dt);
1873     if (!selection || selection->isEmpty()) return;
1875     GSList const *items = selection->itemList();
1876     bool has_path = false;
1877     for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1878         SPItem *item = SP_ITEM(i->data);
1879         SPObject *search = clip
1880             ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1881             : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1882         has_path |= has_path_recursive(search);
1883         if (has_path) break;
1884     }
1885     if (has_path) {
1886         if (!tools_isactive(dt, TOOLS_NODES)) {
1887             tools_switch(dt, TOOLS_NODES);
1888         }
1889         ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1890             clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1891     } else if (clip) {
1892         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1893             _("The selection has no applied clip path."));
1894     } else {
1895         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1896             _("The selection has no applied mask."));
1897     }*/
1901 namespace {
1903 template <typename D>
1904 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1905                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1907     SPObject *current=root;
1908     while (items) {
1909         SPItem *item=SP_ITEM(items->data);
1910         if ( root->isAncestorOf(item) &&
1911              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1912         {
1913             current = item;
1914             break;
1915         }
1916         items = items->next;
1917     }
1919     GSList *path=NULL;
1920     while ( current != root ) {
1921         path = g_slist_prepend(path, current);
1922         current = SP_OBJECT_PARENT(current);
1923     }
1925     SPItem *next;
1926     // first, try from the current object
1927     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1928     g_slist_free(path);
1930     if (!next) { // if we ran out of objects, start over at the root
1931         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1932     }
1934     return next;
1937 template <typename D>
1938 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1939                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1941     typename D::Iterator children;
1942     typename D::Iterator iter;
1944     SPItem *found=NULL;
1946     if (path) {
1947         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1948         g_assert(SP_OBJECT_PARENT(object) == root);
1949         if (desktop->isLayer(object)) {
1950             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1951         }
1952         iter = children = D::siblings_after(object);
1953     } else {
1954         iter = children = D::children(root);
1955     }
1957     while ( iter && !found ) {
1958         SPObject *object=D::object(iter);
1959         if (desktop->isLayer(object)) {
1960             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1961                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1962             }
1963         } else if ( SP_IS_ITEM(object) &&
1964                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1965                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1966                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1967                     !desktop->isLayer(SP_ITEM(object)) )
1968         {
1969             found = SP_ITEM(object);
1970         }
1971         iter = D::next(iter);
1972     }
1974     D::dispose(children);
1976     return found;
1981 /**
1982  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1983  * \a item.
1984  */
1985 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1987     Geom::Rect dbox = desktop->get_display_area();
1988     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1990     if ( sbox && dbox.contains(*sbox) == false ) {
1991         Geom::Point const s_dt = sbox->midpoint();
1992         Geom::Point const s_w = desktop->d2w(s_dt);
1993         Geom::Point const d_dt = dbox.midpoint();
1994         Geom::Point const d_w = desktop->d2w(d_dt);
1995         Geom::Point const moved_w( d_w - s_w );
1996         gint const dx = (gint) moved_w[X];
1997         gint const dy = (gint) moved_w[Y];
1998         desktop->scroll_world(dx, dy);
1999     }
2003 void
2004 sp_selection_clone(SPDesktop *desktop)
2006     if (desktop == NULL)
2007         return;
2009     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2011     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2013     // check if something is selected
2014     if (selection->isEmpty()) {
2015         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2016         return;
2017     }
2019     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2021     selection->clear();
2023     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2024     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2026     GSList *newsel = NULL;
2028     while (reprs) {
2029         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2030         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2032         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2033         clone->setAttribute("x", "0", false);
2034         clone->setAttribute("y", "0", false);
2035         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2037         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2038         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2040         // add the new clone to the top of the original's parent
2041         parent->appendChild(clone);
2043         newsel = g_slist_prepend(newsel, clone);
2044         reprs = g_slist_remove(reprs, sel_repr);
2045         Inkscape::GC::release(clone);
2046     }
2048     // TRANSLATORS: only translate "string" in "context|string".
2049     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2050     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2051                      Q_("action|Clone"));
2053     selection->setReprList(newsel);
2055     g_slist_free(newsel);
2058 void
2059 sp_selection_relink(SPDesktop *desktop)
2061     if (!desktop)
2062         return;
2064     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2066     if (selection->isEmpty()) {
2067         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2068         return;
2069     }
2071     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2072     const gchar *newid = cm->getFirstObjectID();
2073     if (!newid) {
2074         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2075         return;
2076     }
2077     gchar *newref = g_strdup_printf("#%s", newid);
2079     // Get a copy of current selection.
2080     bool relinked = false;
2081     for (GSList *items = (GSList *) selection->itemList();
2082          items != NULL;
2083          items = items->next)
2084     {
2085         SPItem *item = (SPItem *) items->data;
2087         if (!SP_IS_USE(item))
2088             continue;
2090         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2091         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2092         relinked = true;
2093     }
2095     g_free(newref);
2097     if (!relinked) {
2098         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2099     } else {
2100         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2101                          _("Relink clone"));
2102     }
2106 void
2107 sp_selection_unlink(SPDesktop *desktop)
2109     if (!desktop)
2110         return;
2112     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2114     if (selection->isEmpty()) {
2115         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2116         return;
2117     }
2119     // Get a copy of current selection.
2120     GSList *new_select = NULL;
2121     bool unlinked = false;
2122     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2123          items != NULL;
2124          items = items->next)
2125     {
2126         SPItem *item = (SPItem *) items->data;
2128         if (SP_IS_TEXT(item)) {
2129             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2131             if (tspan) {
2132                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2133             }
2135             // Set unlink to true, and fall into the next if which
2136             // will include this text item in the new selection
2137             unlinked = true;
2138         }
2140         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2141             // keep the non-use item in the new selection
2142             new_select = g_slist_prepend(new_select, item);
2143             continue;
2144         }
2146         SPItem *unlink;
2147         if (SP_IS_USE(item)) {
2148             unlink = sp_use_unlink(SP_USE(item));
2149         } else /*if (SP_IS_TREF(use))*/ {
2150             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2151         }
2153         unlinked = true;
2154         // Add ungrouped items to the new selection.
2155         new_select = g_slist_prepend(new_select, unlink);
2156     }
2158     if (new_select) { // set new selection
2159         selection->clear();
2160         selection->setList(new_select);
2161         g_slist_free(new_select);
2162     }
2163     if (!unlinked) {
2164         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2165     }
2167     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2168                      _("Unlink clone"));
2171 void
2172 sp_select_clone_original(SPDesktop *desktop)
2174     if (desktop == NULL)
2175         return;
2177     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2179     SPItem *item = selection->singleItem();
2181     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.");
2183     // Check if other than two objects are selected
2184     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2185         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2186         return;
2187     }
2189     SPItem *original = NULL;
2190     if (SP_IS_USE(item)) {
2191         original = sp_use_get_original(SP_USE(item));
2192     } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2193         original = sp_offset_get_source(SP_OFFSET(item));
2194     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2195         original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2196     } else if (SP_IS_FLOWTEXT(item)) {
2197         original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2198     } else { // it's an object that we don't know what to do with
2199         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2200         return;
2201     }
2203     if (!original) {
2204         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2205         return;
2206     }
2208     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2209         if (SP_IS_DEFS(o)) {
2210             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2211             return;
2212         }
2213     }
2215     if (original) {
2216         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2217         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2218         if (highlight) {
2219             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2220             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2221             if ( a && b ) {
2222                 // draw a flashing line between the objects
2223                 SPCurve *curve = new SPCurve();
2224                 curve->moveto(a->midpoint());
2225                 curve->lineto(b->midpoint());
2227                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2228                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2229                 sp_canvas_item_show(canvasitem);
2230                 curve->unref();
2231                 desktop->add_temporary_canvasitem(canvasitem, 1000);
2232             }
2233         }
2235         selection->clear();
2236         selection->set(original);
2237         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2238             scroll_to_show_item(desktop, original);
2239         }
2240     }
2244 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2246     if (desktop == NULL)
2247         return;
2249     SPDocument *doc = sp_desktop_document(desktop);
2250     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2252     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2254     // check if something is selected
2255     if (selection->isEmpty()) {
2256         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2257         return;
2258     }
2260     sp_document_ensure_up_to_date(doc);
2261     Geom::OptRect r = selection->bounds();
2262     boost::optional<Geom::Point> c = selection->center();
2263     if ( !r || !c ) {
2264         return;
2265     }
2267     // calculate the transform to be applied to objects to move them to 0,0
2268     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2269     move_p[Geom::Y] = -move_p[Geom::Y];
2270     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2272     GSList *items = g_slist_copy((GSList *) selection->itemList());
2274     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2276     // bottommost object, after sorting
2277     SPObject *parent = SP_OBJECT_PARENT(items->data);
2279     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2281     // remember the position of the first item
2282     gint pos = SP_OBJECT_REPR(items->data)->position();
2283     (void)pos; // TODO check why this was remembered
2285     // create a list of duplicates
2286     GSList *repr_copies = NULL;
2287     for (GSList *i = items; i != NULL; i = i->next) {
2288         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2289         repr_copies = g_slist_prepend(repr_copies, dup);
2290     }
2292     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2294     if (apply) {
2295         // delete objects so that their clones don't get alerted; this object will be restored shortly
2296         for (GSList *i = items; i != NULL; i = i->next) {
2297             SPObject *item = SP_OBJECT(i->data);
2298             item->deleteObject(false);
2299         }
2300     }
2302     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2303     // without disturbing clones.
2304     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2305     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2306     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2307     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2309     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2310                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2311                                                                               Geom::Point(r->min()[Geom::X],
2312                                                                                           r->max()[Geom::Y]))))
2313                                              * parent_transform.inverse() ),
2314                                            parent_transform * move);
2315     (void)mark_id;
2317     // restore compensation setting
2318     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2321     g_slist_free(items);
2323     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2324                      _("Objects to marker"));
2327 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2328     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2329         for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2330             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2331         }
2332     } else {
2333         sp_item_convert_item_to_guides(item);
2335         if (deleteitem) {
2336             SP_OBJECT(item)->deleteObject(true);
2337         }
2338     }
2341 void sp_selection_to_guides(SPDesktop *desktop)
2343     if (desktop == NULL)
2344         return;
2346     SPDocument *doc = sp_desktop_document(desktop);
2347     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2348     // we need to copy the list because it gets reset when objects are deleted
2349     GSList *items = g_slist_copy((GSList *) selection->itemList());
2351     if (!items) {
2352         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2353         return;
2354     }
2356     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2357     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2358     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2360     for (GSList const *i = items; i != NULL; i = i->next) {
2361         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2362     }
2364     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2367 void
2368 sp_selection_tile(SPDesktop *desktop, bool apply)
2370     if (desktop == NULL)
2371         return;
2373     SPDocument *doc = sp_desktop_document(desktop);
2374     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2376     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2378     // check if something is selected
2379     if (selection->isEmpty()) {
2380         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2381         return;
2382     }
2384     sp_document_ensure_up_to_date(doc);
2385     Geom::OptRect r = selection->bounds();
2386     if ( !r ) {
2387         return;
2388     }
2390     // calculate the transform to be applied to objects to move them to 0,0
2391     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2392     move_p[Geom::Y] = -move_p[Geom::Y];
2393     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2395     GSList *items = g_slist_copy((GSList *) selection->itemList());
2397     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2399     // bottommost object, after sorting
2400     SPObject *parent = SP_OBJECT_PARENT(items->data);
2402     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2404     // remember the position of the first item
2405     gint pos = SP_OBJECT_REPR(items->data)->position();
2407     // create a list of duplicates
2408     GSList *repr_copies = NULL;
2409     for (GSList *i = items; i != NULL; i = i->next) {
2410         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2411         repr_copies = g_slist_prepend(repr_copies, dup);
2412     }
2413     // restore the z-order after prepends
2414     repr_copies = g_slist_reverse(repr_copies);
2416     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2418     if (apply) {
2419         // delete objects so that their clones don't get alerted; this object will be restored shortly
2420         for (GSList *i = items; i != NULL; i = i->next) {
2421             SPObject *item = SP_OBJECT(i->data);
2422             item->deleteObject(false);
2423         }
2424     }
2426     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2427     // without disturbing clones.
2428     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2429     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2430     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2431     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2433     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2434                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2435                                                                                             r->max()[Geom::Y]))))
2436                                          * to_2geom(parent_transform.inverse()) ),
2437                                        parent_transform * move);
2439     // restore compensation setting
2440     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2442     if (apply) {
2443         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2444         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2446         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2447         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2449         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2450         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2451         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2452         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2454         // restore parent and position
2455         SP_OBJECT_REPR(parent)->appendChild(rect);
2456         rect->setPosition(pos > 0 ? pos : 0);
2457         SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2459         Inkscape::GC::release(rect);
2461         selection->clear();
2462         selection->set(rectangle);
2463     }
2465     g_slist_free(items);
2467     sp_document_done(doc, SP_VERB_EDIT_TILE,
2468                      _("Objects to pattern"));
2471 void
2472 sp_selection_untile(SPDesktop *desktop)
2474     if (desktop == NULL)
2475         return;
2477     SPDocument *doc = sp_desktop_document(desktop);
2478     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2480     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2482     // check if something is selected
2483     if (selection->isEmpty()) {
2484         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2485         return;
2486     }
2488     GSList *new_select = NULL;
2490     bool did = false;
2492     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2493          items != NULL;
2494          items = items->next) {
2496         SPItem *item = (SPItem *) items->data;
2498         SPStyle *style = SP_OBJECT_STYLE(item);
2500         if (!style || !style->fill.isPaintserver())
2501             continue;
2503         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2505         if (!SP_IS_PATTERN(server))
2506             continue;
2508         did = true;
2510         SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2512         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2513         pat_transform *= item->transform;
2515         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2516             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2517             SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2519            // FIXME: relink clones to the new canvas objects
2520            // use SPObject::setid when mental finishes it to steal ids of
2522             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2523             sp_document_ensure_up_to_date(doc);
2525             Geom::Matrix transform( i->transform * pat_transform );
2526             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2528             new_select = g_slist_prepend(new_select, i);
2529         }
2531         SPCSSAttr *css = sp_repr_css_attr_new();
2532         sp_repr_css_set_property(css, "fill", "none");
2533         sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2534     }
2536     if (!did) {
2537         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2538     } else {
2539         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2540                          _("Pattern to objects"));
2541         selection->setList(new_select);
2542     }
2545 void
2546 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2548     if (selection->isEmpty()) {
2549         return;
2550     }
2552     GSList const *reprlst = selection->reprList();
2553     bool filename_search = TRUE;
2554     bool xdpi_search = TRUE;
2555     bool ydpi_search = TRUE;
2557     for (; reprlst != NULL &&
2558             filename_search &&
2559             xdpi_search &&
2560             ydpi_search;
2561         reprlst = reprlst->next) {
2562         gchar const *dpi_string;
2563         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2565         if (filename_search) {
2566             *filename = repr->attribute("inkscape:export-filename");
2567             if (*filename != NULL)
2568                 filename_search = FALSE;
2569         }
2571         if (xdpi_search) {
2572             dpi_string = NULL;
2573             dpi_string = repr->attribute("inkscape:export-xdpi");
2574             if (dpi_string != NULL) {
2575                 *xdpi = atof(dpi_string);
2576                 xdpi_search = FALSE;
2577             }
2578         }
2580         if (ydpi_search) {
2581             dpi_string = NULL;
2582             dpi_string = repr->attribute("inkscape:export-ydpi");
2583             if (dpi_string != NULL) {
2584                 *ydpi = atof(dpi_string);
2585                 ydpi_search = FALSE;
2586             }
2587         }
2588     }
2591 void
2592 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2594     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2595     gchar const *dpi_string;
2597     *filename = repr->attribute("inkscape:export-filename");
2599     dpi_string = NULL;
2600     dpi_string = repr->attribute("inkscape:export-xdpi");
2601     if (dpi_string != NULL) {
2602         *xdpi = atof(dpi_string);
2603     }
2605     dpi_string = NULL;
2606     dpi_string = repr->attribute("inkscape:export-ydpi");
2607     if (dpi_string != NULL) {
2608         *ydpi = atof(dpi_string);
2609     }
2612 void
2613 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2615     if (desktop == NULL)
2616         return;
2618     SPDocument *document = sp_desktop_document(desktop);
2619     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2621     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2623     // check if something is selected
2624     if (selection->isEmpty()) {
2625         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2626         return;
2627     }
2629     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2630     // set "busy" cursor
2631     desktop->setWaitingCursor();
2633     // Get the bounding box of the selection
2634     NRRect bbox;
2635     sp_document_ensure_up_to_date(document);
2636     selection->bounds(&bbox);
2637     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2638         desktop->clearWaitingCursor();
2639         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2640     }
2642     // List of the items to show; all others will be hidden
2643     GSList *items = g_slist_copy((GSList *) selection->itemList());
2645     // Sort items so that the topmost comes last
2646     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2648     // Generate a random value from the current time (you may create bitmap from the same object(s)
2649     // multiple times, and this is done so that they don't clash)
2650     GTimeVal cu;
2651     g_get_current_time(&cu);
2652     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2654     // Create the filename.
2655     gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2656                                             document->name,
2657                                             SP_OBJECT_REPR(items->data)->attribute("id"),
2658                                             current);
2659     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2660     // digits, and a few other chars, with "_"
2661     g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2663     // Build the complete path by adding document base dir, if set, otherwise home dir
2664     gchar * directory = NULL;
2665     if (SP_DOCUMENT_URI(document)) {
2666         directory = g_dirname(SP_DOCUMENT_URI(document));
2667     }
2668     if (directory == NULL) {
2669         directory = homedir_path(NULL);
2670     }
2671     gchar *filepath = g_build_filename(directory, basename, NULL);
2673     //g_print("%s\n", filepath);
2675     // Remember parent and z-order of the topmost one
2676     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2677     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2678     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2680     // Calculate resolution
2681     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2682     double res;
2683     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2684     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2685     if (0 < prefs_res) {
2686         // If it's given explicitly in prefs, take it
2687         res = prefs_res;
2688     } else if (0 < prefs_min) {
2689         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2690         res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2691     } else {
2692         float hint_xdpi = 0, hint_ydpi = 0;
2693         char const *hint_filename;
2694         // take resolution hint from the selected objects
2695         sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2696         if (hint_xdpi != 0) {
2697             res = hint_xdpi;
2698         } else {
2699             // take resolution hint from the document
2700             sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2701             if (hint_xdpi != 0) {
2702                 res = hint_xdpi;
2703             } else {
2704                 // if all else fails, take the default 90 dpi
2705                 res = PX_PER_IN;
2706             }
2707         }
2708     }
2710     // The width and height of the bitmap in pixels
2711     unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2712     unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2714     // Find out if we have to run an external filter
2715     gchar const *run = NULL;
2716     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2717     if (!filter.empty()) {
2718         // filter command is given;
2719         // see if we have a parameter to pass to it
2720         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2721         if (!param1.empty()) {
2722             if (param1[param1.length() - 1] == '%') {
2723                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2724                 gchar p1[256];
2725                 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2726                 // the first param is always the image filename, the second is param1
2727                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2728             } else {
2729                 // otherwise pass the param1 unchanged
2730                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2731             }
2732         } else {
2733             // run without extra parameter
2734             run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2735         }
2736     }
2738     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2739     Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2740     Geom::Matrix t;
2742     double shift_x = bbox.x0;
2743     double shift_y = bbox.y1;
2744     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2745         shift_x = round(shift_x);
2746         shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2747     }
2748     t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2750     // Do the export
2751     sp_export_png_file(document, filepath,
2752                        bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2753                        width, height, res, res,
2754                        (guint32) 0xffffff00,
2755                        NULL, NULL,
2756                        true,  /*bool force_overwrite,*/
2757                        items);
2759     g_slist_free(items);
2761     // Run filter, if any
2762     if (run) {
2763         g_print("Running external filter: %s\n", run);
2764         int retval;
2765         retval = system(run);
2766     }
2768     // Import the image back
2769     GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2770     if (pb) {
2771         // Create the repr for the image
2772         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2773         {
2774             repr->setAttribute("sodipodi:absref", filepath);
2775             gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2776             repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2777             g_free(abs_base);
2778         }
2779         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2780             sp_repr_set_svg_double(repr, "width", width);
2781             sp_repr_set_svg_double(repr, "height", height);
2782         } else {
2783             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2784             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2785         }
2787         // Write transform
2788         gchar *c=sp_svg_transform_write(t);
2789         repr->setAttribute("transform", c);
2790         g_free(c);
2792         // add the new repr to the parent
2793         parent->appendChild(repr);
2795         // move to the saved position
2796         repr->setPosition(pos > 0 ? pos + 1 : 1);
2798         // Set selection to the new image
2799         selection->clear();
2800         selection->add(repr);
2802         // Clean up
2803         Inkscape::GC::release(repr);
2804         gdk_pixbuf_unref(pb);
2806         // Complete undoable transaction
2807         sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2808                          _("Create bitmap"));
2809     }
2811     desktop->clearWaitingCursor();
2813     g_free(basename);
2814     g_free(filepath);
2817 /**
2818  * \brief Creates a mask or clipPath from selection
2819  * Two different modes:
2820  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2821  *       and is applied to current layer
2822  *  otherwise, topmost object is used as mask for other objects
2823  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2824  *
2825  */
2826 void
2827 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2829     if (desktop == NULL)
2830         return;
2832     SPDocument *doc = sp_desktop_document(desktop);
2833     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2835     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2837     // check if something is selected
2838     bool is_empty = selection->isEmpty();
2839     if ( apply_to_layer && is_empty) {
2840         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2841         return;
2842     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2843         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2844         return;
2845     }
2847     // FIXME: temporary patch to prevent crash!
2848     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2849     bool clone_with_original = selection_contains_both_clone_and_original(selection);
2850     if (clone_with_original) {
2851         return; // in this version, you cannot clip/mask an object with its own clone
2852     }
2853     // /END FIXME
2855     sp_document_ensure_up_to_date(doc);
2857     GSList *items = g_slist_copy((GSList *) selection->itemList());
2859     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2861     // create a list of duplicates
2862     GSList *mask_items = NULL;
2863     GSList *apply_to_items = NULL;
2864     GSList *items_to_delete = NULL;
2865     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2866     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2867     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2868     int grouping = prefs->getInt("/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE);
2870     if (apply_to_layer) {
2871         // all selected items are used for mask, which is applied to a layer
2872         apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2874         for (GSList *i = items; i != NULL; i = i->next) {
2875             Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2876             mask_items = g_slist_prepend(mask_items, dup);
2878             if (remove_original) {
2879                 SPObject *item = SP_OBJECT(i->data);
2880                 items_to_delete = g_slist_prepend(items_to_delete, item);
2881             }
2882         }
2883     } else if (!topmost) {
2884         // topmost item is used as a mask, which is applied to other items in a selection
2885         GSList *i = items;
2886         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2887         mask_items = g_slist_prepend(mask_items, dup);
2889         if (remove_original) {
2890             SPObject *item = SP_OBJECT(i->data);
2891             items_to_delete = g_slist_prepend(items_to_delete, item);
2892         }
2894         for (i = i->next; i != NULL; i = i->next) {
2895             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2896         }
2897     } else {
2898         GSList *i = NULL;
2899         for (i = items; NULL != i->next; i = i->next) {
2900             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2901         }
2903         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2904         mask_items = g_slist_prepend(mask_items, dup);
2906         if (remove_original) {
2907             SPObject *item = SP_OBJECT(i->data);
2908             items_to_delete = g_slist_prepend(items_to_delete, item);
2909         }
2910     }
2912     g_slist_free(items);
2913     items = NULL;
2914     
2915     if (apply_to_items && grouping == PREFS_MASKOBJECT_GROUPING_ALL) {
2916         // group all those objects into one group
2917         // and apply mask to that
2918         Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2919         
2920         // make a note we should ungroup this when unsetting mask
2921         group->setAttribute("inkscape:groupmode", "maskhelper");
2922         
2923         GSList *reprs_to_group = NULL;
2924         
2925         for (GSList *i = apply_to_items ; NULL != i ; i = i->next) {
2926                 reprs_to_group = g_slist_prepend(reprs_to_group, SP_OBJECT_REPR(i->data));
2927                 selection->remove(SP_OBJECT(i->data));
2928         }
2929         reprs_to_group = g_slist_reverse(reprs_to_group);
2930         
2931         sp_selection_group_impl(reprs_to_group, group, xml_doc, doc);
2932         
2933         g_slist_free(reprs_to_group);
2934         
2935         // apply clip/mask only to newly created group
2936         g_slist_free(apply_to_items);
2937         apply_to_items = NULL;
2938         apply_to_items = g_slist_prepend(apply_to_items, doc->getObjectByRepr(group));
2939         
2940         selection->add(group);
2941         
2942         Inkscape::GC::release(group);
2943     }
2945     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2946     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2947         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2948         // inverted object transform should be applied to a mask object,
2949         // as mask is calculated in user space (after applying transform)
2950         Geom::Matrix maskTransform(item->transform.inverse());
2952         GSList *mask_items_dup = NULL;
2953         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2954             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2955             mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2956         }
2958         gchar const *mask_id = NULL;
2959         if (apply_clip_path) {
2960             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2961         } else {
2962             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2963         }
2965         g_slist_free(mask_items_dup);
2966         mask_items_dup = NULL;
2968         Inkscape::XML::Node *current = SP_OBJECT_REPR(i->data);
2969         // Node to apply mask to
2970         Inkscape::XML::Node *apply_mask_to = current;
2971         
2972         if (grouping == PREFS_MASKOBJECT_GROUPING_SEPARATE) {
2973             // enclose current node in group, and apply crop/mask on that
2974             Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2975             // make a note we should ungroup this when unsetting mask
2976             group->setAttribute("inkscape:groupmode", "maskhelper");
2977             
2978             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
2979             gint position = current->position();
2980             selection->remove(current);
2981             current->parent()->appendChild(group);
2982             sp_repr_unparent(current);
2983             group->appendChild(spnew);
2984             group->setPosition(position);
2985             
2986             // Apply clip/mask to group instead
2987             apply_mask_to = group;
2988             
2989             selection->add(group);
2990             Inkscape::GC::release(spnew); 
2991             Inkscape::GC::release(group);
2992         }
2993         
2994         apply_mask_to->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2995         
2996     }
2998     g_slist_free(mask_items);
2999     g_slist_free(apply_to_items);
3001     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3002         SPObject *item = SP_OBJECT(i->data);
3003         item->deleteObject(false);
3004     }
3005     g_slist_free(items_to_delete);
3007     if (apply_clip_path)
3008         sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3009     else
3010         sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3013 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
3014     if (desktop == NULL)
3015         return;
3017     SPDocument *doc = sp_desktop_document(desktop);
3018     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
3019     Inkscape::Selection *selection = sp_desktop_selection(desktop);
3021     // check if something is selected
3022     if (selection->isEmpty()) {
3023         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3024         return;
3025     }
3027     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
3028     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
3029     bool ungroup_masked = prefs->getBool("/options/maskobject/ungrouping", true);
3030     sp_document_ensure_up_to_date(doc);
3032     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3033     std::map<SPObject*,SPItem*> referenced_objects;
3034     
3035     GSList *items_to_ungroup = NULL;
3036     
3037     // SPObject* refers to a group containing the clipped path or mask itself,
3038     // whereas SPItem* refers to the item being clipped or masked
3039     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
3040         if (remove_original) {
3041             // remember referenced mask/clippath, so orphaned masks can be moved back to document
3042             SPItem *item = reinterpret_cast<SPItem *>(i->data);
3043             Inkscape::URIReference *uri_ref = NULL;
3045             if (apply_clip_path) {
3046                 uri_ref = item->clip_ref;
3047             } else {
3048                 uri_ref = item->mask_ref;
3049             }
3051             // collect distinct mask object (and associate with item to apply transform)
3052             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3053                 referenced_objects[uri_ref->getObject()] = item;
3054             }
3055         }
3057         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3058         
3059         if (ungroup_masked && SP_IS_GROUP(i->data)) {
3060                 // if we had previously enclosed masked object in group,
3061                 // add it to list so we can ungroup it later
3062                 SPGroup *item = SP_GROUP(i->data);
3063                 
3064                 // ungroup only groups we created when setting clip/mask
3065                 if (item->layerMode() == SPGroup::MASK_HELPER) {
3066                     items_to_ungroup = g_slist_prepend(items_to_ungroup, item);
3067                 }
3068                 
3069         }
3070     }
3072     // restore mask objects into a document
3073     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3074         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
3075         GSList *items_to_move = NULL;
3076         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
3077             // Collect all clipped paths and masks within a single group
3078             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3079             items_to_move = g_slist_prepend(items_to_move, copy);
3080         }
3082         if (!obj->isReferenced()) {
3083             // delete from defs if no other object references this mask
3084             obj->deleteObject(false);
3085         }
3087         // remember parent and position of the item to which the clippath/mask was applied
3088         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3089         gint pos = SP_OBJECT_REPR((*it).second)->position();
3091         // Iterate through all clipped paths / masks
3092         for (GSList *i = items_to_move; NULL != i; i = i->next) {
3093             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3095             // insert into parent, restore pos
3096             parent->appendChild(repr);
3097             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3099             SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3100             selection->add(repr);
3102             // transform mask, so it is moved the same spot where mask was applied
3103             Geom::Matrix transform(mask_item->transform);
3104             transform *= (*it).second->transform;
3105             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3106         }
3108         g_slist_free(items_to_move);
3109     }
3110     
3111     // ungroup marked groups added when setting mask
3112     for (GSList *i = items_to_ungroup ; NULL != i ; i = i->next) {
3113         selection->remove(SP_GROUP(i->data));
3114         GSList *children = NULL;
3115         sp_item_group_ungroup(SP_GROUP(i->data), &children, false);
3116         selection->addList(children);
3117         g_slist_free(children);
3118     }
3119     
3120     g_slist_free(items_to_ungroup);
3122     if (apply_clip_path)
3123         sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3124     else
3125         sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3128 /**
3129  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3130  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3131  * \return true if an undoable change should be recorded.
3132  */
3133 bool
3134 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3136     g_return_val_if_fail(desktop != NULL, false);
3137     SPDocument *doc = sp_desktop_document(desktop);
3139     g_return_val_if_fail(doc != NULL, false);
3140     g_return_val_if_fail(desktop->selection != NULL, false);
3142     if (desktop->selection->isEmpty()) {
3143         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3144         return false;
3145     }
3146     Geom::OptRect const bbox(desktop->selection->bounds());
3147     if (bbox) {
3148         doc->fitToRect(*bbox, with_margins);
3149         return true;
3150     } else {
3151         return false;
3152     }
3155 /**
3156  * Fit canvas to the bounding box of the selection, as an undoable action.
3157  */
3158 void
3159 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3161     if (fit_canvas_to_selection(desktop)) {
3162         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3163                          _("Fit Page to Selection"));
3164     }
3167 /**
3168  * \param with_margins margins defined in the xml under <sodipodi:namedview>
3169  *                     "fit-margin-..." attributes.  See SPDocument::fitToRect.
3170  */
3171 bool
3172 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3174     g_return_val_if_fail(doc != NULL, false);
3176     sp_document_ensure_up_to_date(doc);
3177     SPItem const *const root = SP_ITEM(doc->root);
3178     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
3179     if (bbox) {
3180         doc->fitToRect(*bbox, with_margins);
3181         return true;
3182     } else {
3183         return false;
3184     }
3187 void
3188 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3190     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3191         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3192                          _("Fit Page to Drawing"));
3193     }
3196 /**
3197  * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3198  * "fit-margin-..." attributes.  See SPDocument::fitToRect and
3199  * ui/dialog/page-sizer.
3200  */
3201 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3202     g_return_if_fail(desktop != NULL);
3203     SPDocument *doc = sp_desktop_document(desktop);
3205     g_return_if_fail(doc != NULL);
3206     g_return_if_fail(desktop->selection != NULL);
3208     bool const changed = ( desktop->selection->isEmpty()
3209                            ? fit_canvas_to_drawing(doc, true)
3210                            : fit_canvas_to_selection(desktop, true) );
3211     if (changed) {
3212         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3213                          _("Fit Page to Selection or Drawing"));
3214     }
3215 };
3217 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3218     // don't operate on layers
3219     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3220         f(SP_ITEM(root), desktop);
3221     }
3222     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3223         //don't recurse into locked layers
3224         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3225             itemtree_map(f, iter, desktop);
3226         }
3227     }
3230 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3231     if (item->isLocked()) {
3232         item->setLocked(FALSE);
3233     }
3236 static void unhide(SPItem *item, SPDesktop *desktop) {
3237     if (desktop->itemIsHidden(item)) {
3238         item->setExplicitlyHidden(FALSE);
3239     }
3242 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3243     if (!dt) return;
3245     SPObject *root;
3246     if (layer_only) {
3247         root = dt->currentLayer();
3248     } else {
3249         root = dt->currentRoot();
3250     }
3252     itemtree_map(f, root, dt);
3255 void unlock_all(SPDesktop *dt) {
3256     process_all(&unlock, dt, true);
3259 void unlock_all_in_all_layers(SPDesktop *dt) {
3260     process_all(&unlock, dt, false);
3263 void unhide_all(SPDesktop *dt) {
3264     process_all(&unhide, dt, true);
3267 void unhide_all_in_all_layers(SPDesktop *dt) {
3268     process_all(&unhide, dt, false);
3272 /*
3273   Local Variables:
3274   mode:c++
3275   c-file-style:"stroustrup"
3276   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3277   indent-tabs-mode:nil
3278   fill-column:99
3279   End:
3280 */
3281 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :