Code

badf27ecb45caa4d93541f5e806a371f43b66fd9
[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 "selection.h"
31 #include "tools-switch.h"
32 #include "desktop-handles.h"
33 #include "message-stack.h"
34 #include "sp-item-transform.h"
35 #include "marker.h"
36 #include "sp-use.h"
37 #include "sp-textpath.h"
38 #include "sp-tspan.h"
39 #include "sp-tref.h"
40 #include "sp-flowtext.h"
41 #include "sp-flowregion.h"
42 #include "text-editing.h"
43 #include "text-context.h"
44 #include "connector-context.h"
45 #include "sp-path.h"
46 #include "sp-conn-end.h"
47 #include "dropper-context.h"
48 #include <glibmm/i18n.h>
49 #include "libnr/nr-matrix-rotate-ops.h"
50 #include "libnr/nr-matrix-translate-ops.h"
51 #include "libnr/nr-scale-ops.h"
52 #include <libnr/nr-matrix-ops.h>
53 #include <2geom/transforms.h>
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "preferences.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include <cstring>
73 #include <string>
74 #include "helper/units.h"
75 #include "sp-item.h"
76 #include "box3d.h"
77 #include "unit-constants.h"
78 #include "xml/simple-document.h"
79 #include "sp-filter-reference.h"
80 #include "gradient-drag.h"
81 #include "uri-references.h"
82 #include "libnr/nr-convert2geom.h"
83 #include "display/curve.h"
84 #include "display/canvas-bpath.h"
85 #include "inkscape-private.h"
87 // For clippath editing
88 #include "tools-switch.h"
89 #include "shape-editor.h"
90 #include "node-context.h"
91 #include "nodepath.h"
93 #include "ui/clipboard.h"
95 using Geom::X;
96 using Geom::Y;
98 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
99 because the layer manipulation code uses them. It should be rewritten specifically
100 for that purpose. */
102 /**
103  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
104  * then prepends the copy to 'clip'.
105  */
106 void sp_selection_copy_one (Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
108     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
110     // copy complete inherited style
111     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
112     sp_repr_css_set(copy, css, "style");
113     sp_repr_css_attr_unref(css);
115     // write the complete accumulated transform passed to us
116     // (we're dealing with unattached repr, so we write to its attr
117     // instead of using sp_item_set_transform)
118     gchar *affinestr=sp_svg_transform_write(full_t);
119     copy->setAttribute("transform", affinestr);
120     g_free(affinestr);
122     *clip = g_slist_prepend(*clip, copy);
125 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
127     // Sort items:
128     GSList *sorted_items = g_slist_copy ((GSList *) items);
129     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
131     // Copy item reprs:
132     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
133         sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
134     }
136     *clip = g_slist_reverse(*clip);
137     g_slist_free ((GSList *) sorted_items);
140 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
142     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
144     GSList *copied = NULL;
145     // add objects to document
146     for (GSList *l = *clip; l != NULL; l = l->next) {
147         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
148         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
150         // premultiply the item transform by the accumulated parent transform in the paste layer
151         Geom::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
152         if (!local.isIdentity()) {
153             gchar const *t_str = copy->attribute("transform");
154             Geom::Matrix item_t (Geom::identity());
155             if (t_str)
156                 sp_svg_transform_read(t_str, &item_t);
157             item_t *= local.inverse();
158             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
159             gchar *affinestr=sp_svg_transform_write(item_t);
160             copy->setAttribute("transform", affinestr);
161             g_free(affinestr);
162         }
164         parent->appendChildRepr(copy);
165         copied = g_slist_prepend(copied, copy);
166         Inkscape::GC::release(copy);
167     }
168     return copied;
171 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
173     for (GSList const *i = items ; i ; i = i->next ) {
174         sp_object_ref((SPObject *)i->data, NULL);
175     }
176     for (GSList const *i = items; i != NULL; i = i->next) {
177         SPItem *item = (SPItem *) i->data;
178         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
179         sp_object_unref((SPObject *)item, NULL);
180     }
184 void sp_selection_delete(SPDesktop *desktop)
186     if (desktop == NULL) {
187         return;
188     }
190     if (tools_isactive (desktop, TOOLS_TEXT))
191         if (sp_text_delete_selection(desktop->event_context)) {
192             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
193                              _("Delete text"));
194             return;
195         }
197     Inkscape::Selection *selection = sp_desktop_selection(desktop);
199     // check if something is selected
200     if (selection->isEmpty()) {
201         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
202         return;
203     }
205     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
206     selection->clear();
207     sp_selection_delete_impl (selected);
208     g_slist_free ((GSList *) selected);
210     /* a tool may have set up private information in it's selection context
211      * that depends on desktop items.  I think the only sane way to deal with
212      * this currently is to reset the current tool, which will reset it's
213      * associated selection context.  For example: deleting an object
214      * while moving it around the canvas.
215      */
216     tools_switch ( desktop, tools_active ( desktop ) );
218     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
219                      _("Delete"));
222 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
224     if (!obj)
225         return;
227     ids.push_back(SP_OBJECT_ID(obj));
229     if (SP_IS_GROUP(obj)) {
230         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
231             add_ids_recursive (ids, child);
232         }
233     }
236 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
238     if (desktop == NULL)
239         return;
241     SPDocument *doc = desktop->doc();
242     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
243     Inkscape::Selection *selection = sp_desktop_selection(desktop);
245     // check if something is selected
246     if (selection->isEmpty()) {
247         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
248         return;
249     }
251     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
253     selection->clear();
255     // sorting items from different parents sorts each parent's subset without possibly mixing
256     // them, just what we need
257     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
259     GSList *newsel = NULL;
261     std::vector<const gchar *> old_ids;
262     std::vector<const gchar *> new_ids;
263     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
264     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
266     while (reprs) {
267         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
268         Inkscape::XML::Node *parent = old_repr->parent();
269         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
271         parent->appendChild(copy);
273         if (relink_clones) {
274             SPObject *old_obj = doc->getObjectByRepr(old_repr);
275             SPObject *new_obj = doc->getObjectByRepr(copy);
276             add_ids_recursive (old_ids, old_obj);
277             add_ids_recursive (new_ids, new_obj);
278         }
280         newsel = g_slist_prepend(newsel, copy);
281         reprs = g_slist_remove(reprs, reprs->data);
282         Inkscape::GC::release(copy);
283     }
285     if (relink_clones) {
287         g_assert (old_ids.size() == new_ids.size());
289         for(unsigned int i = 0; i < old_ids.size(); i++) {
290             const gchar *id = old_ids[i];
291             SPObject *old_clone = doc->getObjectById(id);
292             if (SP_IS_USE(old_clone)) {
293                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
294                 for(unsigned int j = 0; j < old_ids.size(); j++) {
295                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
296                         // we have both orig and clone in selection, relink
297                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
298                         gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
299                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
300                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
301                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
302                         g_free (newref);
303                     }
304                 }
305             }
306         }
307     }
310     if ( !suppressDone ) {
311         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
312                          _("Duplicate"));
313     }
315     selection->setReprList(newsel);
317     g_slist_free(newsel);
320 void sp_edit_clear_all(SPDesktop *dt)
322     if (!dt)
323         return;
325     SPDocument *doc = sp_desktop_document(dt);
326     sp_desktop_selection(dt)->clear();
328     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
329     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
331     while (items) {
332         SP_OBJECT (items->data)->deleteObject();
333         items = g_slist_remove(items, items->data);
334     }
336     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
337                      _("Delete all"));
340 GSList *
341 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
343     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
344         if (SP_IS_ITEM(child) &&
345             !desktop->isLayer(SP_ITEM(child)) &&
346             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
347             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
348             (!exclude || !g_slist_find ((GSList *) exclude, child))
349             )
350         {
351             list = g_slist_prepend (list, SP_ITEM(child));
352         }
354         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
355             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
356         }
357     }
359     return list;
362 void sp_edit_select_all_full (SPDesktop *dt, bool force_all_layers, bool invert)
364     if (!dt)
365         return;
367     Inkscape::Selection *selection = sp_desktop_selection(dt);
369     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
370     
371     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
372     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
373     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
374     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
376     GSList *items = NULL;
378     GSList const *exclude = NULL;
379     if (invert) {
380         exclude = selection->itemList();
381     }
383     if (force_all_layers)
384         inlayer = PREFS_SELECTION_ALL;
386     switch (inlayer) {
387         case PREFS_SELECTION_LAYER: {
388         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
389              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
390         return;
392         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
394         for (GSList *i = all_items; i; i = i->next) {
395             SPItem *item = SP_ITEM (i->data);
397             if (item && (!onlysensitive || !item->isLocked())) {
398                 if (!onlyvisible || !dt->itemIsHidden(item)) {
399                     if (!dt->isLayer(item)) {
400                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
401                             items = g_slist_prepend (items, item); // leave it in the list
402                         }
403                     }
404                 }
405             }
406         }
408         g_slist_free (all_items);
409             break;
410         }
411         case PREFS_SELECTION_LAYER_RECURSIVE: {
412             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
413             break;
414         }
415         default: {
416         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
417             break;
418     }
419     }
421     selection->setList (items);
423     if (items) {
424         g_slist_free (items);
425     }
428 void sp_edit_select_all (SPDesktop *desktop)
430     sp_edit_select_all_full (desktop, false, false);
433 void sp_edit_select_all_in_all_layers (SPDesktop *desktop)
435     sp_edit_select_all_full (desktop, true, false);
438 void sp_edit_invert (SPDesktop *desktop)
440     sp_edit_select_all_full (desktop, false, true);
443 void sp_edit_invert_in_all_layers (SPDesktop *desktop)
445     sp_edit_select_all_full (desktop, true, true);
448 void sp_selection_group(SPDesktop *desktop)
450     if (desktop == NULL)
451         return;
453     SPDocument *doc = sp_desktop_document (desktop);
454     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
456     Inkscape::Selection *selection = sp_desktop_selection(desktop);
458     // Check if something is selected.
459     if (selection->isEmpty()) {
460         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
461         return;
462     }
464     GSList const *l = (GSList *) selection->reprList();
466     GSList *p = g_slist_copy((GSList *) l);
468     selection->clear();
470     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
472     // Remember the position and parent of the topmost object.
473     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
474     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
476     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
478     while (p) {
479         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
481         if (current->parent() == topmost_parent) {
482             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
483             sp_repr_unparent(current);
484             group->appendChild(spnew);
485             Inkscape::GC::release(spnew);
486             topmost --; // only reduce count for those items deleted from topmost_parent
487         } else { // move it to topmost_parent first
488                 GSList *temp_clip = NULL;
490                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
491                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
492                 gchar const *t_str = current->attribute("transform");
493                 Geom::Matrix item_t (Geom::identity());
494                 if (t_str)
495                     sp_svg_transform_read(t_str, &item_t);
496                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
497                 //FIXME: when moving both clone and original from a transformed group (either by
498                 //grouping into another parent, or by cut/paste) the transform from the original's
499                 //parent becomes embedded into original itself, and this affects its clones. Fix
500                 //this by remembering the transform diffs we write to each item into an array and
501                 //then, if this is clone, looking up its original in that array and pre-multiplying
502                 //it by the inverse of that original's transform diff.
504                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
505                 sp_repr_unparent(current);
507                 // paste into topmost_parent (temporarily)
508                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
509                 if (temp_clip) g_slist_free (temp_clip);
510                 if (copied) { // if success,
511                     // take pasted object (now in topmost_parent)
512                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
513                     // make a copy
514                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
515                     // remove pasted
516                     sp_repr_unparent(in_topmost);
517                     // put its copy into group
518                     group->appendChild(spnew);
519                     Inkscape::GC::release(spnew);
520                     g_slist_free (copied);
521                 }
522         }
523         p = g_slist_remove(p, current);
524     }
526     // Add the new group to the topmost members' parent
527     topmost_parent->appendChild(group);
529     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
530     group->setPosition(topmost + 1);
532     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
533                      _("Group"));
535     selection->set(group);
536     Inkscape::GC::release(group);
539 void sp_selection_ungroup(SPDesktop *desktop)
541     if (desktop == NULL)
542         return;
544     Inkscape::Selection *selection = sp_desktop_selection(desktop);
546     if (selection->isEmpty()) {
547         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
548         return;
549     }
551     GSList *items = g_slist_copy((GSList *) selection->itemList());
552     selection->clear();
554     // Get a copy of current selection.
555     GSList *new_select = NULL;
556     bool ungrouped = false;
557     for (GSList *i = items;
558          i != NULL;
559          i = i->next)
560     {
561         SPItem *group = (SPItem *) i->data;
563         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
564         if (!SP_IS_OBJECT(group)) {
565             continue;
566         }
568         /* We do not allow ungrouping <svg> etc. (lauris) */
569         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
570             // keep the non-group item in the new selection
571             selection->add(group);
572             continue;
573         }
575         GSList *children = NULL;
576         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
577         sp_item_group_ungroup(SP_GROUP(group), &children, false);
578         ungrouped = true;
579         // Add ungrouped items to the new selection.
580         new_select = g_slist_concat(new_select, children);
581     }
583     if (new_select) { // Set new selection.
584         selection->addList(new_select);
585         g_slist_free(new_select);
586     }
587     if (!ungrouped) {
588         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
589     }
591     g_slist_free(items);
593     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
594                      _("Ungroup"));
597 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
598 GSList *
599 sp_degroup_list (GSList *items)
601     GSList *out = NULL;
602     bool has_groups = false;
603     for (GSList *item = items; item; item = item->next) {
604         if (!SP_IS_GROUP(item->data)) {
605             out = g_slist_prepend(out, item->data);
606         } else {
607             has_groups = true;
608             GSList *members = sp_item_group_item_list (SP_GROUP(item->data));
609             for (GSList *member = members; member; member = member->next) {
610                 out = g_slist_prepend(out, member->data);
611             }
612             g_slist_free (members);
613         }
614     }
615     out = g_slist_reverse (out);
616     g_slist_free (items);
618     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
619         out = sp_degroup_list (out);
620     }
622     return out;
624  
626 /** If items in the list have a common parent, return it, otherwise return NULL */
627 static SPGroup *
628 sp_item_list_common_parent_group(GSList const *items)
630     if (!items) {
631         return NULL;
632     }
633     SPObject *parent = SP_OBJECT_PARENT(items->data);
634     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
635     if (!SP_IS_GROUP(parent)) {
636         return NULL;
637     }
638     for (items = items->next; items; items = items->next) {
639         if (SP_OBJECT_PARENT(items->data) != parent) {
640             return NULL;
641         }
642     }
644     return SP_GROUP(parent);
647 /** Finds out the minimum common bbox of the selected items. */
648 static Geom::OptRect
649 enclose_items(GSList const *items)
651     g_assert(items != NULL);
653     Geom::OptRect r;
654     for (GSList const *i = items; i; i = i->next) {
655         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
656     }
657     return r;
660 SPObject *
661 prev_sibling(SPObject *child)
663     SPObject *parent = SP_OBJECT_PARENT(child);
664     if (!SP_IS_GROUP(parent)) {
665         return NULL;
666     }
667     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
668         if (i->next == child)
669             return i;
670     }
671     return NULL;
674 void
675 sp_selection_raise(SPDesktop *desktop)
677     if (!desktop)
678         return;
680     Inkscape::Selection *selection = sp_desktop_selection(desktop);
682     GSList const *items = (GSList *) selection->itemList();
683     if (!items) {
684         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
685         return;
686     }
688     SPGroup const *group = sp_item_list_common_parent_group(items);
689     if (!group) {
690         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
691         return;
692     }
694     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
696     /* Construct reverse-ordered list of selected children. */
697     GSList *rev = g_slist_copy((GSList *) items);
698     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
700     // Determine the common bbox of the selected items.
701     Geom::OptRect selected = enclose_items(items);
703     // Iterate over all objects in the selection (starting from top).
704     if (selected) {
705         while (rev) {
706             SPObject *child = SP_OBJECT(rev->data);
707             // for each selected object, find the next sibling
708             for (SPObject *newref = child->next; newref; newref = newref->next) {
709                 // if the sibling is an item AND overlaps our selection,
710                 if (SP_IS_ITEM(newref)) {
711                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
712                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
713                         // AND if it's not one of our selected objects,
714                         if (!g_slist_find((GSList *) items, newref)) {
715                             // move the selected object after that sibling
716                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
717                         }
718                         break;
719                     }
720                 }
721             }
722             rev = g_slist_remove(rev, child);
723         }
724     } else {
725         g_slist_free(rev);
726     }
728     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
729                      //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
730                      Q_("undo_action|Raise"));
733 void sp_selection_raise_to_top(SPDesktop *desktop)
735     if (desktop == NULL)
736         return;
738     SPDocument *document = sp_desktop_document(desktop);
739     Inkscape::Selection *selection = sp_desktop_selection(desktop);
741     if (selection->isEmpty()) {
742         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
743         return;
744     }
746     GSList const *items = (GSList *) selection->itemList();
748     SPGroup const *group = sp_item_list_common_parent_group(items);
749     if (!group) {
750         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
751         return;
752     }
754     GSList *rl = g_slist_copy((GSList *) selection->reprList());
755     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
757     for (GSList *l = rl; l != NULL; l = l->next) {
758         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
759         repr->setPosition(-1);
760     }
762     g_slist_free(rl);
764     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
765                      _("Raise to top"));
768 void
769 sp_selection_lower(SPDesktop *desktop)
771     if (desktop == NULL)
772         return;
774     Inkscape::Selection *selection = sp_desktop_selection(desktop);
776     GSList const *items = (GSList *) selection->itemList();
777     if (!items) {
778         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
779         return;
780     }
782     SPGroup const *group = sp_item_list_common_parent_group(items);
783     if (!group) {
784         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
785         return;
786     }
788     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
790     // Determine the common bbox of the selected items.
791     Geom::OptRect selected = enclose_items(items);
793     /* Construct direct-ordered list of selected children. */
794     GSList *rev = g_slist_copy((GSList *) items);
795     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
796     rev = g_slist_reverse(rev);
798     // Iterate over all objects in the selection (starting from top).
799     if (selected) {
800         while (rev) {
801             SPObject *child = SP_OBJECT(rev->data);
802             // for each selected object, find the prev sibling
803             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
804                 // if the sibling is an item AND overlaps our selection,
805                 if (SP_IS_ITEM(newref)) {
806                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
807                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
808                         // AND if it's not one of our selected objects,
809                         if (!g_slist_find((GSList *) items, newref)) {
810                             // move the selected object before that sibling
811                             SPObject *put_after = prev_sibling(newref);
812                             if (put_after)
813                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
814                             else
815                                 SP_OBJECT_REPR(child)->setPosition(0);
816                         }
817                         break;
818                     }
819                 }
820             }
821             rev = g_slist_remove(rev, child);
822         }
823     } else {
824         g_slist_free(rev);
825     }
827     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
828                      _("Lower"));
831 void sp_selection_lower_to_bottom(SPDesktop *desktop)
833     if (desktop == NULL)
834         return;
836     SPDocument *document = sp_desktop_document(desktop);
837     Inkscape::Selection *selection = sp_desktop_selection(desktop);
839     if (selection->isEmpty()) {
840         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
841         return;
842     }
844     GSList const *items = (GSList *) selection->itemList();
846     SPGroup const *group = sp_item_list_common_parent_group(items);
847     if (!group) {
848         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
849         return;
850     }
852     GSList *rl;
853     rl = g_slist_copy((GSList *) selection->reprList());
854     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
855     rl = g_slist_reverse(rl);
857     for (GSList *l = rl; l != NULL; l = l->next) {
858         gint minpos;
859         SPObject *pp, *pc;
860         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
861         pp = document->getObjectByRepr(sp_repr_parent(repr));
862         minpos = 0;
863         g_assert(SP_IS_GROUP(pp));
864         pc = sp_object_first_child(pp);
865         while (!SP_IS_ITEM(pc)) {
866             minpos += 1;
867             pc = pc->next;
868         }
869         repr->setPosition(minpos);
870     }
872     g_slist_free(rl);
874     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
875                      _("Lower to bottom"));
878 void
879 sp_undo(SPDesktop *desktop, SPDocument *)
881         if (!sp_document_undo(sp_desktop_document(desktop)))
882             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
885 void
886 sp_redo(SPDesktop *desktop, SPDocument *)
888         if (!sp_document_redo(sp_desktop_document(desktop)))
889             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
892 void sp_selection_cut(SPDesktop *desktop)
894     sp_selection_copy();
895     sp_selection_delete(desktop);
898 /**
899  * \pre item != NULL
900  */
901 SPCSSAttr *
902 take_style_from_item (SPItem *item)
904     // write the complete cascaded style, context-free
905     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
906     if (css == NULL)
907         return NULL;
909     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
910         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
911         // if this is a text with exactly one tspan child, merge the style of that tspan as well
912         // If this is a group, merge the style of its topmost (last) child with style
913         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
914             if (SP_OBJECT_STYLE (last_element) != NULL) {
915                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
916                 if (temp) {
917                     sp_repr_css_merge (css, temp);
918                     sp_repr_css_attr_unref (temp);
919                 }
920                 break;
921             }
922         }
923     }
924     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
925         // do not copy text properties from non-text objects, it's confusing
926         css = sp_css_attr_unset_text (css);
927     }
929     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
930     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
931     if (ex != 1.0) {
932         css = sp_css_attr_scale (css, ex);
933     }
935     return css;
939 void sp_selection_copy()
941     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
942     cm->copy();
945 void sp_selection_paste(SPDesktop *desktop, bool in_place)
947     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
948     if(cm->paste(in_place))
949         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
952 void sp_selection_paste_style(SPDesktop *desktop)
954     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
955     if(cm->pasteStyle())
956         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
960 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
962     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
963     if(cm->pastePathEffect())
964         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
965                      _("Paste live path effect"));
969 void sp_selection_remove_livepatheffect_impl(SPItem *item)
971     if ( item && SP_IS_LPE_ITEM(item) ) {
972         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
973     }
976 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
978     if (desktop == NULL) return;
980     Inkscape::Selection *selection = sp_desktop_selection(desktop);
982     // check if something is selected
983     if (selection->isEmpty()) {
984         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
985         return;
986     }
988     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
989         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
991         sp_selection_remove_livepatheffect_impl(item);
993     }
995     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
996                      _("Remove live path effect"));
999 void sp_selection_remove_filter (SPDesktop *desktop)
1001     if (desktop == NULL) return;
1003     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1005     // check if something is selected
1006     if (selection->isEmpty()) {
1007         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1008         return;
1009     }
1011     SPCSSAttr *css = sp_repr_css_attr_new();
1012     sp_repr_css_unset_property(css, "filter");
1013     sp_desktop_set_style(desktop, css);
1014     sp_repr_css_attr_unref(css);
1016     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
1017                      _("Remove filter"));
1021 void sp_selection_paste_size (SPDesktop *desktop, bool apply_x, bool apply_y)
1023     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1024     if(cm->pasteSize(false, apply_x, apply_y))
1025         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1026                      _("Paste size"));
1029 void sp_selection_paste_size_separately (SPDesktop *desktop, bool apply_x, bool apply_y)
1031     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1032     if(cm->pasteSize(true, apply_x, apply_y))
1033         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1034                      _("Paste size separately"));
1037 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1039     Inkscape::Selection *selection = sp_desktop_selection(dt);
1041     // check if something is selected
1042     if (selection->isEmpty()) {
1043         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1044         return;
1045     }
1047     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1049     bool no_more = false; // Set to true, if no more layers above
1050     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1051     if (next) {
1052         GSList *temp_clip = NULL;
1053         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1054         sp_selection_delete_impl (items, false, false);
1055         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1056         GSList *copied;
1057         if(next) {
1058             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1059         } else {
1060             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1061             no_more = true;
1062         }
1063         selection->setReprList((GSList const *) copied);
1064         g_slist_free (copied);
1065         if (temp_clip) g_slist_free (temp_clip);
1066         if (next) dt->setCurrentLayer(next);
1067         if ( !suppressDone ) {
1068             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1069                              _("Raise to next layer"));
1070         }
1071     } else {
1072         no_more = true;
1073     }
1075     if (no_more) {
1076         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1077     }
1079     g_slist_free ((GSList *) items);
1082 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1084     Inkscape::Selection *selection = sp_desktop_selection(dt);
1086     // check if something is selected
1087     if (selection->isEmpty()) {
1088         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1089         return;
1090     }
1092     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1094     bool no_more = false; // Set to true, if no more layers below
1095     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1096     if (next) {
1097         GSList *temp_clip = NULL;
1098         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
1099         sp_selection_delete_impl (items, false, false);
1100         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1101         GSList *copied;
1102         if(next) {
1103             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1104         } else {
1105             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1106             no_more = true;
1107         }
1108         selection->setReprList((GSList const *) copied);
1109         g_slist_free (copied);
1110         if (temp_clip) g_slist_free (temp_clip);
1111         if (next) dt->setCurrentLayer(next);
1112         if ( !suppressDone ) {
1113             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1114                              _("Lower to previous layer"));
1115         }
1116     } else {
1117         no_more = true;
1118     }
1120     if (no_more) {
1121         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1122     }
1124     g_slist_free ((GSList *) items);
1127 bool
1128 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1130     bool contains_original = false;
1132     bool is_use = SP_IS_USE(item);
1133     SPItem *item_use = item;
1134     SPItem *item_use_first = item;
1135     while (is_use && item_use && !contains_original)
1136     {
1137         item_use = sp_use_get_original (SP_USE(item_use));
1138         contains_original |= selection->includes(item_use);
1139         if (item_use == item_use_first)
1140             break;
1141         is_use = SP_IS_USE(item_use);
1142     }
1144     // If it's a tref, check whether the object containing the character
1145     // data is part of the selection
1146     if (!contains_original && SP_IS_TREF(item)) {
1147         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1148     }
1150     return contains_original;
1154 bool
1155 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1157     bool clone_with_original = false;
1158     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1159         SPItem *item = SP_ITEM(l->data);
1160         clone_with_original |= selection_contains_original(item, selection);
1161         if (clone_with_original)
1162             break;
1163     }
1164     return clone_with_original;
1168 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1169 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1170 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1171 that case, items are already in the new position, but the repr is in the old, and this function
1172 then simply updates the repr from item->transform.
1173  */
1174 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1176     if (selection->isEmpty())
1177         return;
1179     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1180         SPItem *item = SP_ITEM(l->data);
1182         Geom::Point old_center(0,0);
1183         if (set_i2d && item->isCenterSet())
1184             old_center = item->getCenter();
1186 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1187          At the time of writing, this is the only place to re-enable. */
1188         sp_item_update_cns(*item, selection->desktop());
1189 #endif
1191         // we're moving both a clone and its original or any ancestor in clone chain?
1192         bool transform_clone_with_original = selection_contains_original(item, selection);
1193         // ...both a text-on-path and its path?
1194         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)))) ));
1195         // ...both a flowtext and its frame?
1196         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)
1197         // ...both an offset and its source?
1198         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1200         // If we're moving a connector, we want to detach it
1201         // from shapes that aren't part of the selection, but
1202         // leave it attached if they are
1203         if (cc_item_is_connector(item)) {
1204             SPItem *attItem[2];
1205             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1207             for (int n = 0; n < 2; ++n) {
1208                 if (!selection->includes(attItem[n])) {
1209                     sp_conn_end_detach(item, n);
1210                 }
1211             }
1212         }
1214         // "clones are unmoved when original is moved" preference
1215         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1216         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1217         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1218         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1220         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1221         // transform of its original and respond to it itself. Without this, a clone is doubly
1222         // transformed, very unintuitive.
1223       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1224       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1225       // Same for linked offset if we are also moving its source: do not move it.
1226         if (transform_textpath_with_path || transform_offset_with_source) {
1227                 // restore item->transform field from the repr, in case it was changed by seltrans
1228             sp_object_read_attr (SP_OBJECT (item), "transform");
1230         } else if (transform_flowtext_with_frame) {
1231             // apply the inverse of the region's transform to the <use> so that the flow remains
1232             // the same (even though the output itself gets transformed)
1233             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1234                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1235                     continue;
1236                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1237                     if (!SP_IS_USE(use)) continue;
1238                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1239                 }
1240             }
1241         } else if (transform_clone_with_original) {
1242             // We are transforming a clone along with its original. The below matrix juggling is
1243             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1244             // transform and its move compensation are both cancelled out.
1246             // restore item->transform field from the repr, in case it was changed by seltrans
1247             sp_object_read_attr (SP_OBJECT (item), "transform");
1249             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1250             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1251             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1252             Geom::Matrix t_inv = t.inverse();
1253             Geom::Matrix result = t_inv * item->transform * t;
1255             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1256                 // we need to cancel out the move compensation, too
1258                 // find out the clone move, same as in sp_use_move_compensate
1259                 Geom::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1260                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1262                 if (prefs_parallel) {
1263                     Geom::Matrix move = result * clone_move * t_inv;
1264                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1266                 } else if (prefs_unmoved) {
1267                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1268                     //    clone_move = Geom::identity();
1269                     Geom::Matrix move = result * clone_move;
1270                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1271                 }
1273             } else {
1274                 // just apply the result
1275                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1276             }
1278         } else {
1279             if (set_i2d) {
1280                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1281             }
1282             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1283         }
1285         // if we're moving the actual object, not just updating the repr, we can transform the
1286         // center by the same matrix (only necessary for non-translations)
1287         if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1288             item->setCenter(old_center * affine);
1289             SP_OBJECT(item)->updateRepr();
1290         }
1291     }
1294 void sp_selection_remove_transform(SPDesktop *desktop)
1296     if (desktop == NULL)
1297         return;
1299     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1301     GSList const *l = (GSList *) selection->reprList();
1302     while (l != NULL) {
1303         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1304         l = l->next;
1305     }
1307     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1308                      _("Remove transform"));
1311 void
1312 sp_selection_scale_absolute(Inkscape::Selection *selection,
1313                             double const x0, double const x1,
1314                             double const y0, double const y1)
1316     if (selection->isEmpty())
1317         return;
1319     Geom::OptRect const bbox(selection->bounds());
1320     if ( !bbox ) {
1321         return;
1322     }
1324     Geom::Translate const p2o(-bbox->min());
1326     Geom::Scale const newSize(x1 - x0,
1327                             y1 - y0);
1328     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1329     Geom::Translate const o2n(x0, y0);
1330     Geom::Matrix const final( p2o * scale * o2n );
1332     sp_selection_apply_affine(selection, final);
1336 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1338     if (selection->isEmpty())
1339         return;
1341     Geom::OptRect const bbox(selection->bounds());
1343     if ( !bbox ) {
1344         return;
1345     }
1347     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1348     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1349          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1350     {
1351         return;
1352     }
1354     Geom::Translate const n2d(-align);
1355     Geom::Translate const d2n(align);
1356     Geom::Matrix const final( n2d * scale * d2n );
1357     sp_selection_apply_affine(selection, final);
1360 void
1361 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1363     Geom::Translate const d2n(center);
1364     Geom::Translate const n2d(-center);
1365     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1366     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1367     sp_selection_apply_affine(selection, final);
1370 void
1371 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1373     Geom::Translate const d2n(align);
1374     Geom::Translate const n2d(-align);
1375     Geom::Matrix const skew(1, dy,
1376                             dx, 1,
1377                             0, 0);
1378     Geom::Matrix const final( n2d * skew * d2n );
1379     sp_selection_apply_affine(selection, final);
1382 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1384     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)));
1387 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1389     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1392 /**
1393  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1394  */
1395 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1397     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1399     if (selection->isEmpty())
1400         return;
1402     GSList const *l = selection->itemList();
1403     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1404     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1405         SPItem *item = SP_ITEM(l2->data);
1406         sp_item_rotate_rel(item, rot_90);
1407     }
1409     sp_document_done(sp_desktop_document(desktop),
1410                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1411                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1414 void
1415 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1417     if (selection->isEmpty())
1418         return;
1420     boost::optional<Geom::Point> center = selection->center();
1421     if (!center) {
1422         return;
1423     }
1425     sp_selection_rotate_relative(selection, *center, angle_degrees);
1427     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1428                            ( ( angle_degrees > 0 )
1429                              ? "selector:rotate:ccw"
1430                              : "selector:rotate:cw" ),
1431                            SP_VERB_CONTEXT_SELECT,
1432                            _("Rotate"));
1435 // helper function:
1436 static
1437 Geom::Point
1438 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1439     Geom::Point m = r.midpoint();
1440     unsigned i = 0;
1441     if (p[X] < m[X]) {
1442         i = 1;
1443     }
1444     if (p[Y] < m[Y]) {
1445         i = 3 - i;
1446     }
1447     return r.corner(i);
1450 /**
1451 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1452 */
1453 void
1454 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1456     if (selection->isEmpty())
1457         return;
1459     Geom::OptRect const bbox(selection->bounds());
1460     boost::optional<Geom::Point> center = selection->center();
1462     if ( !bbox || !center ) {
1463         return;
1464     }
1466     gdouble const zoom = selection->desktop()->current_zoom();
1467     gdouble const zmove = angle / zoom;
1468     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1470     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1472     sp_selection_rotate_relative(selection, *center, zangle);
1474     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1475                            ( (angle > 0)
1476                              ? "selector:rotate:ccw"
1477                              : "selector:rotate:cw" ),
1478                            SP_VERB_CONTEXT_SELECT,
1479                            _("Rotate by pixels"));
1482 void
1483 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1485     if (selection->isEmpty())
1486         return;
1488     Geom::OptRect const bbox(selection->bounds());
1489     if (!bbox) {
1490         return;
1491     }
1493     Geom::Point const center(bbox->midpoint());
1495     // you can't scale "do nizhe pola" (below zero)
1496     double const max_len = bbox->maxExtent();
1497     if ( max_len + grow <= 1e-3 ) {
1498         return;
1499     }
1501     double const times = 1.0 + grow / max_len;
1502     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1504     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1505                            ( (grow > 0)
1506                              ? "selector:scale:larger"
1507                              : "selector:scale:smaller" ),
1508                            SP_VERB_CONTEXT_SELECT,
1509                            _("Scale"));
1512 void
1513 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1515     sp_selection_scale(selection,
1516                        grow_pixels / selection->desktop()->current_zoom());
1519 void
1520 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1522     if (selection->isEmpty())
1523         return;
1525     Geom::OptRect sel_bbox = selection->bounds();
1527     if (!sel_bbox) {
1528         return;
1529     }
1531     Geom::Point const center(sel_bbox->midpoint());
1532     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1533     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1534                      _("Scale by whole factor"));
1537 void
1538 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1540     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1541     if (selection->isEmpty()) {
1542         return;
1543     }
1545     sp_selection_move_relative(selection, dx, dy);
1547     if (dx == 0) {
1548         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1549                                _("Move vertically"));
1550     } else if (dy == 0) {
1551         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1552                                _("Move horizontally"));
1553     } else {
1554         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1555                          _("Move"));
1556     }
1559 void
1560 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1562     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1563     if (selection->isEmpty()) {
1564         return;
1565     }
1567     // same as sp_selection_move but divide deltas by zoom factor
1568     gdouble const zoom = desktop->current_zoom();
1569     gdouble const zdx = dx / zoom;
1570     gdouble const zdy = dy / zoom;
1571     sp_selection_move_relative(selection, zdx, zdy);
1573     if (dx == 0) {
1574         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1575                                _("Move vertically by pixels"));
1576     } else if (dy == 0) {
1577         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1578                                _("Move horizontally by pixels"));
1579     } else {
1580         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1581                          _("Move"));
1582     }
1585 namespace {
1587 template <typename D>
1588 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1589                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1591 template <typename D>
1592 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1593                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1595 struct Forward {
1596     typedef SPObject *Iterator;
1598     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1599     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1600     static void dispose(Iterator /*i*/) {}
1602     static SPObject *object(Iterator i) { return i; }
1603     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1604 };
1606 struct Reverse {
1607     typedef GSList *Iterator;
1609     static Iterator children(SPObject *o) {
1610         return make_list(o->firstChild(), NULL);
1611     }
1612     static Iterator siblings_after(SPObject *o) {
1613         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1614     }
1615     static void dispose(Iterator i) {
1616         g_slist_free(i);
1617     }
1619     static SPObject *object(Iterator i) {
1620         return reinterpret_cast<SPObject *>(i->data);
1621     }
1622     static Iterator next(Iterator i) { return i->next; }
1624 private:
1625     static GSList *make_list(SPObject *object, SPObject *limit) {
1626         GSList *list=NULL;
1627         while ( object != limit ) {
1628             list = g_slist_prepend(list, object);
1629             object = SP_OBJECT_NEXT(object);
1630         }
1631         return list;
1632     }
1633 };
1637 void
1638 sp_selection_item_next(SPDesktop *desktop)
1640     g_return_if_fail(desktop != NULL);
1641     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1643     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1644     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1645     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1646     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1648     SPObject *root;
1649     if (PREFS_SELECTION_ALL != inlayer) {
1650         root = selection->activeContext();
1651     } else {
1652         root = desktop->currentRoot();
1653     }
1655     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1657     if (item) {
1658         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1659         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1660             scroll_to_show_item(desktop, item);
1661         }
1662     }
1665 void
1666 sp_selection_item_prev(SPDesktop *desktop)
1668     SPDocument *document = sp_desktop_document(desktop);
1669     g_return_if_fail(document != NULL);
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<Reverse>(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 sp_selection_next_patheffect_param(SPDesktop * dt)
1697     if (!dt) return;
1699     Inkscape::Selection *selection = sp_desktop_selection(dt);
1700     if ( selection && !selection->isEmpty() ) {
1701         SPItem *item = selection->singleItem();
1702         if ( item && SP_IS_SHAPE(item)) {
1703             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1704                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1705             } else {
1706                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1707             }
1708         }
1709     }
1712 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1714     if (!dt) return;
1716     Inkscape::Selection *selection = sp_desktop_selection(dt);
1717     if ( selection && !selection->isEmpty() ) {
1718         SPItem *item = selection->singleItem();
1719         if ( item ) {
1720             SPObject *obj = NULL;
1721             if (clip)
1722                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1723             else
1724                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1726             if (obj) {
1727                 // obj is a group object, the children are the actual clippers
1728                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1729                     if ( SP_IS_ITEM(child) ) {
1730                         // If not already in nodecontext, goto it!
1731                         if (!tools_isactive(dt, TOOLS_NODES)) {
1732                             tools_switch(dt, TOOLS_NODES);
1733                         }
1735                         ShapeEditor * shape_editor = dt->event_context->shape_editor;
1736                         // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1737                         shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1738                         shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1739                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1740                         if (np) {
1741                             // take colors from prefs (same as used in outline mode)
1742                             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1743                             np->helperpath_rgba = clip ? 
1744                                 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) : 
1745                                 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1746                             np->helperpath_width = 1.0;
1747                             sp_nodepath_show_helperpath(np, true);
1748                         }
1749                         break; // break out of for loop after 1st encountered item
1750                     }
1751                 }
1752             } else if (clip) {
1753                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1754             } else {
1755                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1756             }
1757         }
1758     }
1762 namespace {
1764 template <typename D>
1765 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1766                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1768     SPObject *current=root;
1769     while (items) {
1770         SPItem *item=SP_ITEM(items->data);
1771         if ( root->isAncestorOf(item) &&
1772              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1773         {
1774             current = item;
1775             break;
1776         }
1777         items = items->next;
1778     }
1780     GSList *path=NULL;
1781     while ( current != root ) {
1782         path = g_slist_prepend(path, current);
1783         current = SP_OBJECT_PARENT(current);
1784     }
1786     SPItem *next;
1787     // first, try from the current object
1788     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1789     g_slist_free(path);
1791     if (!next) { // if we ran out of objects, start over at the root
1792         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1793     }
1795     return next;
1798 template <typename D>
1799 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1800                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1802     typename D::Iterator children;
1803     typename D::Iterator iter;
1805     SPItem *found=NULL;
1807     if (path) {
1808         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1809         g_assert(SP_OBJECT_PARENT(object) == root);
1810         if (desktop->isLayer(object)) {
1811             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1812         }
1813         iter = children = D::siblings_after(object);
1814     } else {
1815         iter = children = D::children(root);
1816     }
1818     while ( iter && !found ) {
1819         SPObject *object=D::object(iter);
1820         if (desktop->isLayer(object)) {
1821             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1822                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1823             }
1824         } else if ( SP_IS_ITEM(object) &&
1825                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1826                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1827                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1828                     !desktop->isLayer(SP_ITEM(object)) )
1829         {
1830             found = SP_ITEM(object);
1831         }
1832         iter = D::next(iter);
1833     }
1835     D::dispose(children);
1837     return found;
1842 /**
1843  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1844  * \a item.
1845  */
1846 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1848     Geom::Rect dbox = desktop->get_display_area();
1849     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1851     if ( sbox && dbox.contains(*sbox) == false ) {
1852         Geom::Point const s_dt = sbox->midpoint();
1853         Geom::Point const s_w = desktop->d2w(s_dt);
1854         Geom::Point const d_dt = dbox.midpoint();
1855         Geom::Point const d_w = desktop->d2w(d_dt);
1856         Geom::Point const moved_w( d_w - s_w );
1857         gint const dx = (gint) moved_w[X];
1858         gint const dy = (gint) moved_w[Y];
1859         desktop->scroll_world(dx, dy);
1860     }
1864 void
1865 sp_selection_clone(SPDesktop *desktop)
1867     if (desktop == NULL)
1868         return;
1870     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1872     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1874     // check if something is selected
1875     if (selection->isEmpty()) {
1876         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1877         return;
1878     }
1880     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1882     selection->clear();
1884     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1885     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1887     GSList *newsel = NULL;
1889     while (reprs) {
1890         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1891         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1893         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1894         clone->setAttribute("x", "0", false);
1895         clone->setAttribute("y", "0", false);
1896         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1897         
1898         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1899         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1901         // add the new clone to the top of the original's parent
1902         parent->appendChild(clone);
1904         newsel = g_slist_prepend(newsel, clone);
1905         reprs = g_slist_remove(reprs, sel_repr);
1906         Inkscape::GC::release(clone);
1907     }
1909     // TRANSLATORS: only translate "string" in "context|string".
1910     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1911     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1912                      Q_("action|Clone"));
1914     selection->setReprList(newsel);
1916     g_slist_free(newsel);
1919 void
1920 sp_selection_relink(SPDesktop *desktop)
1922     if (!desktop)
1923         return;
1925     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1927     if (selection->isEmpty()) {
1928         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1929         return;
1930     }
1932     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1933     const gchar *newid = cm->getFirstObjectID();
1934     if (!newid) {
1935         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1936         return;
1937     }
1938     gchar *newref = g_strdup_printf ("#%s", newid);
1940     // Get a copy of current selection.
1941     bool relinked = false;
1942     for (GSList *items = (GSList *) selection->itemList();
1943          items != NULL;
1944          items = items->next)
1945     {
1946         SPItem *item = (SPItem *) items->data;
1948         if (!SP_IS_USE(item))
1949             continue;
1951         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1952         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1953         relinked = true;
1954     }
1956     g_free(newref);
1958     if (!relinked) {
1959         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1960     } else {
1961         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1962                      _("Relink clone"));
1963     }
1967 void
1968 sp_selection_unlink(SPDesktop *desktop)
1970     if (!desktop)
1971         return;
1973     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1975     if (selection->isEmpty()) {
1976         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1977         return;
1978     }
1980     // Get a copy of current selection.
1981     GSList *new_select = NULL;
1982     bool unlinked = false;
1983     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1984          items != NULL;
1985          items = items->next)
1986     {
1987         SPItem *item = (SPItem *) items->data;
1989         if (SP_IS_TEXT(item)) {
1990             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1992             if (tspan) {
1993                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1994             }
1996             // Set unlink to true, and fall into the next if which
1997             // will include this text item in the new selection
1998             unlinked = true;
1999         }
2001         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2002             // keep the non-use item in the new selection
2003             new_select = g_slist_prepend(new_select, item);
2004             continue;
2005         }
2007         SPItem *unlink;
2008         if (SP_IS_USE(item)) {
2009             unlink = sp_use_unlink(SP_USE(item));
2010         } else /*if (SP_IS_TREF(use))*/ {
2011             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2012         }
2014         unlinked = true;
2015         // Add ungrouped items to the new selection.
2016         new_select = g_slist_prepend(new_select, unlink);
2017     }
2019     if (new_select) { // set new selection
2020         selection->clear();
2021         selection->setList(new_select);
2022         g_slist_free(new_select);
2023     }
2024     if (!unlinked) {
2025         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2026     }
2028     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2029                      _("Unlink clone"));
2032 void
2033 sp_select_clone_original(SPDesktop *desktop)
2035     if (desktop == NULL)
2036         return;
2038     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2040     SPItem *item = selection->singleItem();
2042     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.");
2044     // Check if other than two objects are selected
2045     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2046         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2047         return;
2048     }
2050     SPItem *original = NULL;
2051     if (SP_IS_USE(item)) {
2052         original = sp_use_get_original (SP_USE(item));
2053     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2054         original = sp_offset_get_source (SP_OFFSET(item));
2055     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2056         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2057     } else if (SP_IS_FLOWTEXT(item)) {
2058         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2059     } else { // it's an object that we don't know what to do with
2060         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2061         return;
2062     }
2064     if (!original) {
2065         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2066         return;
2067     }
2069     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2070         if (SP_IS_DEFS (o)) {
2071             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2072             return;
2073         }
2074     }
2076     if (original) {
2077         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2078         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2079         if (highlight) {
2080             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2081             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2082             if ( a && b ) {
2083                 // draw a flashing line between the objects
2084                 SPCurve *curve = new SPCurve();
2085                 curve->moveto(a->midpoint());
2086                 curve->lineto(b->midpoint());
2088                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2089                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2090                 sp_canvas_item_show(canvasitem);
2091                 curve->unref();
2092                 desktop->add_temporary_canvasitem (canvasitem, 1000);
2093             }
2094         }
2096         selection->clear();
2097         selection->set(original);
2098         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2099             scroll_to_show_item(desktop, original);
2100         }
2101     }
2105 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2107     if (desktop == NULL)
2108         return;
2110     SPDocument *doc = sp_desktop_document(desktop);
2111     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2113     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2115     // check if something is selected
2116     if (selection->isEmpty()) {
2117         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2118         return;
2119     }
2121     sp_document_ensure_up_to_date(doc);
2122     Geom::OptRect r = selection->bounds();
2123     boost::optional<Geom::Point> c = selection->center();
2124     if ( !r || !c ) {
2125         return;
2126     }
2128     // calculate the transform to be applied to objects to move them to 0,0
2129     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2130     move_p[Geom::Y] = -move_p[Geom::Y];
2131     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2133     GSList *items = g_slist_copy((GSList *) selection->itemList());
2135     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2137     // bottommost object, after sorting
2138     SPObject *parent = SP_OBJECT_PARENT (items->data);
2140     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2142     // remember the position of the first item
2143     gint pos = SP_OBJECT_REPR (items->data)->position();
2144     (void)pos; // TODO check why this was remembered
2146     // create a list of duplicates
2147     GSList *repr_copies = NULL;
2148     for (GSList *i = items; i != NULL; i = i->next) {
2149         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2150         repr_copies = g_slist_prepend (repr_copies, dup);
2151     }
2153     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2155     if (apply) {
2156         // delete objects so that their clones don't get alerted; this object will be restored shortly
2157         for (GSList *i = items; i != NULL; i = i->next) {
2158             SPObject *item = SP_OBJECT (i->data);
2159             item->deleteObject (false);
2160         }
2161     }
2163     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2164     // without disturbing clones.
2165     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2166     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2167     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2168     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2170     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2171                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2172                                                                               Geom::Point(r->min()[Geom::X],
2173                                                                                           r->max()[Geom::Y]))))
2174                                              * parent_transform.inverse() ),
2175                                            parent_transform * move);
2176     (void)mark_id;
2178     // restore compensation setting
2179     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2182     g_slist_free (items);
2184     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2185                       _("Objects to marker"));
2188 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2189     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2190         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2191             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2192         }
2193     } else {
2194         sp_item_convert_item_to_guides(item);
2196         if (deleteitem) {
2197             SP_OBJECT(item)->deleteObject(true);
2198         }
2199     }
2202 void sp_selection_to_guides(SPDesktop *desktop)
2204     if (desktop == NULL)
2205         return;
2207     SPDocument *doc = sp_desktop_document(desktop);
2208     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2209     // we need to copy the list because it gets reset when objects are deleted
2210     GSList *items = g_slist_copy((GSList *) selection->itemList());
2212     if (!items) {
2213         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2214         return;
2215     }
2216     
2217     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2218     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2219     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2221     for (GSList const *i = items; i != NULL; i = i->next) {
2222         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2223     }
2225     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2228 void
2229 sp_selection_tile(SPDesktop *desktop, bool apply)
2231     if (desktop == NULL)
2232         return;
2234     SPDocument *doc = sp_desktop_document(desktop);
2235     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2237     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2239     // check if something is selected
2240     if (selection->isEmpty()) {
2241         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2242         return;
2243     }
2245     sp_document_ensure_up_to_date(doc);
2246     Geom::OptRect r = selection->bounds();
2247     if ( !r ) {
2248         return;
2249     }
2251     // calculate the transform to be applied to objects to move them to 0,0
2252     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point (0, r->dimensions()[Geom::Y]));
2253     move_p[Geom::Y] = -move_p[Geom::Y];
2254     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2256     GSList *items = g_slist_copy((GSList *) selection->itemList());
2258     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2260     // bottommost object, after sorting
2261     SPObject *parent = SP_OBJECT_PARENT (items->data);
2263     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2265     // remember the position of the first item
2266     gint pos = SP_OBJECT_REPR (items->data)->position();
2268     // create a list of duplicates
2269     GSList *repr_copies = NULL;
2270     for (GSList *i = items; i != NULL; i = i->next) {
2271         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2272         repr_copies = g_slist_prepend (repr_copies, dup);
2273     }
2274     // restore the z-order after prepends
2275     repr_copies = g_slist_reverse (repr_copies);
2277     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2279     if (apply) {
2280         // delete objects so that their clones don't get alerted; this object will be restored shortly
2281         for (GSList *i = items; i != NULL; i = i->next) {
2282             SPObject *item = SP_OBJECT (i->data);
2283             item->deleteObject (false);
2284         }
2285     }
2287     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2288     // without disturbing clones.
2289     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2290     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2291     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2292     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2294     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2295                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2296                                                                                             r->max()[Geom::Y]))))
2297                                          * to_2geom(parent_transform.inverse()) ),
2298                                        parent_transform * move);
2300     // restore compensation setting
2301     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2303     if (apply) {
2304         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2305         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2307         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2308         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2310         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2311         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2312         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2313         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2315         // restore parent and position
2316         SP_OBJECT_REPR (parent)->appendChild(rect);
2317         rect->setPosition(pos > 0 ? pos : 0);
2318         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2320         Inkscape::GC::release(rect);
2322         selection->clear();
2323         selection->set(rectangle);
2324     }
2326     g_slist_free (items);
2328     sp_document_done (doc, SP_VERB_EDIT_TILE,
2329                       _("Objects to pattern"));
2332 void
2333 sp_selection_untile(SPDesktop *desktop)
2335     if (desktop == NULL)
2336         return;
2338     SPDocument *doc = sp_desktop_document(desktop);
2339     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2341     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2343     // check if something is selected
2344     if (selection->isEmpty()) {
2345         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2346         return;
2347     }
2349     GSList *new_select = NULL;
2351     bool did = false;
2353     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2354          items != NULL;
2355          items = items->next) {
2357         SPItem *item = (SPItem *) items->data;
2359         SPStyle *style = SP_OBJECT_STYLE (item);
2361         if (!style || !style->fill.isPaintserver())
2362             continue;
2364         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2366         if (!SP_IS_PATTERN(server))
2367             continue;
2369         did = true;
2371         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2373         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform (SP_PATTERN (server)));
2374         pat_transform *= item->transform;
2376         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2377             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2378             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2380            // FIXME: relink clones to the new canvas objects
2381            // use SPObject::setid when mental finishes it to steal ids of
2383             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2384             sp_document_ensure_up_to_date (doc);
2386             Geom::Matrix transform( i->transform * pat_transform );
2387             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2389             new_select = g_slist_prepend(new_select, i);
2390         }
2392         SPCSSAttr *css = sp_repr_css_attr_new ();
2393         sp_repr_css_set_property (css, "fill", "none");
2394         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2395     }
2397     if (!did) {
2398         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2399     } else {
2400         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2401                          _("Pattern to objects"));
2402         selection->setList(new_select);
2403     }
2406 void
2407 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2409     if (selection->isEmpty()) {
2410         return;
2411     }
2413     GSList const *reprlst = selection->reprList();
2414     bool filename_search = TRUE;
2415     bool xdpi_search = TRUE;
2416     bool ydpi_search = TRUE;
2418     for(; reprlst != NULL &&
2419             filename_search &&
2420             xdpi_search &&
2421             ydpi_search;
2422         reprlst = reprlst->next) {
2423         gchar const *dpi_string;
2424         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2426         if (filename_search) {
2427             *filename = repr->attribute("inkscape:export-filename");
2428             if (*filename != NULL)
2429                 filename_search = FALSE;
2430         }
2432         if (xdpi_search) {
2433             dpi_string = NULL;
2434             dpi_string = repr->attribute("inkscape:export-xdpi");
2435             if (dpi_string != NULL) {
2436                 *xdpi = atof(dpi_string);
2437                 xdpi_search = FALSE;
2438             }
2439         }
2441         if (ydpi_search) {
2442             dpi_string = NULL;
2443             dpi_string = repr->attribute("inkscape:export-ydpi");
2444             if (dpi_string != NULL) {
2445                 *ydpi = atof(dpi_string);
2446                 ydpi_search = FALSE;
2447             }
2448         }
2449     }
2452 void
2453 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2455     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2456     gchar const *dpi_string;
2458     *filename = repr->attribute("inkscape:export-filename");
2460     dpi_string = NULL;
2461     dpi_string = repr->attribute("inkscape:export-xdpi");
2462     if (dpi_string != NULL) {
2463         *xdpi = atof(dpi_string);
2464     }
2466     dpi_string = NULL;
2467     dpi_string = repr->attribute("inkscape:export-ydpi");
2468     if (dpi_string != NULL) {
2469         *ydpi = atof(dpi_string);
2470     }
2473 void
2474 sp_selection_create_bitmap_copy (SPDesktop *desktop)
2476     if (desktop == NULL)
2477         return;
2479     SPDocument *document = sp_desktop_document(desktop);
2480     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2482     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2484     // check if something is selected
2485     if (selection->isEmpty()) {
2486         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2487         return;
2488     }
2490     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2491     // set "busy" cursor
2492     desktop->setWaitingCursor();
2494     // Get the bounding box of the selection
2495     NRRect bbox;
2496     sp_document_ensure_up_to_date (document);
2497     selection->bounds(&bbox);
2498     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2499         desktop->clearWaitingCursor();
2500         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2501     }
2503     // List of the items to show; all others will be hidden
2504     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2506     // Sort items so that the topmost comes last
2507     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2509     // Generate a random value from the current time (you may create bitmap from the same object(s)
2510     // multiple times, and this is done so that they don't clash)
2511     GTimeVal cu;
2512     g_get_current_time (&cu);
2513     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2515     // Create the filename
2516     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2517     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2518     // digits, and a few other chars, with "_"
2519     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2521     // Build the complete path by adding document base dir, if set, otherwise home dir
2522     gchar * directory = NULL;
2523     if (SP_DOCUMENT_URI(document)) {
2524         directory = g_dirname(SP_DOCUMENT_URI(document));
2525     }
2526     if (directory == NULL) {
2527         directory = homedir_path(NULL);
2528     }
2529     gchar *filepath = g_build_filename (directory, filename, NULL);
2531     //g_print ("%s\n", filepath);
2533     // Remember parent and z-order of the topmost one
2534     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2535     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2536     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2538     // Calculate resolution
2539     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2540     double res;
2541     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2542     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2543     if (0 < prefs_res) {
2544         // If it's given explicitly in prefs, take it
2545         res = prefs_res;
2546     } else if (0 < prefs_min) {
2547         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2548         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2549     } else {
2550         float hint_xdpi = 0, hint_ydpi = 0;
2551         char const *hint_filename;
2552         // take resolution hint from the selected objects
2553         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2554         if (hint_xdpi != 0) {
2555             res = hint_xdpi;
2556         } else {
2557             // take resolution hint from the document
2558             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2559             if (hint_xdpi != 0) {
2560                 res = hint_xdpi;
2561             } else {
2562                 // if all else fails, take the default 90 dpi
2563                 res = PX_PER_IN;
2564             }
2565         }
2566     }
2568     // The width and height of the bitmap in pixels
2569     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2570     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2572     // Find out if we have to run an external filter
2573     gchar const *run = NULL;
2574     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2575     if (!filter.empty()) {
2576         // filter command is given;
2577         // see if we have a parameter to pass to it
2578         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2579         if (!param1.empty()) {
2580             if (param1[param1.length() - 1] == '%') {
2581                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2582                 gchar p1[256];
2583                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1.data(), NULL) * MAX(width, height) / 100));
2584                 // the first param is always the image filename, the second is param1
2585                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, p1);
2586             } else {
2587                 // otherwise pass the param1 unchanged
2588                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, param1.data());
2589             }
2590         } else {
2591             // run without extra parameter
2592             run = g_strdup_printf ("%s \"%s\"", filter.data(), filepath);
2593         }
2594     }
2596     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2597     Geom::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2598     Geom::Matrix t;
2600     double shift_x = bbox.x0;
2601     double shift_y = bbox.y1;
2602     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2603         shift_x = round (shift_x);
2604         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2605     }
2606     t = Geom::Scale(1, -1) * Geom::Translate (shift_x, shift_y) * eek.inverse();
2608     // Do the export
2609     sp_export_png_file(document, filepath,
2610                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2611                    width, height, res, res,
2612                    (guint32) 0xffffff00,
2613                    NULL, NULL,
2614                    true,  /*bool force_overwrite,*/
2615                    items);
2617     g_slist_free (items);
2619     // Run filter, if any
2620     if (run) {
2621         g_print ("Running external filter: %s\n", run);
2622         int retval;
2623         retval = system (run);
2624     }
2626     // Import the image back
2627     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2628     if (pb) {
2629         // Create the repr for the image
2630         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2631         repr->setAttribute("xlink:href", filename);
2632         repr->setAttribute("sodipodi:absref", filepath);
2633         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2634             sp_repr_set_svg_double(repr, "width", width);
2635             sp_repr_set_svg_double(repr, "height", height);
2636         } else {
2637             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2638             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2639         }
2641         // Write transform
2642         gchar *c=sp_svg_transform_write(t);
2643         repr->setAttribute("transform", c);
2644         g_free(c);
2646         // add the new repr to the parent
2647         parent->appendChild(repr);
2649         // move to the saved position
2650         repr->setPosition(pos > 0 ? pos + 1 : 1);
2652         // Set selection to the new image
2653         selection->clear();
2654         selection->add(repr);
2656         // Clean up
2657         Inkscape::GC::release(repr);
2658         gdk_pixbuf_unref (pb);
2660         // Complete undoable transaction
2661         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2662                           _("Create bitmap"));
2663     }
2665     desktop->clearWaitingCursor();
2667     g_free (filename);
2668     g_free (filepath);
2671 /**
2672  * \brief Creates a mask or clipPath from selection
2673  * Two different modes:
2674  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2675  *       and is applied to current layer
2676  *  otherwise, topmost object is used as mask for other objects
2677  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2678  *
2679  */
2680 void
2681 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2683     if (desktop == NULL)
2684         return;
2686     SPDocument *doc = sp_desktop_document(desktop);
2687     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2689     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2691     // check if something is selected
2692     bool is_empty = selection->isEmpty();
2693     if ( apply_to_layer && is_empty) {
2694         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2695         return;
2696     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2697         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2698         return;
2699     }
2701     // FIXME: temporary patch to prevent crash!
2702     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2703     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2704     if (clone_with_original) {
2705         return; // in this version, you cannot clip/mask an object with its own clone
2706     }
2707     // /END FIXME
2709     sp_document_ensure_up_to_date(doc);
2711     GSList *items = g_slist_copy((GSList *) selection->itemList());
2713     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2715     // create a list of duplicates
2716     GSList *mask_items = NULL;
2717     GSList *apply_to_items = NULL;
2718     GSList *items_to_delete = NULL;
2719     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2720     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2721     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2723     if (apply_to_layer) {
2724         // all selected items are used for mask, which is applied to a layer
2725         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2727         for (GSList *i = items; i != NULL; i = i->next) {
2728             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2729             mask_items = g_slist_prepend (mask_items, dup);
2731             if (remove_original) {
2732                 SPObject *item = SP_OBJECT (i->data);
2733                 items_to_delete = g_slist_prepend (items_to_delete, item);
2734             }
2735         }
2736     } else if (!topmost) {
2737         // topmost item is used as a mask, which is applied to other items in a selection
2738         GSList *i = items;
2739         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2740         mask_items = g_slist_prepend (mask_items, dup);
2742         if (remove_original) {
2743             SPObject *item = SP_OBJECT (i->data);
2744             items_to_delete = g_slist_prepend (items_to_delete, item);
2745         }
2747         for (i = i->next; i != NULL; i = i->next) {
2748             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2749         }
2750     } else {
2751         GSList *i = NULL;
2752         for (i = items; NULL != i->next; i = i->next) {
2753             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2754         }
2756         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2757         mask_items = g_slist_prepend (mask_items, dup);
2759         if (remove_original) {
2760             SPObject *item = SP_OBJECT (i->data);
2761             items_to_delete = g_slist_prepend (items_to_delete, item);
2762         }
2763     }
2765     g_slist_free (items);
2766     items = NULL;
2768     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2769     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2770         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2771         // inverted object transform should be applied to a mask object,
2772         // as mask is calculated in user space (after applying transform)
2773         Geom::Matrix maskTransform (item->transform.inverse());
2775         GSList *mask_items_dup = NULL;
2776         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2777             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2778             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2779         }
2781         gchar const *mask_id = NULL;
2782         if (apply_clip_path) {
2783             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2784         } else {
2785             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2786         }
2788         g_slist_free (mask_items_dup);
2789         mask_items_dup = NULL;
2791         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2792     }
2794     g_slist_free (mask_items);
2795     g_slist_free (apply_to_items);
2797     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2798         SPObject *item = SP_OBJECT (i->data);
2799         item->deleteObject (false);
2800     }
2801     g_slist_free (items_to_delete);
2803     if (apply_clip_path)
2804         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2805     else
2806         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2809 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2810     if (desktop == NULL)
2811         return;
2813     SPDocument *doc = sp_desktop_document(desktop);
2814     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2815     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2817     // check if something is selected
2818     if (selection->isEmpty()) {
2819         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2820         return;
2821     }
2823     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2824     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2825     sp_document_ensure_up_to_date(doc);
2827     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2828     std::map<SPObject*,SPItem*> referenced_objects; 
2829     // SPObject* refers to a group containing the clipped path or mask itself, 
2830     // whereas SPItem* refers to the item being clipped or masked
2831     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2832         if (remove_original) {
2833             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2834             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2835             Inkscape::URIReference *uri_ref = NULL;
2837             if (apply_clip_path) {
2838                 uri_ref = item->clip_ref;
2839             } else {
2840                 uri_ref = item->mask_ref;
2841             }
2843             // collect distinct mask object (and associate with item to apply transform)
2844             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2845                 referenced_objects[uri_ref->getObject()] = item;
2846             }
2847         }
2849         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2850     }
2852     // restore mask objects into a document
2853     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2854         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2855         GSList *items_to_move = NULL;
2856         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2857             // Collect all clipped paths and masks within a single group 
2858             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2859             items_to_move = g_slist_prepend (items_to_move, copy);
2860         }
2862         if (!obj->isReferenced()) {
2863             // delete from defs if no other object references this mask
2864             obj->deleteObject(false);
2865         }
2867         // remember parent and position of the item to which the clippath/mask was applied
2868         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2869         gint pos = SP_OBJECT_REPR((*it).second)->position();
2871         // Iterate through all clipped paths / masks
2872         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2873             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2875             // insert into parent, restore pos
2876             parent->appendChild(repr);
2877             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2879             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2880             selection->add(repr);
2882             // transform mask, so it is moved the same spot where mask was applied
2883             Geom::Matrix transform (mask_item->transform);
2884             transform *= (*it).second->transform;
2885             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2886         }
2888         g_slist_free (items_to_move);
2889     }
2891     if (apply_clip_path)
2892         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2893     else
2894         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2897 /**
2898  * Returns true if an undoable change should be recorded.
2899  */
2900 bool
2901 fit_canvas_to_selection(SPDesktop *desktop)
2903     g_return_val_if_fail(desktop != NULL, false);
2904     SPDocument *doc = sp_desktop_document(desktop);
2906     g_return_val_if_fail(doc != NULL, false);
2907     g_return_val_if_fail(desktop->selection != NULL, false);
2909     if (desktop->selection->isEmpty()) {
2910         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2911         return false;
2912     }
2913     Geom::OptRect const bbox(desktop->selection->bounds());
2914     if (bbox) {
2915         doc->fitToRect(*bbox);
2916         return true;
2917     } else {
2918         return false;
2919     }
2922 /**
2923  * Fit canvas to the bounding box of the selection, as an undoable action.
2924  */
2925 void
2926 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2928     if (fit_canvas_to_selection(desktop)) {
2929         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2930                          _("Fit Page to Selection"));
2931     }
2934 bool
2935 fit_canvas_to_drawing(SPDocument *doc)
2937     g_return_val_if_fail(doc != NULL, false);
2939     sp_document_ensure_up_to_date(doc);
2940     SPItem const *const root = SP_ITEM(doc->root);
2941     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2942     if (bbox) {
2943         doc->fitToRect(*bbox);
2944         return true;
2945     } else {
2946         return false;
2947     }
2950 void
2951 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2953     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2954         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2955                          _("Fit Page to Drawing"));
2956     }
2959 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2960     g_return_if_fail(desktop != NULL);
2961     SPDocument *doc = sp_desktop_document(desktop);
2963     g_return_if_fail(doc != NULL);
2964     g_return_if_fail(desktop->selection != NULL);
2966     bool const changed = ( desktop->selection->isEmpty()
2967                            ? fit_canvas_to_drawing(doc)
2968                            : fit_canvas_to_selection(desktop) );
2969     if (changed) {
2970         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2971                          _("Fit Page to Selection or Drawing"));
2972     }
2973 };
2975 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2976     // don't operate on layers
2977     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2978         f(SP_ITEM(root), desktop);
2979     }
2980     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2981         //don't recurse into locked layers
2982         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2983             itemtree_map(f, iter, desktop);
2984         }
2985     }
2988 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2989     if (item->isLocked()) {
2990         item->setLocked(FALSE);
2991     }
2994 static void unhide(SPItem *item, SPDesktop *desktop) {
2995     if (desktop->itemIsHidden(item)) {
2996         item->setExplicitlyHidden(FALSE);
2997     }
3000 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3001     if (!dt) return;
3003     SPObject *root;
3004     if (layer_only) {
3005         root = dt->currentLayer();
3006     } else {
3007         root = dt->currentRoot();
3008     }
3010     itemtree_map(f, root, dt);
3013 void unlock_all(SPDesktop *dt) {
3014     process_all(&unlock, dt, true);
3017 void unlock_all_in_all_layers(SPDesktop *dt) {
3018     process_all(&unlock, dt, false);
3021 void unhide_all(SPDesktop *dt) {
3022     process_all(&unhide, dt, true);
3025 void unhide_all_in_all_layers(SPDesktop *dt) {
3026     process_all(&unhide, dt, false);
3030 /*
3031   Local Variables:
3032   mode:c++
3033   c-file-style:"stroustrup"
3034   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3035   indent-tabs-mode:nil
3036   fill-column:99
3037   End:
3038 */
3039 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :