Code

Major simplification of 3D box code.
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /** @file
4  * @brief Miscellanous operations on selected items
5  */
6 /* Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "desktop.h"
29 #include "desktop-style.h"
30 #include "dir-util.h"
31 #include "selection.h"
32 #include "tools-switch.h"
33 #include "desktop-handles.h"
34 #include "message-stack.h"
35 #include "sp-item-transform.h"
36 #include "marker.h"
37 #include "sp-use.h"
38 #include "sp-textpath.h"
39 #include "sp-tspan.h"
40 #include "sp-tref.h"
41 #include "sp-flowtext.h"
42 #include "sp-flowregion.h"
43 #include "text-editing.h"
44 #include "text-context.h"
45 #include "connector-context.h"
46 #include "sp-path.h"
47 #include "sp-conn-end.h"
48 #include "dropper-context.h"
49 #include <glibmm/i18n.h>
50 #include "libnr/nr-matrix-rotate-ops.h"
51 #include "libnr/nr-matrix-translate-ops.h"
52 #include "libnr/nr-scale-ops.h"
53 #include <libnr/nr-matrix-ops.h>
54 #include <2geom/transforms.h>
55 #include "xml/repr.h"
56 #include "xml/rebase-hrefs.h"
57 #include "style.h"
58 #include "document-private.h"
59 #include "sp-gradient.h"
60 #include "sp-gradient-reference.h"
61 #include "sp-linear-gradient-fns.h"
62 #include "sp-pattern.h"
63 #include "sp-radial-gradient-fns.h"
64 #include "sp-namedview.h"
65 #include "preferences.h"
66 #include "sp-offset.h"
67 #include "sp-clippath.h"
68 #include "sp-mask.h"
69 #include "file.h"
70 #include "helper/png-write.h"
71 #include "layer-fns.h"
72 #include "context-fns.h"
73 #include <map>
74 #include <cstring>
75 #include <string>
76 #include "helper/units.h"
77 #include "sp-item.h"
78 #include "box3d.h"
79 #include "persp3d.h"
80 #include "unit-constants.h"
81 #include "xml/simple-document.h"
82 #include "sp-filter-reference.h"
83 #include "gradient-drag.h"
84 #include "uri-references.h"
85 #include "libnr/nr-convert2geom.h"
86 #include "display/curve.h"
87 #include "display/canvas-bpath.h"
88 #include "inkscape-private.h"
90 // For clippath editing
91 #include "tools-switch.h"
92 #include "shape-editor.h"
93 #include "node-context.h"
94 #include "nodepath.h"
96 #include "ui/clipboard.h"
98 using Geom::X;
99 using Geom::Y;
101 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
102 because the layer manipulation code uses them. It should be rewritten specifically
103 for that purpose. */
105 /**
106  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
107  * then prepends the copy to 'clip'.
108  */
109 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
111     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
113     // copy complete inherited style
114     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
115     sp_repr_css_set(copy, css, "style");
116     sp_repr_css_attr_unref(css);
118     // write the complete accumulated transform passed to us
119     // (we're dealing with unattached repr, so we write to its attr
120     // instead of using sp_item_set_transform)
121     gchar *affinestr=sp_svg_transform_write(full_t);
122     copy->setAttribute("transform", affinestr);
123     g_free(affinestr);
125     *clip = g_slist_prepend(*clip, copy);
128 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
130     // Sort items:
131     GSList *sorted_items = g_slist_copy((GSList *) items);
132     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
134     // Copy item reprs:
135     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
136         sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
137     }
139     *clip = g_slist_reverse(*clip);
140     g_slist_free((GSList *) sorted_items);
143 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
145     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
147     GSList *copied = NULL;
148     // add objects to document
149     for (GSList *l = *clip; l != NULL; l = l->next) {
150         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
151         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
153         // premultiply the item transform by the accumulated parent transform in the paste layer
154         Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
155         if (!local.isIdentity()) {
156             gchar const *t_str = copy->attribute("transform");
157             Geom::Matrix item_t(Geom::identity());
158             if (t_str)
159                 sp_svg_transform_read(t_str, &item_t);
160             item_t *= local.inverse();
161             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
162             gchar *affinestr=sp_svg_transform_write(item_t);
163             copy->setAttribute("transform", affinestr);
164             g_free(affinestr);
165         }
167         parent->appendChildRepr(copy);
168         copied = g_slist_prepend(copied, copy);
169         Inkscape::GC::release(copy);
170     }
171     return copied;
174 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
176     for (GSList const *i = items ; i ; i = i->next ) {
177         sp_object_ref((SPObject *)i->data, NULL);
178     }
179     for (GSList const *i = items; i != NULL; i = i->next) {
180         SPItem *item = (SPItem *) i->data;
181         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
182         sp_object_unref((SPObject *)item, NULL);
183     }
187 void sp_selection_delete(SPDesktop *desktop)
189     if (desktop == NULL) {
190         return;
191     }
193     if (tools_isactive(desktop, TOOLS_TEXT))
194         if (sp_text_delete_selection(desktop->event_context)) {
195             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
196                              _("Delete text"));
197             return;
198         }
200     Inkscape::Selection *selection = sp_desktop_selection(desktop);
202     // check if something is selected
203     if (selection->isEmpty()) {
204         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
205         return;
206     }
208     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
209     selection->clear();
210     sp_selection_delete_impl(selected);
211     g_slist_free((GSList *) selected);
213     /* a tool may have set up private information in it's selection context
214      * that depends on desktop items.  I think the only sane way to deal with
215      * this currently is to reset the current tool, which will reset it's
216      * associated selection context.  For example: deleting an object
217      * while moving it around the canvas.
218      */
219     tools_switch( desktop, tools_active( desktop ) );
221     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
222                      _("Delete"));
225 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
227     if (!obj)
228         return;
230     ids.push_back(SP_OBJECT_ID(obj));
232     if (SP_IS_GROUP(obj)) {
233         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
234             add_ids_recursive(ids, child);
235         }
236     }
239 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
241     if (desktop == NULL)
242         return;
244     SPDocument *doc = desktop->doc();
245     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
246     Inkscape::Selection *selection = sp_desktop_selection(desktop);
248     // check if something is selected
249     if (selection->isEmpty()) {
250         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
251         return;
252     }
254     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
256     selection->clear();
258     // sorting items from different parents sorts each parent's subset without possibly mixing
259     // them, just what we need
260     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
262     GSList *newsel = NULL;
264     std::vector<const gchar *> old_ids;
265     std::vector<const gchar *> new_ids;
266     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
267     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
269     while (reprs) {
270         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
271         Inkscape::XML::Node *parent = old_repr->parent();
272         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
274         parent->appendChild(copy);
276         if (relink_clones) {
277             SPObject *old_obj = doc->getObjectByRepr(old_repr);
278             SPObject *new_obj = doc->getObjectByRepr(copy);
279             add_ids_recursive(old_ids, old_obj);
280             add_ids_recursive(new_ids, new_obj);
281         }
283         newsel = g_slist_prepend(newsel, copy);
284         reprs = g_slist_remove(reprs, reprs->data);
285         Inkscape::GC::release(copy);
286     }
288     if (relink_clones) {
290         g_assert(old_ids.size() == new_ids.size());
292         for (unsigned int i = 0; i < old_ids.size(); i++) {
293             const gchar *id = old_ids[i];
294             SPObject *old_clone = doc->getObjectById(id);
295             if (SP_IS_USE(old_clone)) {
296                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
297                 if (!orig) // orphaned
298                     continue;
299                 for (unsigned int j = 0; j < old_ids.size(); j++) {
300                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
301                         // we have both orig and clone in selection, relink
302                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
303                         gchar *newref = g_strdup_printf("#%s", new_ids[j]);
304                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
305                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
306                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
307                         g_free(newref);
308                     }
309                 }
310             }
311         }
312     }
315     if ( !suppressDone ) {
316         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
317                          _("Duplicate"));
318     }
320     selection->setReprList(newsel);
322     g_slist_free(newsel);
325 void sp_edit_clear_all(SPDesktop *dt)
327     if (!dt)
328         return;
330     SPDocument *doc = sp_desktop_document(dt);
331     sp_desktop_selection(dt)->clear();
333     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
334     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
336     while (items) {
337         SP_OBJECT(items->data)->deleteObject();
338         items = g_slist_remove(items, items->data);
339     }
341     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
342                      _("Delete all"));
345 GSList *
346 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
348     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
349         if (SP_IS_ITEM(child) &&
350             !desktop->isLayer(SP_ITEM(child)) &&
351             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
352             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
353             (!exclude || !g_slist_find((GSList *) exclude, child))
354             )
355         {
356             list = g_slist_prepend(list, SP_ITEM(child));
357         }
359         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
360             list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
361         }
362     }
364     return list;
367 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
369     if (!dt)
370         return;
372     Inkscape::Selection *selection = sp_desktop_selection(dt);
374     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
376     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
377     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
378     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
379     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
381     GSList *items = NULL;
383     GSList const *exclude = NULL;
384     if (invert) {
385         exclude = selection->itemList();
386     }
388     if (force_all_layers)
389         inlayer = PREFS_SELECTION_ALL;
391     switch (inlayer) {
392         case PREFS_SELECTION_LAYER: {
393         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
394              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
395         return;
397         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
399         for (GSList *i = all_items; i; i = i->next) {
400             SPItem *item = SP_ITEM(i->data);
402             if (item && (!onlysensitive || !item->isLocked())) {
403                 if (!onlyvisible || !dt->itemIsHidden(item)) {
404                     if (!dt->isLayer(item)) {
405                         if (!invert || !g_slist_find((GSList *) exclude, item)) {
406                             items = g_slist_prepend(items, item); // leave it in the list
407                         }
408                     }
409                 }
410             }
411         }
413         g_slist_free(all_items);
414             break;
415         }
416         case PREFS_SELECTION_LAYER_RECURSIVE: {
417             items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
418             break;
419         }
420         default: {
421         items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
422             break;
423     }
424     }
426     selection->setList(items);
428     if (items) {
429         g_slist_free(items);
430     }
433 void sp_edit_select_all(SPDesktop *desktop)
435     sp_edit_select_all_full(desktop, false, false);
438 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
440     sp_edit_select_all_full(desktop, true, false);
443 void sp_edit_invert(SPDesktop *desktop)
445     sp_edit_select_all_full(desktop, false, true);
448 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
450     sp_edit_select_all_full(desktop, true, true);
453 void sp_selection_group(SPDesktop *desktop)
455     if (desktop == NULL)
456         return;
458     SPDocument *doc = sp_desktop_document(desktop);
459     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
461     Inkscape::Selection *selection = sp_desktop_selection(desktop);
463     // Check if something is selected.
464     if (selection->isEmpty()) {
465         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
466         return;
467     }
469     GSList const *l = (GSList *) selection->reprList();
471     GSList *p = g_slist_copy((GSList *) l);
473     selection->clear();
475     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
477     // Remember the position and parent of the topmost object.
478     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
479     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
481     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
483     while (p) {
484         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
486         if (current->parent() == topmost_parent) {
487             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
488             sp_repr_unparent(current);
489             group->appendChild(spnew);
490             Inkscape::GC::release(spnew);
491             topmost --; // only reduce count for those items deleted from topmost_parent
492         } else { // move it to topmost_parent first
493             GSList *temp_clip = NULL;
495             // At this point, current may already have no item, due to its being a clone whose original is already moved away
496             // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
497             gchar const *t_str = current->attribute("transform");
498             Geom::Matrix item_t(Geom::identity());
499             if (t_str)
500                 sp_svg_transform_read(t_str, &item_t);
501             item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
502             // FIXME: when moving both clone and original from a transformed group (either by
503             // grouping into another parent, or by cut/paste) the transform from the original's
504             // parent becomes embedded into original itself, and this affects its clones. Fix
505             // this by remembering the transform diffs we write to each item into an array and
506             // then, if this is clone, looking up its original in that array and pre-multiplying
507             // it by the inverse of that original's transform diff.
509             sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
510             sp_repr_unparent(current);
512             // paste into topmost_parent (temporarily)
513             GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
514             if (temp_clip) g_slist_free(temp_clip);
515             if (copied) { // if success,
516                 // take pasted object (now in topmost_parent)
517                 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
518                 // make a copy
519                 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
520                 // remove pasted
521                 sp_repr_unparent(in_topmost);
522                 // put its copy into group
523                 group->appendChild(spnew);
524                 Inkscape::GC::release(spnew);
525                 g_slist_free(copied);
526             }
527         }
528         p = g_slist_remove(p, current);
529     }
531     // Add the new group to the topmost members' parent
532     topmost_parent->appendChild(group);
534     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
535     group->setPosition(topmost + 1);
537     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
538                      _("Group"));
540     selection->set(group);
541     Inkscape::GC::release(group);
544 void sp_selection_ungroup(SPDesktop *desktop)
546     if (desktop == NULL)
547         return;
549     Inkscape::Selection *selection = sp_desktop_selection(desktop);
551     if (selection->isEmpty()) {
552         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
553         return;
554     }
556     GSList *items = g_slist_copy((GSList *) selection->itemList());
557     selection->clear();
559     // Get a copy of current selection.
560     GSList *new_select = NULL;
561     bool ungrouped = false;
562     for (GSList *i = items;
563          i != NULL;
564          i = i->next)
565     {
566         SPItem *group = (SPItem *) i->data;
568         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
569         if (!SP_IS_OBJECT(group)) {
570             continue;
571         }
573         /* We do not allow ungrouping <svg> etc. (lauris) */
574         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
575             // keep the non-group item in the new selection
576             selection->add(group);
577             continue;
578         }
580         GSList *children = NULL;
581         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
582         sp_item_group_ungroup(SP_GROUP(group), &children, false);
583         ungrouped = true;
584         // Add ungrouped items to the new selection.
585         new_select = g_slist_concat(new_select, children);
586     }
588     if (new_select) { // Set new selection.
589         selection->addList(new_select);
590         g_slist_free(new_select);
591     }
592     if (!ungrouped) {
593         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
594     }
596     g_slist_free(items);
598     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
599                      _("Ungroup"));
602 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
603 GSList *
604 sp_degroup_list(GSList *items)
606     GSList *out = NULL;
607     bool has_groups = false;
608     for (GSList *item = items; item; item = item->next) {
609         if (!SP_IS_GROUP(item->data)) {
610             out = g_slist_prepend(out, item->data);
611         } else {
612             has_groups = true;
613             GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
614             for (GSList *member = members; member; member = member->next) {
615                 out = g_slist_prepend(out, member->data);
616             }
617             g_slist_free(members);
618         }
619     }
620     out = g_slist_reverse(out);
621     g_slist_free(items);
623     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
624         out = sp_degroup_list(out);
625     }
627     return out;
631 /** If items in the list have a common parent, return it, otherwise return NULL */
632 static SPGroup *
633 sp_item_list_common_parent_group(GSList const *items)
635     if (!items) {
636         return NULL;
637     }
638     SPObject *parent = SP_OBJECT_PARENT(items->data);
639     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
640     if (!SP_IS_GROUP(parent)) {
641         return NULL;
642     }
643     for (items = items->next; items; items = items->next) {
644         if (SP_OBJECT_PARENT(items->data) != parent) {
645             return NULL;
646         }
647     }
649     return SP_GROUP(parent);
652 /** Finds out the minimum common bbox of the selected items. */
653 static Geom::OptRect
654 enclose_items(GSList const *items)
656     g_assert(items != NULL);
658     Geom::OptRect r;
659     for (GSList const *i = items; i; i = i->next) {
660         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
661     }
662     return r;
665 SPObject *
666 prev_sibling(SPObject *child)
668     SPObject *parent = SP_OBJECT_PARENT(child);
669     if (!SP_IS_GROUP(parent)) {
670         return NULL;
671     }
672     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
673         if (i->next == child)
674             return i;
675     }
676     return NULL;
679 void
680 sp_selection_raise(SPDesktop *desktop)
682     if (!desktop)
683         return;
685     Inkscape::Selection *selection = sp_desktop_selection(desktop);
687     GSList const *items = (GSList *) selection->itemList();
688     if (!items) {
689         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
690         return;
691     }
693     SPGroup const *group = sp_item_list_common_parent_group(items);
694     if (!group) {
695         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
696         return;
697     }
699     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
701     /* Construct reverse-ordered list of selected children. */
702     GSList *rev = g_slist_copy((GSList *) items);
703     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
705     // Determine the common bbox of the selected items.
706     Geom::OptRect selected = enclose_items(items);
708     // Iterate over all objects in the selection (starting from top).
709     if (selected) {
710         while (rev) {
711             SPObject *child = SP_OBJECT(rev->data);
712             // for each selected object, find the next sibling
713             for (SPObject *newref = child->next; newref; newref = newref->next) {
714                 // if the sibling is an item AND overlaps our selection,
715                 if (SP_IS_ITEM(newref)) {
716                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
717                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
718                         // AND if it's not one of our selected objects,
719                         if (!g_slist_find((GSList *) items, newref)) {
720                             // move the selected object after that sibling
721                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
722                         }
723                         break;
724                     }
725                 }
726             }
727             rev = g_slist_remove(rev, child);
728         }
729     } else {
730         g_slist_free(rev);
731     }
733     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
734                      //TRANSLATORS: only translate "string" in "context|string".
735                      // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
736                      // "Raise" means "to raise an object" in the undo history
737                      Q_("undo_action|Raise"));
740 void sp_selection_raise_to_top(SPDesktop *desktop)
742     if (desktop == NULL)
743         return;
745     SPDocument *document = sp_desktop_document(desktop);
746     Inkscape::Selection *selection = sp_desktop_selection(desktop);
748     if (selection->isEmpty()) {
749         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
750         return;
751     }
753     GSList const *items = (GSList *) selection->itemList();
755     SPGroup const *group = sp_item_list_common_parent_group(items);
756     if (!group) {
757         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
758         return;
759     }
761     GSList *rl = g_slist_copy((GSList *) selection->reprList());
762     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
764     for (GSList *l = rl; l != NULL; l = l->next) {
765         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
766         repr->setPosition(-1);
767     }
769     g_slist_free(rl);
771     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
772                      _("Raise to top"));
775 void
776 sp_selection_lower(SPDesktop *desktop)
778     if (desktop == NULL)
779         return;
781     Inkscape::Selection *selection = sp_desktop_selection(desktop);
783     GSList const *items = (GSList *) selection->itemList();
784     if (!items) {
785         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
786         return;
787     }
789     SPGroup const *group = sp_item_list_common_parent_group(items);
790     if (!group) {
791         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
792         return;
793     }
795     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
797     // Determine the common bbox of the selected items.
798     Geom::OptRect selected = enclose_items(items);
800     /* Construct direct-ordered list of selected children. */
801     GSList *rev = g_slist_copy((GSList *) items);
802     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
803     rev = g_slist_reverse(rev);
805     // Iterate over all objects in the selection (starting from top).
806     if (selected) {
807         while (rev) {
808             SPObject *child = SP_OBJECT(rev->data);
809             // for each selected object, find the prev sibling
810             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
811                 // if the sibling is an item AND overlaps our selection,
812                 if (SP_IS_ITEM(newref)) {
813                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
814                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
815                         // AND if it's not one of our selected objects,
816                         if (!g_slist_find((GSList *) items, newref)) {
817                             // move the selected object before that sibling
818                             SPObject *put_after = prev_sibling(newref);
819                             if (put_after)
820                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
821                             else
822                                 SP_OBJECT_REPR(child)->setPosition(0);
823                         }
824                         break;
825                     }
826                 }
827             }
828             rev = g_slist_remove(rev, child);
829         }
830     } else {
831         g_slist_free(rev);
832     }
834     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
835                      _("Lower"));
838 void sp_selection_lower_to_bottom(SPDesktop *desktop)
840     if (desktop == NULL)
841         return;
843     SPDocument *document = sp_desktop_document(desktop);
844     Inkscape::Selection *selection = sp_desktop_selection(desktop);
846     if (selection->isEmpty()) {
847         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
848         return;
849     }
851     GSList const *items = (GSList *) selection->itemList();
853     SPGroup const *group = sp_item_list_common_parent_group(items);
854     if (!group) {
855         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
856         return;
857     }
859     GSList *rl;
860     rl = g_slist_copy((GSList *) selection->reprList());
861     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
862     rl = g_slist_reverse(rl);
864     for (GSList *l = rl; l != NULL; l = l->next) {
865         gint minpos;
866         SPObject *pp, *pc;
867         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
868         pp = document->getObjectByRepr(sp_repr_parent(repr));
869         minpos = 0;
870         g_assert(SP_IS_GROUP(pp));
871         pc = sp_object_first_child(pp);
872         while (!SP_IS_ITEM(pc)) {
873             minpos += 1;
874             pc = pc->next;
875         }
876         repr->setPosition(minpos);
877     }
879     g_slist_free(rl);
881     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
882                      _("Lower to bottom"));
885 void
886 sp_undo(SPDesktop *desktop, SPDocument *)
888         if (!sp_document_undo(sp_desktop_document(desktop)))
889             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
892 void
893 sp_redo(SPDesktop *desktop, SPDocument *)
895         if (!sp_document_redo(sp_desktop_document(desktop)))
896             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
899 void sp_selection_cut(SPDesktop *desktop)
901     sp_selection_copy();
902     sp_selection_delete(desktop);
905 /**
906  * \pre item != NULL
907  */
908 SPCSSAttr *
909 take_style_from_item(SPItem *item)
911     // write the complete cascaded style, context-free
912     SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
913     if (css == NULL)
914         return NULL;
916     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
917         (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
918         // if this is a text with exactly one tspan child, merge the style of that tspan as well
919         // If this is a group, merge the style of its topmost (last) child with style
920         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
921             if (SP_OBJECT_STYLE(last_element) != NULL) {
922                 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
923                 if (temp) {
924                     sp_repr_css_merge(css, temp);
925                     sp_repr_css_attr_unref(temp);
926                 }
927                 break;
928             }
929         }
930     }
931     if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
932         // do not copy text properties from non-text objects, it's confusing
933         css = sp_css_attr_unset_text(css);
934     }
936     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
937     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
938     if (ex != 1.0) {
939         css = sp_css_attr_scale(css, ex);
940     }
942     return css;
946 void sp_selection_copy()
948     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
949     cm->copy();
952 void sp_selection_paste(SPDesktop *desktop, bool in_place)
954     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
955     if (cm->paste(in_place))
956         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
959 void sp_selection_paste_style(SPDesktop *desktop)
961     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
962     if (cm->pasteStyle())
963         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
967 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
969     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
970     if (cm->pastePathEffect())
971         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
972                          _("Paste live path effect"));
976 void sp_selection_remove_livepatheffect_impl(SPItem *item)
978     if ( item && SP_IS_LPE_ITEM(item) &&
979          sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
980         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
981     }
984 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
986     if (desktop == NULL) return;
988     Inkscape::Selection *selection = sp_desktop_selection(desktop);
990     // check if something is selected
991     if (selection->isEmpty()) {
992         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
993         return;
994     }
996     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
997         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
999         sp_selection_remove_livepatheffect_impl(item);
1001     }
1003     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1004                      _("Remove live path effect"));
1007 void sp_selection_remove_filter(SPDesktop *desktop)
1009     if (desktop == NULL) return;
1011     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1013     // check if something is selected
1014     if (selection->isEmpty()) {
1015         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1016         return;
1017     }
1019     SPCSSAttr *css = sp_repr_css_attr_new();
1020     sp_repr_css_unset_property(css, "filter");
1021     sp_desktop_set_style(desktop, css);
1022     sp_repr_css_attr_unref(css);
1024     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1025                      _("Remove filter"));
1029 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1031     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1032     if (cm->pasteSize(false, apply_x, apply_y))
1033         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1034                          _("Paste size"));
1037 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1039     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1040     if (cm->pasteSize(true, apply_x, apply_y))
1041         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1042                          _("Paste size separately"));
1045 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1047     Inkscape::Selection *selection = sp_desktop_selection(dt);
1049     // check if something is selected
1050     if (selection->isEmpty()) {
1051         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1052         return;
1053     }
1055     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1057     bool no_more = false; // Set to true, if no more layers above
1058     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1059     if (next) {
1060         GSList *temp_clip = NULL;
1061         sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1062         sp_selection_delete_impl(items, false, false);
1063         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1064         GSList *copied;
1065         if (next) {
1066             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1067         } else {
1068             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1069             no_more = true;
1070         }
1071         selection->setReprList((GSList const *) copied);
1072         g_slist_free(copied);
1073         if (temp_clip) g_slist_free(temp_clip);
1074         if (next) dt->setCurrentLayer(next);
1075         if ( !suppressDone ) {
1076             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1077                              _("Raise to next layer"));
1078         }
1079     } else {
1080         no_more = true;
1081     }
1083     if (no_more) {
1084         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1085     }
1087     g_slist_free((GSList *) items);
1090 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1092     Inkscape::Selection *selection = sp_desktop_selection(dt);
1094     // check if something is selected
1095     if (selection->isEmpty()) {
1096         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1097         return;
1098     }
1100     GSList const *items = g_slist_copy((GSList *) selection->itemList());
1102     bool no_more = false; // Set to true, if no more layers below
1103     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1104     if (next) {
1105         GSList *temp_clip = NULL;
1106         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
1107         sp_selection_delete_impl(items, false, false);
1108         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1109         GSList *copied;
1110         if (next) {
1111             copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1112         } else {
1113             copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1114             no_more = true;
1115         }
1116         selection->setReprList((GSList const *) copied);
1117         g_slist_free(copied);
1118         if (temp_clip) g_slist_free(temp_clip);
1119         if (next) dt->setCurrentLayer(next);
1120         if ( !suppressDone ) {
1121             sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1122                              _("Lower to previous layer"));
1123         }
1124     } else {
1125         no_more = true;
1126     }
1128     if (no_more) {
1129         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1130     }
1132     g_slist_free((GSList *) items);
1135 bool
1136 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1138     bool contains_original = false;
1140     bool is_use = SP_IS_USE(item);
1141     SPItem *item_use = item;
1142     SPItem *item_use_first = item;
1143     while (is_use && item_use && !contains_original)
1144     {
1145         item_use = sp_use_get_original(SP_USE(item_use));
1146         contains_original |= selection->includes(item_use);
1147         if (item_use == item_use_first)
1148             break;
1149         is_use = SP_IS_USE(item_use);
1150     }
1152     // If it's a tref, check whether the object containing the character
1153     // data is part of the selection
1154     if (!contains_original && SP_IS_TREF(item)) {
1155         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1156     }
1158     return contains_original;
1162 bool
1163 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1165     bool clone_with_original = false;
1166     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1167         SPItem *item = SP_ITEM(l->data);
1168         clone_with_original |= selection_contains_original(item, selection);
1169         if (clone_with_original)
1170             break;
1171     }
1172     return clone_with_original;
1175 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1176 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1177 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1178 that case, items are already in the new position, but the repr is in the old, and this function
1179 then simply updates the repr from item->transform.
1180  */
1181 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1183     if (selection->isEmpty())
1184         return;
1186     // For each perspective with a box in selection, check whether all boxes are selected and
1187     // unlink all non-selected boxes.
1188     Persp3D *persp;
1189     Persp3D *transf_persp;
1190     std::list<Persp3D *> plist = selection->perspList();
1191     for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1192         persp = (Persp3D *) (*i);
1194         if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1195             std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1197             // create a new perspective as a copy of the current one and link the selected boxes to it
1198             transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1200             for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1201                 box3d_switch_perspectives(*b, persp, transf_persp);
1202         } else {
1203             transf_persp = persp;
1204         }
1206         persp3d_apply_affine_transformation(transf_persp, affine);
1207     }
1209     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1210         SPItem *item = SP_ITEM(l->data);
1212         Geom::Point old_center(0,0);
1213         if (set_i2d && item->isCenterSet())
1214             old_center = item->getCenter();
1216 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1217          At the time of writing, this is the only place to re-enable. */
1218         sp_item_update_cns(*item, selection->desktop());
1219 #endif
1221         // we're moving both a clone and its original or any ancestor in clone chain?
1222         bool transform_clone_with_original = selection_contains_original(item, selection);
1223         // ...both a text-on-path and its path?
1224         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)))) ));
1225         // ...both a flowtext and its frame?
1226         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)
1227         // ...both an offset and its source?
1228         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1230         // If we're moving a connector, we want to detach it
1231         // from shapes that aren't part of the selection, but
1232         // leave it attached if they are
1233         if (cc_item_is_connector(item)) {
1234             SPItem *attItem[2];
1235             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1237             for (int n = 0; n < 2; ++n) {
1238                 if (!selection->includes(attItem[n])) {
1239                     sp_conn_end_detach(item, n);
1240                 }
1241             }
1242         }
1244         // "clones are unmoved when original is moved" preference
1245         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1246         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1247         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1248         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1250         /* If this is a clone and it's selected along with its original, do not move it;
1251          * it will feel the transform of its original and respond to it itself.
1252          * Without this, a clone is doubly transformed, very unintuitive.
1253          *
1254          * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1255          * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1256          * Same for linked offset if we are also moving its source: do not move it. */
1257         if (transform_textpath_with_path || transform_offset_with_source) {
1258             // Restore item->transform field from the repr, in case it was changed by seltrans.
1259             sp_object_read_attr(SP_OBJECT(item), "transform");
1260         } else if (transform_flowtext_with_frame) {
1261             // apply the inverse of the region's transform to the <use> so that the flow remains
1262             // the same (even though the output itself gets transformed)
1263             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1264                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1265                     continue;
1266                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1267                     if (!SP_IS_USE(use)) continue;
1268                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1269                 }
1270             }
1271         } else if (transform_clone_with_original) {
1272             // We are transforming a clone along with its original. The below matrix juggling is
1273             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1274             // transform and its move compensation are both cancelled out.
1276             // restore item->transform field from the repr, in case it was changed by seltrans
1277             sp_object_read_attr(SP_OBJECT(item), "transform");
1279             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1280             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1281             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1282             Geom::Matrix t_inv = t.inverse();
1283             Geom::Matrix result = t_inv * item->transform * t;
1285             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1286                 // we need to cancel out the move compensation, too
1288                 // find out the clone move, same as in sp_use_move_compensate
1289                 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1290                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1292                 if (prefs_parallel) {
1293                     Geom::Matrix move = result * clone_move * t_inv;
1294                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1296                 } else if (prefs_unmoved) {
1297                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1298                     //    clone_move = Geom::identity();
1299                     Geom::Matrix move = result * clone_move;
1300                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1301                 }
1303             } else {
1304                 // just apply the result
1305                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1306             }
1308         } else {
1309             if (set_i2d) {
1310                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1311             }
1312             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1313         }
1315         // if we're moving the actual object, not just updating the repr, we can transform the
1316         // center by the same matrix (only necessary for non-translations)
1317         if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1318             item->setCenter(old_center * affine);
1319             SP_OBJECT(item)->updateRepr();
1320         }
1321     }
1324 void sp_selection_remove_transform(SPDesktop *desktop)
1326     if (desktop == NULL)
1327         return;
1329     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1331     GSList const *l = (GSList *) selection->reprList();
1332     while (l != NULL) {
1333         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1334         l = l->next;
1335     }
1337     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1338                      _("Remove transform"));
1341 void
1342 sp_selection_scale_absolute(Inkscape::Selection *selection,
1343                             double const x0, double const x1,
1344                             double const y0, double const y1)
1346     if (selection->isEmpty())
1347         return;
1349     Geom::OptRect const bbox(selection->bounds());
1350     if ( !bbox ) {
1351         return;
1352     }
1354     Geom::Translate const p2o(-bbox->min());
1356     Geom::Scale const newSize(x1 - x0,
1357                               y1 - y0);
1358     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1359     Geom::Translate const o2n(x0, y0);
1360     Geom::Matrix const final( p2o * scale * o2n );
1362     sp_selection_apply_affine(selection, final);
1366 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1368     if (selection->isEmpty())
1369         return;
1371     Geom::OptRect const bbox(selection->bounds());
1373     if ( !bbox ) {
1374         return;
1375     }
1377     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1378     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1379          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1380     {
1381         return;
1382     }
1384     Geom::Translate const n2d(-align);
1385     Geom::Translate const d2n(align);
1386     Geom::Matrix const final( n2d * scale * d2n );
1387     sp_selection_apply_affine(selection, final);
1390 void
1391 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1393     Geom::Translate const d2n(center);
1394     Geom::Translate const n2d(-center);
1395     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1396     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1397     sp_selection_apply_affine(selection, final);
1400 void
1401 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1403     Geom::Translate const d2n(align);
1404     Geom::Translate const n2d(-align);
1405     Geom::Matrix const skew(1, dy,
1406                             dx, 1,
1407                             0, 0);
1408     Geom::Matrix const final( n2d * skew * d2n );
1409     sp_selection_apply_affine(selection, final);
1412 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1414     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1417 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1419     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1422 /**
1423  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1424  */
1425 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1427     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1429     if (selection->isEmpty())
1430         return;
1432     GSList const *l = selection->itemList();
1433     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1434     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1435         SPItem *item = SP_ITEM(l2->data);
1436         sp_item_rotate_rel(item, rot_90);
1437     }
1439     sp_document_done(sp_desktop_document(desktop),
1440                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1441                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1444 void
1445 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1447     if (selection->isEmpty())
1448         return;
1450     boost::optional<Geom::Point> center = selection->center();
1451     if (!center) {
1452         return;
1453     }
1455     sp_selection_rotate_relative(selection, *center, angle_degrees);
1457     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1458                            ( ( angle_degrees > 0 )
1459                              ? "selector:rotate:ccw"
1460                              : "selector:rotate:cw" ),
1461                            SP_VERB_CONTEXT_SELECT,
1462                            _("Rotate"));
1465 // helper function:
1466 static
1467 Geom::Point
1468 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1469     Geom::Point m = r.midpoint();
1470     unsigned i = 0;
1471     if (p[X] < m[X]) {
1472         i = 1;
1473     }
1474     if (p[Y] < m[Y]) {
1475         i = 3 - i;
1476     }
1477     return r.corner(i);
1480 /**
1481 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1482 */
1483 void
1484 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1486     if (selection->isEmpty())
1487         return;
1489     Geom::OptRect const bbox(selection->bounds());
1490     boost::optional<Geom::Point> center = selection->center();
1492     if ( !bbox || !center ) {
1493         return;
1494     }
1496     gdouble const zoom = selection->desktop()->current_zoom();
1497     gdouble const zmove = angle / zoom;
1498     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1500     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1502     sp_selection_rotate_relative(selection, *center, zangle);
1504     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1505                            ( (angle > 0)
1506                              ? "selector:rotate:ccw"
1507                              : "selector:rotate:cw" ),
1508                            SP_VERB_CONTEXT_SELECT,
1509                            _("Rotate by pixels"));
1512 void
1513 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1515     if (selection->isEmpty())
1516         return;
1518     Geom::OptRect const bbox(selection->bounds());
1519     if (!bbox) {
1520         return;
1521     }
1523     Geom::Point const center(bbox->midpoint());
1525     // you can't scale "do nizhe pola" (below zero)
1526     double const max_len = bbox->maxExtent();
1527     if ( max_len + grow <= 1e-3 ) {
1528         return;
1529     }
1531     double const times = 1.0 + grow / max_len;
1532     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1534     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1535                            ( (grow > 0)
1536                              ? "selector:scale:larger"
1537                              : "selector:scale:smaller" ),
1538                            SP_VERB_CONTEXT_SELECT,
1539                            _("Scale"));
1542 void
1543 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1545     sp_selection_scale(selection,
1546                        grow_pixels / selection->desktop()->current_zoom());
1549 void
1550 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1552     if (selection->isEmpty())
1553         return;
1555     Geom::OptRect sel_bbox = selection->bounds();
1557     if (!sel_bbox) {
1558         return;
1559     }
1561     Geom::Point const center(sel_bbox->midpoint());
1562     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1563     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1564                      _("Scale by whole factor"));
1567 void
1568 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1570     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1571     if (selection->isEmpty()) {
1572         return;
1573     }
1575     sp_selection_move_relative(selection, dx, dy);
1577     if (dx == 0) {
1578         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1579                                _("Move vertically"));
1580     } else if (dy == 0) {
1581         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1582                                _("Move horizontally"));
1583     } else {
1584         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1585                          _("Move"));
1586     }
1589 void
1590 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1592     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1593     if (selection->isEmpty()) {
1594         return;
1595     }
1597     // same as sp_selection_move but divide deltas by zoom factor
1598     gdouble const zoom = desktop->current_zoom();
1599     gdouble const zdx = dx / zoom;
1600     gdouble const zdy = dy / zoom;
1601     sp_selection_move_relative(selection, zdx, zdy);
1603     if (dx == 0) {
1604         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1605                                _("Move vertically by pixels"));
1606     } else if (dy == 0) {
1607         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1608                                _("Move horizontally by pixels"));
1609     } else {
1610         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1611                          _("Move"));
1612     }
1615 namespace {
1617 template <typename D>
1618 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1619                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1621 template <typename D>
1622 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1623                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1625 struct Forward {
1626     typedef SPObject *Iterator;
1628     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1629     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1630     static void dispose(Iterator /*i*/) {}
1632     static SPObject *object(Iterator i) { return i; }
1633     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1634 };
1636 struct Reverse {
1637     typedef GSList *Iterator;
1639     static Iterator children(SPObject *o) {
1640         return make_list(o->firstChild(), NULL);
1641     }
1642     static Iterator siblings_after(SPObject *o) {
1643         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1644     }
1645     static void dispose(Iterator i) {
1646         g_slist_free(i);
1647     }
1649     static SPObject *object(Iterator i) {
1650         return reinterpret_cast<SPObject *>(i->data);
1651     }
1652     static Iterator next(Iterator i) { return i->next; }
1654 private:
1655     static GSList *make_list(SPObject *object, SPObject *limit) {
1656         GSList *list=NULL;
1657         while ( object != limit ) {
1658             list = g_slist_prepend(list, object);
1659             object = SP_OBJECT_NEXT(object);
1660         }
1661         return list;
1662     }
1663 };
1667 void
1668 sp_selection_item_next(SPDesktop *desktop)
1670     g_return_if_fail(desktop != NULL);
1671     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1673     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1674     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1675     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1676     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1678     SPObject *root;
1679     if (PREFS_SELECTION_ALL != inlayer) {
1680         root = selection->activeContext();
1681     } else {
1682         root = desktop->currentRoot();
1683     }
1685     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1687     if (item) {
1688         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1689         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1690             scroll_to_show_item(desktop, item);
1691         }
1692     }
1695 void
1696 sp_selection_item_prev(SPDesktop *desktop)
1698     SPDocument *document = sp_desktop_document(desktop);
1699     g_return_if_fail(document != NULL);
1700     g_return_if_fail(desktop != NULL);
1701     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1703     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1704     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1705     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1706     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1708     SPObject *root;
1709     if (PREFS_SELECTION_ALL != inlayer) {
1710         root = selection->activeContext();
1711     } else {
1712         root = desktop->currentRoot();
1713     }
1715     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1717     if (item) {
1718         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1719         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1720             scroll_to_show_item(desktop, item);
1721         }
1722     }
1725 void sp_selection_next_patheffect_param(SPDesktop * dt)
1727     if (!dt) return;
1729     Inkscape::Selection *selection = sp_desktop_selection(dt);
1730     if ( selection && !selection->isEmpty() ) {
1731         SPItem *item = selection->singleItem();
1732         if ( item && SP_IS_SHAPE(item)) {
1733             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1734                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1735             } else {
1736                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1737             }
1738         }
1739     }
1742 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1744     if (!dt) return;
1746     Inkscape::Selection *selection = sp_desktop_selection(dt);
1747     if ( selection && !selection->isEmpty() ) {
1748         SPItem *item = selection->singleItem();
1749         if ( item ) {
1750             SPObject *obj = NULL;
1751             if (clip)
1752                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1753             else
1754                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1756             if (obj) {
1757                 // obj is a group object, the children are the actual clippers
1758                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1759                     if ( SP_IS_ITEM(child) ) {
1760                         // If not already in nodecontext, goto it!
1761                         if (!tools_isactive(dt, TOOLS_NODES)) {
1762                             tools_switch(dt, TOOLS_NODES);
1763                         }
1765                         ShapeEditor * shape_editor = dt->event_context->shape_editor;
1766                         // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1767                         shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1768                         shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1769                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1770                         if (np) {
1771                             // take colors from prefs (same as used in outline mode)
1772                             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1773                             np->helperpath_rgba = clip ?
1774                                 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) :
1775                                 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1776                             np->helperpath_width = 1.0;
1777                             sp_nodepath_show_helperpath(np, true);
1778                         }
1779                         break; // break out of for loop after 1st encountered item
1780                     }
1781                 }
1782             } else if (clip) {
1783                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1784             } else {
1785                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1786             }
1787         }
1788     }
1792 namespace {
1794 template <typename D>
1795 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1796                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1798     SPObject *current=root;
1799     while (items) {
1800         SPItem *item=SP_ITEM(items->data);
1801         if ( root->isAncestorOf(item) &&
1802              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1803         {
1804             current = item;
1805             break;
1806         }
1807         items = items->next;
1808     }
1810     GSList *path=NULL;
1811     while ( current != root ) {
1812         path = g_slist_prepend(path, current);
1813         current = SP_OBJECT_PARENT(current);
1814     }
1816     SPItem *next;
1817     // first, try from the current object
1818     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1819     g_slist_free(path);
1821     if (!next) { // if we ran out of objects, start over at the root
1822         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1823     }
1825     return next;
1828 template <typename D>
1829 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1830                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1832     typename D::Iterator children;
1833     typename D::Iterator iter;
1835     SPItem *found=NULL;
1837     if (path) {
1838         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1839         g_assert(SP_OBJECT_PARENT(object) == root);
1840         if (desktop->isLayer(object)) {
1841             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1842         }
1843         iter = children = D::siblings_after(object);
1844     } else {
1845         iter = children = D::children(root);
1846     }
1848     while ( iter && !found ) {
1849         SPObject *object=D::object(iter);
1850         if (desktop->isLayer(object)) {
1851             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1852                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1853             }
1854         } else if ( SP_IS_ITEM(object) &&
1855                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1856                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1857                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1858                     !desktop->isLayer(SP_ITEM(object)) )
1859         {
1860             found = SP_ITEM(object);
1861         }
1862         iter = D::next(iter);
1863     }
1865     D::dispose(children);
1867     return found;
1872 /**
1873  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1874  * \a item.
1875  */
1876 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1878     Geom::Rect dbox = desktop->get_display_area();
1879     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1881     if ( sbox && dbox.contains(*sbox) == false ) {
1882         Geom::Point const s_dt = sbox->midpoint();
1883         Geom::Point const s_w = desktop->d2w(s_dt);
1884         Geom::Point const d_dt = dbox.midpoint();
1885         Geom::Point const d_w = desktop->d2w(d_dt);
1886         Geom::Point const moved_w( d_w - s_w );
1887         gint const dx = (gint) moved_w[X];
1888         gint const dy = (gint) moved_w[Y];
1889         desktop->scroll_world(dx, dy);
1890     }
1894 void
1895 sp_selection_clone(SPDesktop *desktop)
1897     if (desktop == NULL)
1898         return;
1900     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1902     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1904     // check if something is selected
1905     if (selection->isEmpty()) {
1906         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1907         return;
1908     }
1910     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1912     selection->clear();
1914     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1915     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1917     GSList *newsel = NULL;
1919     while (reprs) {
1920         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1921         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1923         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1924         clone->setAttribute("x", "0", false);
1925         clone->setAttribute("y", "0", false);
1926         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1928         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1929         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1931         // add the new clone to the top of the original's parent
1932         parent->appendChild(clone);
1934         newsel = g_slist_prepend(newsel, clone);
1935         reprs = g_slist_remove(reprs, sel_repr);
1936         Inkscape::GC::release(clone);
1937     }
1939     // TRANSLATORS: only translate "string" in "context|string".
1940     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1941     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1942                      Q_("action|Clone"));
1944     selection->setReprList(newsel);
1946     g_slist_free(newsel);
1949 void
1950 sp_selection_relink(SPDesktop *desktop)
1952     if (!desktop)
1953         return;
1955     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1957     if (selection->isEmpty()) {
1958         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1959         return;
1960     }
1962     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1963     const gchar *newid = cm->getFirstObjectID();
1964     if (!newid) {
1965         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1966         return;
1967     }
1968     gchar *newref = g_strdup_printf("#%s", newid);
1970     // Get a copy of current selection.
1971     bool relinked = false;
1972     for (GSList *items = (GSList *) selection->itemList();
1973          items != NULL;
1974          items = items->next)
1975     {
1976         SPItem *item = (SPItem *) items->data;
1978         if (!SP_IS_USE(item))
1979             continue;
1981         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1982         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1983         relinked = true;
1984     }
1986     g_free(newref);
1988     if (!relinked) {
1989         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1990     } else {
1991         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1992                          _("Relink clone"));
1993     }
1997 void
1998 sp_selection_unlink(SPDesktop *desktop)
2000     if (!desktop)
2001         return;
2003     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2005     if (selection->isEmpty()) {
2006         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2007         return;
2008     }
2010     // Get a copy of current selection.
2011     GSList *new_select = NULL;
2012     bool unlinked = false;
2013     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2014          items != NULL;
2015          items = items->next)
2016     {
2017         SPItem *item = (SPItem *) items->data;
2019         if (SP_IS_TEXT(item)) {
2020             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2022             if (tspan) {
2023                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2024             }
2026             // Set unlink to true, and fall into the next if which
2027             // will include this text item in the new selection
2028             unlinked = true;
2029         }
2031         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2032             // keep the non-use item in the new selection
2033             new_select = g_slist_prepend(new_select, item);
2034             continue;
2035         }
2037         SPItem *unlink;
2038         if (SP_IS_USE(item)) {
2039             unlink = sp_use_unlink(SP_USE(item));
2040         } else /*if (SP_IS_TREF(use))*/ {
2041             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2042         }
2044         unlinked = true;
2045         // Add ungrouped items to the new selection.
2046         new_select = g_slist_prepend(new_select, unlink);
2047     }
2049     if (new_select) { // set new selection
2050         selection->clear();
2051         selection->setList(new_select);
2052         g_slist_free(new_select);
2053     }
2054     if (!unlinked) {
2055         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2056     }
2058     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2059                      _("Unlink clone"));
2062 void
2063 sp_select_clone_original(SPDesktop *desktop)
2065     if (desktop == NULL)
2066         return;
2068     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2070     SPItem *item = selection->singleItem();
2072     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.");
2074     // Check if other than two objects are selected
2075     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2076         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2077         return;
2078     }
2080     SPItem *original = NULL;
2081     if (SP_IS_USE(item)) {
2082         original = sp_use_get_original(SP_USE(item));
2083     } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2084         original = sp_offset_get_source(SP_OFFSET(item));
2085     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2086         original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2087     } else if (SP_IS_FLOWTEXT(item)) {
2088         original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2089     } else { // it's an object that we don't know what to do with
2090         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2091         return;
2092     }
2094     if (!original) {
2095         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2096         return;
2097     }
2099     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2100         if (SP_IS_DEFS(o)) {
2101             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2102             return;
2103         }
2104     }
2106     if (original) {
2107         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2108         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2109         if (highlight) {
2110             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2111             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2112             if ( a && b ) {
2113                 // draw a flashing line between the objects
2114                 SPCurve *curve = new SPCurve();
2115                 curve->moveto(a->midpoint());
2116                 curve->lineto(b->midpoint());
2118                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2119                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2120                 sp_canvas_item_show(canvasitem);
2121                 curve->unref();
2122                 desktop->add_temporary_canvasitem(canvasitem, 1000);
2123             }
2124         }
2126         selection->clear();
2127         selection->set(original);
2128         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2129             scroll_to_show_item(desktop, original);
2130         }
2131     }
2135 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2137     if (desktop == NULL)
2138         return;
2140     SPDocument *doc = sp_desktop_document(desktop);
2141     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2143     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2145     // check if something is selected
2146     if (selection->isEmpty()) {
2147         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2148         return;
2149     }
2151     sp_document_ensure_up_to_date(doc);
2152     Geom::OptRect r = selection->bounds();
2153     boost::optional<Geom::Point> c = selection->center();
2154     if ( !r || !c ) {
2155         return;
2156     }
2158     // calculate the transform to be applied to objects to move them to 0,0
2159     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2160     move_p[Geom::Y] = -move_p[Geom::Y];
2161     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2163     GSList *items = g_slist_copy((GSList *) selection->itemList());
2165     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2167     // bottommost object, after sorting
2168     SPObject *parent = SP_OBJECT_PARENT(items->data);
2170     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2172     // remember the position of the first item
2173     gint pos = SP_OBJECT_REPR(items->data)->position();
2174     (void)pos; // TODO check why this was remembered
2176     // create a list of duplicates
2177     GSList *repr_copies = NULL;
2178     for (GSList *i = items; i != NULL; i = i->next) {
2179         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2180         repr_copies = g_slist_prepend(repr_copies, dup);
2181     }
2183     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2185     if (apply) {
2186         // delete objects so that their clones don't get alerted; this object will be restored shortly
2187         for (GSList *i = items; i != NULL; i = i->next) {
2188             SPObject *item = SP_OBJECT(i->data);
2189             item->deleteObject(false);
2190         }
2191     }
2193     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2194     // without disturbing clones.
2195     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2196     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2197     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2198     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2200     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2201                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2202                                                                               Geom::Point(r->min()[Geom::X],
2203                                                                                           r->max()[Geom::Y]))))
2204                                              * parent_transform.inverse() ),
2205                                            parent_transform * move);
2206     (void)mark_id;
2208     // restore compensation setting
2209     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2212     g_slist_free(items);
2214     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2215                      _("Objects to marker"));
2218 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2219     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2220         for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2221             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2222         }
2223     } else {
2224         sp_item_convert_item_to_guides(item);
2226         if (deleteitem) {
2227             SP_OBJECT(item)->deleteObject(true);
2228         }
2229     }
2232 void sp_selection_to_guides(SPDesktop *desktop)
2234     if (desktop == NULL)
2235         return;
2237     SPDocument *doc = sp_desktop_document(desktop);
2238     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2239     // we need to copy the list because it gets reset when objects are deleted
2240     GSList *items = g_slist_copy((GSList *) selection->itemList());
2242     if (!items) {
2243         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2244         return;
2245     }
2247     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2248     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2249     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2251     for (GSList const *i = items; i != NULL; i = i->next) {
2252         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2253     }
2255     sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2258 void
2259 sp_selection_tile(SPDesktop *desktop, bool apply)
2261     if (desktop == NULL)
2262         return;
2264     SPDocument *doc = sp_desktop_document(desktop);
2265     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2267     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2269     // check if something is selected
2270     if (selection->isEmpty()) {
2271         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2272         return;
2273     }
2275     sp_document_ensure_up_to_date(doc);
2276     Geom::OptRect r = selection->bounds();
2277     if ( !r ) {
2278         return;
2279     }
2281     // calculate the transform to be applied to objects to move them to 0,0
2282     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2283     move_p[Geom::Y] = -move_p[Geom::Y];
2284     Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2286     GSList *items = g_slist_copy((GSList *) selection->itemList());
2288     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2290     // bottommost object, after sorting
2291     SPObject *parent = SP_OBJECT_PARENT(items->data);
2293     Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2295     // remember the position of the first item
2296     gint pos = SP_OBJECT_REPR(items->data)->position();
2298     // create a list of duplicates
2299     GSList *repr_copies = NULL;
2300     for (GSList *i = items; i != NULL; i = i->next) {
2301         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2302         repr_copies = g_slist_prepend(repr_copies, dup);
2303     }
2304     // restore the z-order after prepends
2305     repr_copies = g_slist_reverse(repr_copies);
2307     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2309     if (apply) {
2310         // delete objects so that their clones don't get alerted; this object will be restored shortly
2311         for (GSList *i = items; i != NULL; i = i->next) {
2312             SPObject *item = SP_OBJECT(i->data);
2313             item->deleteObject(false);
2314         }
2315     }
2317     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2318     // without disturbing clones.
2319     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2320     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2321     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2322     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2324     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2325                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2326                                                                                             r->max()[Geom::Y]))))
2327                                          * to_2geom(parent_transform.inverse()) ),
2328                                        parent_transform * move);
2330     // restore compensation setting
2331     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2333     if (apply) {
2334         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2335         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2337         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2338         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2340         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2341         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2342         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2343         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2345         // restore parent and position
2346         SP_OBJECT_REPR(parent)->appendChild(rect);
2347         rect->setPosition(pos > 0 ? pos : 0);
2348         SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2350         Inkscape::GC::release(rect);
2352         selection->clear();
2353         selection->set(rectangle);
2354     }
2356     g_slist_free(items);
2358     sp_document_done(doc, SP_VERB_EDIT_TILE,
2359                      _("Objects to pattern"));
2362 void
2363 sp_selection_untile(SPDesktop *desktop)
2365     if (desktop == NULL)
2366         return;
2368     SPDocument *doc = sp_desktop_document(desktop);
2369     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2371     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2373     // check if something is selected
2374     if (selection->isEmpty()) {
2375         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2376         return;
2377     }
2379     GSList *new_select = NULL;
2381     bool did = false;
2383     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2384          items != NULL;
2385          items = items->next) {
2387         SPItem *item = (SPItem *) items->data;
2389         SPStyle *style = SP_OBJECT_STYLE(item);
2391         if (!style || !style->fill.isPaintserver())
2392             continue;
2394         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2396         if (!SP_IS_PATTERN(server))
2397             continue;
2399         did = true;
2401         SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2403         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2404         pat_transform *= item->transform;
2406         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2407             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2408             SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2410            // FIXME: relink clones to the new canvas objects
2411            // use SPObject::setid when mental finishes it to steal ids of
2413             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2414             sp_document_ensure_up_to_date(doc);
2416             Geom::Matrix transform( i->transform * pat_transform );
2417             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2419             new_select = g_slist_prepend(new_select, i);
2420         }
2422         SPCSSAttr *css = sp_repr_css_attr_new();
2423         sp_repr_css_set_property(css, "fill", "none");
2424         sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2425     }
2427     if (!did) {
2428         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2429     } else {
2430         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2431                          _("Pattern to objects"));
2432         selection->setList(new_select);
2433     }
2436 void
2437 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2439     if (selection->isEmpty()) {
2440         return;
2441     }
2443     GSList const *reprlst = selection->reprList();
2444     bool filename_search = TRUE;
2445     bool xdpi_search = TRUE;
2446     bool ydpi_search = TRUE;
2448     for (; reprlst != NULL &&
2449             filename_search &&
2450             xdpi_search &&
2451             ydpi_search;
2452         reprlst = reprlst->next) {
2453         gchar const *dpi_string;
2454         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2456         if (filename_search) {
2457             *filename = repr->attribute("inkscape:export-filename");
2458             if (*filename != NULL)
2459                 filename_search = FALSE;
2460         }
2462         if (xdpi_search) {
2463             dpi_string = NULL;
2464             dpi_string = repr->attribute("inkscape:export-xdpi");
2465             if (dpi_string != NULL) {
2466                 *xdpi = atof(dpi_string);
2467                 xdpi_search = FALSE;
2468             }
2469         }
2471         if (ydpi_search) {
2472             dpi_string = NULL;
2473             dpi_string = repr->attribute("inkscape:export-ydpi");
2474             if (dpi_string != NULL) {
2475                 *ydpi = atof(dpi_string);
2476                 ydpi_search = FALSE;
2477             }
2478         }
2479     }
2482 void
2483 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2485     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2486     gchar const *dpi_string;
2488     *filename = repr->attribute("inkscape:export-filename");
2490     dpi_string = NULL;
2491     dpi_string = repr->attribute("inkscape:export-xdpi");
2492     if (dpi_string != NULL) {
2493         *xdpi = atof(dpi_string);
2494     }
2496     dpi_string = NULL;
2497     dpi_string = repr->attribute("inkscape:export-ydpi");
2498     if (dpi_string != NULL) {
2499         *ydpi = atof(dpi_string);
2500     }
2503 void
2504 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2506     if (desktop == NULL)
2507         return;
2509     SPDocument *document = sp_desktop_document(desktop);
2510     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2512     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2514     // check if something is selected
2515     if (selection->isEmpty()) {
2516         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2517         return;
2518     }
2520     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2521     // set "busy" cursor
2522     desktop->setWaitingCursor();
2524     // Get the bounding box of the selection
2525     NRRect bbox;
2526     sp_document_ensure_up_to_date(document);
2527     selection->bounds(&bbox);
2528     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2529         desktop->clearWaitingCursor();
2530         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2531     }
2533     // List of the items to show; all others will be hidden
2534     GSList *items = g_slist_copy((GSList *) selection->itemList());
2536     // Sort items so that the topmost comes last
2537     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2539     // Generate a random value from the current time (you may create bitmap from the same object(s)
2540     // multiple times, and this is done so that they don't clash)
2541     GTimeVal cu;
2542     g_get_current_time(&cu);
2543     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2545     // Create the filename.
2546     gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2547                                             document->name,
2548                                             SP_OBJECT_REPR(items->data)->attribute("id"),
2549                                             current);
2550     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2551     // digits, and a few other chars, with "_"
2552     g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2554     // Build the complete path by adding document base dir, if set, otherwise home dir
2555     gchar * directory = NULL;
2556     if (SP_DOCUMENT_URI(document)) {
2557         directory = g_dirname(SP_DOCUMENT_URI(document));
2558     }
2559     if (directory == NULL) {
2560         directory = homedir_path(NULL);
2561     }
2562     gchar *filepath = g_build_filename(directory, basename, NULL);
2564     //g_print("%s\n", filepath);
2566     // Remember parent and z-order of the topmost one
2567     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2568     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2569     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2571     // Calculate resolution
2572     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2573     double res;
2574     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2575     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2576     if (0 < prefs_res) {
2577         // If it's given explicitly in prefs, take it
2578         res = prefs_res;
2579     } else if (0 < prefs_min) {
2580         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2581         res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2582     } else {
2583         float hint_xdpi = 0, hint_ydpi = 0;
2584         char const *hint_filename;
2585         // take resolution hint from the selected objects
2586         sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2587         if (hint_xdpi != 0) {
2588             res = hint_xdpi;
2589         } else {
2590             // take resolution hint from the document
2591             sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2592             if (hint_xdpi != 0) {
2593                 res = hint_xdpi;
2594             } else {
2595                 // if all else fails, take the default 90 dpi
2596                 res = PX_PER_IN;
2597             }
2598         }
2599     }
2601     // The width and height of the bitmap in pixels
2602     unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2603     unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2605     // Find out if we have to run an external filter
2606     gchar const *run = NULL;
2607     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2608     if (!filter.empty()) {
2609         // filter command is given;
2610         // see if we have a parameter to pass to it
2611         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2612         if (!param1.empty()) {
2613             if (param1[param1.length() - 1] == '%') {
2614                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2615                 gchar p1[256];
2616                 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2617                 // the first param is always the image filename, the second is param1
2618                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2619             } else {
2620                 // otherwise pass the param1 unchanged
2621                 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2622             }
2623         } else {
2624             // run without extra parameter
2625             run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2626         }
2627     }
2629     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2630     Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2631     Geom::Matrix t;
2633     double shift_x = bbox.x0;
2634     double shift_y = bbox.y1;
2635     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2636         shift_x = round(shift_x);
2637         shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2638     }
2639     t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2641     // Do the export
2642     sp_export_png_file(document, filepath,
2643                        bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2644                        width, height, res, res,
2645                        (guint32) 0xffffff00,
2646                        NULL, NULL,
2647                        true,  /*bool force_overwrite,*/
2648                        items);
2650     g_slist_free(items);
2652     // Run filter, if any
2653     if (run) {
2654         g_print("Running external filter: %s\n", run);
2655         int retval;
2656         retval = system(run);
2657     }
2659     // Import the image back
2660     GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2661     if (pb) {
2662         // Create the repr for the image
2663         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2664         {
2665             repr->setAttribute("sodipodi:absref", filepath);
2666             gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2667             repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2668             g_free(abs_base);
2669         }
2670         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2671             sp_repr_set_svg_double(repr, "width", width);
2672             sp_repr_set_svg_double(repr, "height", height);
2673         } else {
2674             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2675             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2676         }
2678         // Write transform
2679         gchar *c=sp_svg_transform_write(t);
2680         repr->setAttribute("transform", c);
2681         g_free(c);
2683         // add the new repr to the parent
2684         parent->appendChild(repr);
2686         // move to the saved position
2687         repr->setPosition(pos > 0 ? pos + 1 : 1);
2689         // Set selection to the new image
2690         selection->clear();
2691         selection->add(repr);
2693         // Clean up
2694         Inkscape::GC::release(repr);
2695         gdk_pixbuf_unref(pb);
2697         // Complete undoable transaction
2698         sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2699                          _("Create bitmap"));
2700     }
2702     desktop->clearWaitingCursor();
2704     g_free(basename);
2705     g_free(filepath);
2708 /**
2709  * \brief Creates a mask or clipPath from selection
2710  * Two different modes:
2711  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2712  *       and is applied to current layer
2713  *  otherwise, topmost object is used as mask for other objects
2714  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2715  *
2716  */
2717 void
2718 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2720     if (desktop == NULL)
2721         return;
2723     SPDocument *doc = sp_desktop_document(desktop);
2724     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2726     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2728     // check if something is selected
2729     bool is_empty = selection->isEmpty();
2730     if ( apply_to_layer && is_empty) {
2731         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2732         return;
2733     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2734         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2735         return;
2736     }
2738     // FIXME: temporary patch to prevent crash!
2739     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2740     bool clone_with_original = selection_contains_both_clone_and_original(selection);
2741     if (clone_with_original) {
2742         return; // in this version, you cannot clip/mask an object with its own clone
2743     }
2744     // /END FIXME
2746     sp_document_ensure_up_to_date(doc);
2748     GSList *items = g_slist_copy((GSList *) selection->itemList());
2750     items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2752     // create a list of duplicates
2753     GSList *mask_items = NULL;
2754     GSList *apply_to_items = NULL;
2755     GSList *items_to_delete = NULL;
2756     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2757     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2758     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2760     if (apply_to_layer) {
2761         // all selected items are used for mask, which is applied to a layer
2762         apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2764         for (GSList *i = items; i != NULL; i = i->next) {
2765             Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2766             mask_items = g_slist_prepend(mask_items, dup);
2768             if (remove_original) {
2769                 SPObject *item = SP_OBJECT(i->data);
2770                 items_to_delete = g_slist_prepend(items_to_delete, item);
2771             }
2772         }
2773     } else if (!topmost) {
2774         // topmost item is used as a mask, which is applied to other items in a selection
2775         GSList *i = items;
2776         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2777         mask_items = g_slist_prepend(mask_items, dup);
2779         if (remove_original) {
2780             SPObject *item = SP_OBJECT(i->data);
2781             items_to_delete = g_slist_prepend(items_to_delete, item);
2782         }
2784         for (i = i->next; i != NULL; i = i->next) {
2785             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2786         }
2787     } else {
2788         GSList *i = NULL;
2789         for (i = items; NULL != i->next; i = i->next) {
2790             apply_to_items = g_slist_prepend(apply_to_items, i->data);
2791         }
2793         Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2794         mask_items = g_slist_prepend(mask_items, dup);
2796         if (remove_original) {
2797             SPObject *item = SP_OBJECT(i->data);
2798             items_to_delete = g_slist_prepend(items_to_delete, item);
2799         }
2800     }
2802     g_slist_free(items);
2803     items = NULL;
2805     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2806     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2807         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2808         // inverted object transform should be applied to a mask object,
2809         // as mask is calculated in user space (after applying transform)
2810         Geom::Matrix maskTransform(item->transform.inverse());
2812         GSList *mask_items_dup = NULL;
2813         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2814             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2815             mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2816         }
2818         gchar const *mask_id = NULL;
2819         if (apply_clip_path) {
2820             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2821         } else {
2822             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2823         }
2825         g_slist_free(mask_items_dup);
2826         mask_items_dup = NULL;
2828         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2829     }
2831     g_slist_free(mask_items);
2832     g_slist_free(apply_to_items);
2834     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2835         SPObject *item = SP_OBJECT(i->data);
2836         item->deleteObject(false);
2837     }
2838     g_slist_free(items_to_delete);
2840     if (apply_clip_path)
2841         sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2842     else
2843         sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2846 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2847     if (desktop == NULL)
2848         return;
2850     SPDocument *doc = sp_desktop_document(desktop);
2851     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2852     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2854     // check if something is selected
2855     if (selection->isEmpty()) {
2856         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2857         return;
2858     }
2860     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2861     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2862     sp_document_ensure_up_to_date(doc);
2864     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2865     std::map<SPObject*,SPItem*> referenced_objects;
2866     // SPObject* refers to a group containing the clipped path or mask itself,
2867     // whereas SPItem* refers to the item being clipped or masked
2868     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2869         if (remove_original) {
2870             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2871             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2872             Inkscape::URIReference *uri_ref = NULL;
2874             if (apply_clip_path) {
2875                 uri_ref = item->clip_ref;
2876             } else {
2877                 uri_ref = item->mask_ref;
2878             }
2880             // collect distinct mask object (and associate with item to apply transform)
2881             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2882                 referenced_objects[uri_ref->getObject()] = item;
2883             }
2884         }
2886         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2887     }
2889     // restore mask objects into a document
2890     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2891         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2892         GSList *items_to_move = NULL;
2893         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2894             // Collect all clipped paths and masks within a single group
2895             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2896             items_to_move = g_slist_prepend(items_to_move, copy);
2897         }
2899         if (!obj->isReferenced()) {
2900             // delete from defs if no other object references this mask
2901             obj->deleteObject(false);
2902         }
2904         // remember parent and position of the item to which the clippath/mask was applied
2905         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2906         gint pos = SP_OBJECT_REPR((*it).second)->position();
2908         // Iterate through all clipped paths / masks
2909         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2910             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2912             // insert into parent, restore pos
2913             parent->appendChild(repr);
2914             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2916             SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
2917             selection->add(repr);
2919             // transform mask, so it is moved the same spot where mask was applied
2920             Geom::Matrix transform(mask_item->transform);
2921             transform *= (*it).second->transform;
2922             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2923         }
2925         g_slist_free(items_to_move);
2926     }
2928     if (apply_clip_path)
2929         sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2930     else
2931         sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2934 /**
2935  * Returns true if an undoable change should be recorded.
2936  */
2937 bool
2938 fit_canvas_to_selection(SPDesktop *desktop)
2940     g_return_val_if_fail(desktop != NULL, false);
2941     SPDocument *doc = sp_desktop_document(desktop);
2943     g_return_val_if_fail(doc != NULL, false);
2944     g_return_val_if_fail(desktop->selection != NULL, false);
2946     if (desktop->selection->isEmpty()) {
2947         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2948         return false;
2949     }
2950     Geom::OptRect const bbox(desktop->selection->bounds());
2951     if (bbox) {
2952         doc->fitToRect(*bbox);
2953         return true;
2954     } else {
2955         return false;
2956     }
2959 /**
2960  * Fit canvas to the bounding box of the selection, as an undoable action.
2961  */
2962 void
2963 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2965     if (fit_canvas_to_selection(desktop)) {
2966         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2967                          _("Fit Page to Selection"));
2968     }
2971 bool
2972 fit_canvas_to_drawing(SPDocument *doc)
2974     g_return_val_if_fail(doc != NULL, false);
2976     sp_document_ensure_up_to_date(doc);
2977     SPItem const *const root = SP_ITEM(doc->root);
2978     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2979     if (bbox) {
2980         doc->fitToRect(*bbox);
2981         return true;
2982     } else {
2983         return false;
2984     }
2987 void
2988 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2990     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2991         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2992                          _("Fit Page to Drawing"));
2993     }
2996 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2997     g_return_if_fail(desktop != NULL);
2998     SPDocument *doc = sp_desktop_document(desktop);
3000     g_return_if_fail(doc != NULL);
3001     g_return_if_fail(desktop->selection != NULL);
3003     bool const changed = ( desktop->selection->isEmpty()
3004                            ? fit_canvas_to_drawing(doc)
3005                            : fit_canvas_to_selection(desktop) );
3006     if (changed) {
3007         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3008                          _("Fit Page to Selection or Drawing"));
3009     }
3010 };
3012 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3013     // don't operate on layers
3014     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3015         f(SP_ITEM(root), desktop);
3016     }
3017     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3018         //don't recurse into locked layers
3019         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3020             itemtree_map(f, iter, desktop);
3021         }
3022     }
3025 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3026     if (item->isLocked()) {
3027         item->setLocked(FALSE);
3028     }
3031 static void unhide(SPItem *item, SPDesktop *desktop) {
3032     if (desktop->itemIsHidden(item)) {
3033         item->setExplicitlyHidden(FALSE);
3034     }
3037 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3038     if (!dt) return;
3040     SPObject *root;
3041     if (layer_only) {
3042         root = dt->currentLayer();
3043     } else {
3044         root = dt->currentRoot();
3045     }
3047     itemtree_map(f, root, dt);
3050 void unlock_all(SPDesktop *dt) {
3051     process_all(&unlock, dt, true);
3054 void unlock_all_in_all_layers(SPDesktop *dt) {
3055     process_all(&unlock, dt, false);
3058 void unhide_all(SPDesktop *dt) {
3059     process_all(&unhide, dt, true);
3062 void unhide_all_in_all_layers(SPDesktop *dt) {
3063     process_all(&unhide, dt, false);
3067 /*
3068   Local Variables:
3069   mode:c++
3070   c-file-style:"stroustrup"
3071   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3072   indent-tabs-mode:nil
3073   fill-column:99
3074   End:
3075 */
3076 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :