Code

add utility for recursively replacing groups with their members in a list of objects
[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"
86 // For clippath editing
87 #include "tools-switch.h"
88 #include "shape-editor.h"
89 #include "node-context.h"
90 #include "nodepath.h"
92 #include "ui/clipboard.h"
94 using Geom::X;
95 using Geom::Y;
97 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
98 because the layer manipulation code uses them. It should be rewritten specifically
99 for that purpose. */
101 /**
102  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
103  * then prepends the copy to 'clip'.
104  */
105 void sp_selection_copy_one (Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
107     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
109     // copy complete inherited style
110     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
111     sp_repr_css_set(copy, css, "style");
112     sp_repr_css_attr_unref(css);
114     // write the complete accumulated transform passed to us
115     // (we're dealing with unattached repr, so we write to its attr
116     // instead of using sp_item_set_transform)
117     gchar *affinestr=sp_svg_transform_write(full_t);
118     copy->setAttribute("transform", affinestr);
119     g_free(affinestr);
121     *clip = g_slist_prepend(*clip, copy);
124 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
126     // Sort items:
127     GSList *sorted_items = g_slist_copy ((GSList *) items);
128     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
130     // Copy item reprs:
131     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
132         sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
133     }
135     *clip = g_slist_reverse(*clip);
136     g_slist_free ((GSList *) sorted_items);
139 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
141     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
143     GSList *copied = NULL;
144     // add objects to document
145     for (GSList *l = *clip; l != NULL; l = l->next) {
146         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
147         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
149         // premultiply the item transform by the accumulated parent transform in the paste layer
150         Geom::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
151         if (!local.isIdentity()) {
152             gchar const *t_str = copy->attribute("transform");
153             Geom::Matrix item_t (Geom::identity());
154             if (t_str)
155                 sp_svg_transform_read(t_str, &item_t);
156             item_t *= local.inverse();
157             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
158             gchar *affinestr=sp_svg_transform_write(item_t);
159             copy->setAttribute("transform", affinestr);
160             g_free(affinestr);
161         }
163         parent->appendChildRepr(copy);
164         copied = g_slist_prepend(copied, copy);
165         Inkscape::GC::release(copy);
166     }
167     return copied;
170 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
172     for (GSList const *i = items ; i ; i = i->next ) {
173         sp_object_ref((SPObject *)i->data, NULL);
174     }
175     for (GSList const *i = items; i != NULL; i = i->next) {
176         SPItem *item = (SPItem *) i->data;
177         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
178         sp_object_unref((SPObject *)item, NULL);
179     }
183 void sp_selection_delete(SPDesktop *desktop)
185     if (desktop == NULL) {
186         return;
187     }
189     if (tools_isactive (desktop, TOOLS_TEXT))
190         if (sp_text_delete_selection(desktop->event_context)) {
191             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
192                              _("Delete text"));
193             return;
194         }
196     Inkscape::Selection *selection = sp_desktop_selection(desktop);
198     // check if something is selected
199     if (selection->isEmpty()) {
200         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
201         return;
202     }
204     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
205     selection->clear();
206     sp_selection_delete_impl (selected);
207     g_slist_free ((GSList *) selected);
209     /* a tool may have set up private information in it's selection context
210      * that depends on desktop items.  I think the only sane way to deal with
211      * this currently is to reset the current tool, which will reset it's
212      * associated selection context.  For example: deleting an object
213      * while moving it around the canvas.
214      */
215     tools_switch ( desktop, tools_active ( desktop ) );
217     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
218                      _("Delete"));
221 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
223     if (!obj)
224         return;
226     ids.push_back(SP_OBJECT_ID(obj));
228     if (SP_IS_GROUP(obj)) {
229         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
230             add_ids_recursive (ids, child);
231         }
232     }
235 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
237     if (desktop == NULL)
238         return;
240     SPDocument *doc = desktop->doc();
241     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
242     Inkscape::Selection *selection = sp_desktop_selection(desktop);
244     // check if something is selected
245     if (selection->isEmpty()) {
246         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
247         return;
248     }
250     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
252     selection->clear();
254     // sorting items from different parents sorts each parent's subset without possibly mixing
255     // them, just what we need
256     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
258     GSList *newsel = NULL;
260     std::vector<const gchar *> old_ids;
261     std::vector<const gchar *> new_ids;
262     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
263     bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
265     while (reprs) {
266         Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
267         Inkscape::XML::Node *parent = old_repr->parent();
268         Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
270         parent->appendChild(copy);
272         if (relink_clones) {
273             SPObject *old_obj = doc->getObjectByRepr(old_repr);
274             SPObject *new_obj = doc->getObjectByRepr(copy);
275             add_ids_recursive (old_ids, old_obj);
276             add_ids_recursive (new_ids, new_obj);
277         }
279         newsel = g_slist_prepend(newsel, copy);
280         reprs = g_slist_remove(reprs, reprs->data);
281         Inkscape::GC::release(copy);
282     }
284     if (relink_clones) {
286         g_assert (old_ids.size() == new_ids.size());
288         for(unsigned int i = 0; i < old_ids.size(); i++) {
289             const gchar *id = old_ids[i];
290             SPObject *old_clone = doc->getObjectById(id);
291             if (SP_IS_USE(old_clone)) {
292                 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
293                 for(unsigned int j = 0; j < old_ids.size(); j++) {
294                     if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
295                         // we have both orig and clone in selection, relink
296                         // std::cout << id  << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
297                         gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
298                         SPObject *new_clone = doc->getObjectById(new_ids[i]);
299                         SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
300                         new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
301                         g_free (newref);
302                     }
303                 }
304             }
305         }
306     }
309     if ( !suppressDone ) {
310         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
311                          _("Duplicate"));
312     }
314     selection->setReprList(newsel);
316     g_slist_free(newsel);
319 void sp_edit_clear_all(SPDesktop *dt)
321     if (!dt)
322         return;
324     SPDocument *doc = sp_desktop_document(dt);
325     sp_desktop_selection(dt)->clear();
327     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
328     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
330     while (items) {
331         SP_OBJECT (items->data)->deleteObject();
332         items = g_slist_remove(items, items->data);
333     }
335     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
336                      _("Delete all"));
339 GSList *
340 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
342     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
343         if (SP_IS_ITEM(child) &&
344             !desktop->isLayer(SP_ITEM(child)) &&
345             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
346             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
347             (!exclude || !g_slist_find ((GSList *) exclude, child))
348             )
349         {
350             list = g_slist_prepend (list, SP_ITEM(child));
351         }
353         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
354             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
355         }
356     }
358     return list;
361 void sp_edit_select_all_full (SPDesktop *dt, bool force_all_layers, bool invert)
363     if (!dt)
364         return;
366     Inkscape::Selection *selection = sp_desktop_selection(dt);
368     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
369     
370     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
371     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
372     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
373     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
375     GSList *items = NULL;
377     GSList const *exclude = NULL;
378     if (invert) {
379         exclude = selection->itemList();
380     }
382     if (force_all_layers)
383         inlayer = PREFS_SELECTION_ALL;
385     switch (inlayer) {
386         case PREFS_SELECTION_LAYER: {
387         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
388              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
389         return;
391         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
393         for (GSList *i = all_items; i; i = i->next) {
394             SPItem *item = SP_ITEM (i->data);
396             if (item && (!onlysensitive || !item->isLocked())) {
397                 if (!onlyvisible || !dt->itemIsHidden(item)) {
398                     if (!dt->isLayer(item)) {
399                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
400                             items = g_slist_prepend (items, item); // leave it in the list
401                         }
402                     }
403                 }
404             }
405         }
407         g_slist_free (all_items);
408             break;
409         }
410         case PREFS_SELECTION_LAYER_RECURSIVE: {
411             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
412             break;
413         }
414         default: {
415         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
416             break;
417     }
418     }
420     selection->setList (items);
422     if (items) {
423         g_slist_free (items);
424     }
427 void sp_edit_select_all (SPDesktop *desktop)
429     sp_edit_select_all_full (desktop, false, false);
432 void sp_edit_select_all_in_all_layers (SPDesktop *desktop)
434     sp_edit_select_all_full (desktop, true, false);
437 void sp_edit_invert (SPDesktop *desktop)
439     sp_edit_select_all_full (desktop, false, true);
442 void sp_edit_invert_in_all_layers (SPDesktop *desktop)
444     sp_edit_select_all_full (desktop, true, true);
447 void sp_selection_group(SPDesktop *desktop)
449     if (desktop == NULL)
450         return;
452     SPDocument *doc = sp_desktop_document (desktop);
453     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
455     Inkscape::Selection *selection = sp_desktop_selection(desktop);
457     // Check if something is selected.
458     if (selection->isEmpty()) {
459         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
460         return;
461     }
463     GSList const *l = (GSList *) selection->reprList();
465     GSList *p = g_slist_copy((GSList *) l);
467     selection->clear();
469     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
471     // Remember the position and parent of the topmost object.
472     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
473     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
475     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
477     while (p) {
478         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
480         if (current->parent() == topmost_parent) {
481             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
482             sp_repr_unparent(current);
483             group->appendChild(spnew);
484             Inkscape::GC::release(spnew);
485             topmost --; // only reduce count for those items deleted from topmost_parent
486         } else { // move it to topmost_parent first
487                 GSList *temp_clip = NULL;
489                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
490                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
491                 gchar const *t_str = current->attribute("transform");
492                 Geom::Matrix item_t (Geom::identity());
493                 if (t_str)
494                     sp_svg_transform_read(t_str, &item_t);
495                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
496                 //FIXME: when moving both clone and original from a transformed group (either by
497                 //grouping into another parent, or by cut/paste) the transform from the original's
498                 //parent becomes embedded into original itself, and this affects its clones. Fix
499                 //this by remembering the transform diffs we write to each item into an array and
500                 //then, if this is clone, looking up its original in that array and pre-multiplying
501                 //it by the inverse of that original's transform diff.
503                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
504                 sp_repr_unparent(current);
506                 // paste into topmost_parent (temporarily)
507                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
508                 if (temp_clip) g_slist_free (temp_clip);
509                 if (copied) { // if success,
510                     // take pasted object (now in topmost_parent)
511                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
512                     // make a copy
513                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
514                     // remove pasted
515                     sp_repr_unparent(in_topmost);
516                     // put its copy into group
517                     group->appendChild(spnew);
518                     Inkscape::GC::release(spnew);
519                     g_slist_free (copied);
520                 }
521         }
522         p = g_slist_remove(p, current);
523     }
525     // Add the new group to the topmost members' parent
526     topmost_parent->appendChild(group);
528     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
529     group->setPosition(topmost + 1);
531     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
532                      _("Group"));
534     selection->set(group);
535     Inkscape::GC::release(group);
538 void sp_selection_ungroup(SPDesktop *desktop)
540     if (desktop == NULL)
541         return;
543     Inkscape::Selection *selection = sp_desktop_selection(desktop);
545     if (selection->isEmpty()) {
546         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
547         return;
548     }
550     GSList *items = g_slist_copy((GSList *) selection->itemList());
551     selection->clear();
553     // Get a copy of current selection.
554     GSList *new_select = NULL;
555     bool ungrouped = false;
556     for (GSList *i = items;
557          i != NULL;
558          i = i->next)
559     {
560         SPItem *group = (SPItem *) i->data;
562         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
563         if (!SP_IS_OBJECT(group)) {
564             continue;
565         }
567         /* We do not allow ungrouping <svg> etc. (lauris) */
568         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
569             // keep the non-group item in the new selection
570             selection->add(group);
571             continue;
572         }
574         GSList *children = NULL;
575         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
576         sp_item_group_ungroup(SP_GROUP(group), &children, false);
577         ungrouped = true;
578         // Add ungrouped items to the new selection.
579         new_select = g_slist_concat(new_select, children);
580     }
582     if (new_select) { // Set new selection.
583         selection->addList(new_select);
584         g_slist_free(new_select);
585     }
586     if (!ungrouped) {
587         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
588     }
590     g_slist_free(items);
592     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
593                      _("Ungroup"));
596 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
597 GSList *
598 sp_degroup_list (GSList *items)
600     GSList *out = NULL;
601     bool has_groups = false;
602     for (GSList *item = items; item; item = item->next) {
603         if (!SP_IS_GROUP(item->data)) {
604             out = g_slist_prepend(out, item->data);
605         } else {
606             has_groups = true;
607             GSList *members = sp_item_group_item_list (SP_GROUP(item->data));
608             for (GSList *member = members; member; member = member->next) {
609                 out = g_slist_prepend(out, member->data);
610             }
611             g_slist_free (members);
612         }
613     }
614     out = g_slist_reverse (out);
615     g_slist_free (items);
617     if (has_groups) { // recurse if we unwrapped a group - it may have contained others
618         out = sp_degroup_list (out);
619     }
621     return out;
623  
625 /** If items in the list have a common parent, return it, otherwise return NULL */
626 static SPGroup *
627 sp_item_list_common_parent_group(GSList const *items)
629     if (!items) {
630         return NULL;
631     }
632     SPObject *parent = SP_OBJECT_PARENT(items->data);
633     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
634     if (!SP_IS_GROUP(parent)) {
635         return NULL;
636     }
637     for (items = items->next; items; items = items->next) {
638         if (SP_OBJECT_PARENT(items->data) != parent) {
639             return NULL;
640         }
641     }
643     return SP_GROUP(parent);
646 /** Finds out the minimum common bbox of the selected items. */
647 static Geom::OptRect
648 enclose_items(GSList const *items)
650     g_assert(items != NULL);
652     Geom::OptRect r;
653     for (GSList const *i = items; i; i = i->next) {
654         r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
655     }
656     return r;
659 SPObject *
660 prev_sibling(SPObject *child)
662     SPObject *parent = SP_OBJECT_PARENT(child);
663     if (!SP_IS_GROUP(parent)) {
664         return NULL;
665     }
666     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
667         if (i->next == child)
668             return i;
669     }
670     return NULL;
673 void
674 sp_selection_raise(SPDesktop *desktop)
676     if (!desktop)
677         return;
679     Inkscape::Selection *selection = sp_desktop_selection(desktop);
681     GSList const *items = (GSList *) selection->itemList();
682     if (!items) {
683         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
684         return;
685     }
687     SPGroup const *group = sp_item_list_common_parent_group(items);
688     if (!group) {
689         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
690         return;
691     }
693     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
695     /* Construct reverse-ordered list of selected children. */
696     GSList *rev = g_slist_copy((GSList *) items);
697     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
699     // Determine the common bbox of the selected items.
700     Geom::OptRect selected = enclose_items(items);
702     // Iterate over all objects in the selection (starting from top).
703     if (selected) {
704         while (rev) {
705             SPObject *child = SP_OBJECT(rev->data);
706             // for each selected object, find the next sibling
707             for (SPObject *newref = child->next; newref; newref = newref->next) {
708                 // if the sibling is an item AND overlaps our selection,
709                 if (SP_IS_ITEM(newref)) {
710                     Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
711                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
712                         // AND if it's not one of our selected objects,
713                         if (!g_slist_find((GSList *) items, newref)) {
714                             // move the selected object after that sibling
715                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
716                         }
717                         break;
718                     }
719                 }
720             }
721             rev = g_slist_remove(rev, child);
722         }
723     } else {
724         g_slist_free(rev);
725     }
727     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
728                      //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
729                      Q_("undo_action|Raise"));
732 void sp_selection_raise_to_top(SPDesktop *desktop)
734     if (desktop == NULL)
735         return;
737     SPDocument *document = sp_desktop_document(desktop);
738     Inkscape::Selection *selection = sp_desktop_selection(desktop);
740     if (selection->isEmpty()) {
741         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
742         return;
743     }
745     GSList const *items = (GSList *) selection->itemList();
747     SPGroup const *group = sp_item_list_common_parent_group(items);
748     if (!group) {
749         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
750         return;
751     }
753     GSList *rl = g_slist_copy((GSList *) selection->reprList());
754     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
756     for (GSList *l = rl; l != NULL; l = l->next) {
757         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
758         repr->setPosition(-1);
759     }
761     g_slist_free(rl);
763     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
764                      _("Raise to top"));
767 void
768 sp_selection_lower(SPDesktop *desktop)
770     if (desktop == NULL)
771         return;
773     Inkscape::Selection *selection = sp_desktop_selection(desktop);
775     GSList const *items = (GSList *) selection->itemList();
776     if (!items) {
777         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
778         return;
779     }
781     SPGroup const *group = sp_item_list_common_parent_group(items);
782     if (!group) {
783         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
784         return;
785     }
787     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
789     // Determine the common bbox of the selected items.
790     Geom::OptRect selected = enclose_items(items);
792     /* Construct direct-ordered list of selected children. */
793     GSList *rev = g_slist_copy((GSList *) items);
794     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
795     rev = g_slist_reverse(rev);
797     // Iterate over all objects in the selection (starting from top).
798     if (selected) {
799         while (rev) {
800             SPObject *child = SP_OBJECT(rev->data);
801             // for each selected object, find the prev sibling
802             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
803                 // if the sibling is an item AND overlaps our selection,
804                 if (SP_IS_ITEM(newref)) {
805                     Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
806                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
807                         // AND if it's not one of our selected objects,
808                         if (!g_slist_find((GSList *) items, newref)) {
809                             // move the selected object before that sibling
810                             SPObject *put_after = prev_sibling(newref);
811                             if (put_after)
812                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
813                             else
814                                 SP_OBJECT_REPR(child)->setPosition(0);
815                         }
816                         break;
817                     }
818                 }
819             }
820             rev = g_slist_remove(rev, child);
821         }
822     } else {
823         g_slist_free(rev);
824     }
826     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
827                      _("Lower"));
830 void sp_selection_lower_to_bottom(SPDesktop *desktop)
832     if (desktop == NULL)
833         return;
835     SPDocument *document = sp_desktop_document(desktop);
836     Inkscape::Selection *selection = sp_desktop_selection(desktop);
838     if (selection->isEmpty()) {
839         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
840         return;
841     }
843     GSList const *items = (GSList *) selection->itemList();
845     SPGroup const *group = sp_item_list_common_parent_group(items);
846     if (!group) {
847         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
848         return;
849     }
851     GSList *rl;
852     rl = g_slist_copy((GSList *) selection->reprList());
853     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
854     rl = g_slist_reverse(rl);
856     for (GSList *l = rl; l != NULL; l = l->next) {
857         gint minpos;
858         SPObject *pp, *pc;
859         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
860         pp = document->getObjectByRepr(sp_repr_parent(repr));
861         minpos = 0;
862         g_assert(SP_IS_GROUP(pp));
863         pc = sp_object_first_child(pp);
864         while (!SP_IS_ITEM(pc)) {
865             minpos += 1;
866             pc = pc->next;
867         }
868         repr->setPosition(minpos);
869     }
871     g_slist_free(rl);
873     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
874                      _("Lower to bottom"));
877 void
878 sp_undo(SPDesktop *desktop, SPDocument *)
880         if (!sp_document_undo(sp_desktop_document(desktop)))
881             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
884 void
885 sp_redo(SPDesktop *desktop, SPDocument *)
887         if (!sp_document_redo(sp_desktop_document(desktop)))
888             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
891 void sp_selection_cut(SPDesktop *desktop)
893     sp_selection_copy();
894     sp_selection_delete(desktop);
897 /**
898  * \pre item != NULL
899  */
900 SPCSSAttr *
901 take_style_from_item (SPItem *item)
903     // write the complete cascaded style, context-free
904     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
905     if (css == NULL)
906         return NULL;
908     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
909         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
910         // if this is a text with exactly one tspan child, merge the style of that tspan as well
911         // If this is a group, merge the style of its topmost (last) child with style
912         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
913             if (SP_OBJECT_STYLE (last_element) != NULL) {
914                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
915                 if (temp) {
916                     sp_repr_css_merge (css, temp);
917                     sp_repr_css_attr_unref (temp);
918                 }
919                 break;
920             }
921         }
922     }
923     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
924         // do not copy text properties from non-text objects, it's confusing
925         css = sp_css_attr_unset_text (css);
926     }
928     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
929     double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
930     if (ex != 1.0) {
931         css = sp_css_attr_scale (css, ex);
932     }
934     return css;
938 void sp_selection_copy()
940     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
941     cm->copy();
944 void sp_selection_paste(SPDesktop *desktop, bool in_place)
946     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
947     if(cm->paste(in_place))
948         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
951 void sp_selection_paste_style(SPDesktop *desktop)
953     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
954     if(cm->pasteStyle())
955         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
959 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
961     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
962     if(cm->pastePathEffect())
963         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
964                      _("Paste live path effect"));
968 void sp_selection_remove_livepatheffect_impl(SPItem *item)
970     if ( item && SP_IS_LPE_ITEM(item) ) {
971         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
972     }
975 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
977     if (desktop == NULL) return;
979     Inkscape::Selection *selection = sp_desktop_selection(desktop);
981     // check if something is selected
982     if (selection->isEmpty()) {
983         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
984         return;
985     }
987     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
988         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
990         sp_selection_remove_livepatheffect_impl(item);
992     }
994     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
995                      _("Remove live path effect"));
998 void sp_selection_remove_filter (SPDesktop *desktop)
1000     if (desktop == NULL) return;
1002     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1004     // check if something is selected
1005     if (selection->isEmpty()) {
1006         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1007         return;
1008     }
1010     SPCSSAttr *css = sp_repr_css_attr_new();
1011     sp_repr_css_unset_property(css, "filter");
1012     sp_desktop_set_style(desktop, css);
1013     sp_repr_css_attr_unref(css);
1015     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
1016                      _("Remove filter"));
1020 void sp_selection_paste_size (SPDesktop *desktop, bool apply_x, bool apply_y)
1022     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1023     if(cm->pasteSize(false, apply_x, apply_y))
1024         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1025                      _("Paste size"));
1028 void sp_selection_paste_size_separately (SPDesktop *desktop, bool apply_x, bool apply_y)
1030     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1031     if(cm->pasteSize(true, apply_x, apply_y))
1032         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1033                      _("Paste size separately"));
1036 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1038     Inkscape::Selection *selection = sp_desktop_selection(dt);
1040     // check if something is selected
1041     if (selection->isEmpty()) {
1042         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1043         return;
1044     }
1046     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1048     bool no_more = false; // Set to true, if no more layers above
1049     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1050     if (next) {
1051         GSList *temp_clip = NULL;
1052         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1053         sp_selection_delete_impl (items, false, false);
1054         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1055         GSList *copied;
1056         if(next) {
1057             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1058         } else {
1059             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1060             no_more = true;
1061         }
1062         selection->setReprList((GSList const *) copied);
1063         g_slist_free (copied);
1064         if (temp_clip) g_slist_free (temp_clip);
1065         if (next) dt->setCurrentLayer(next);
1066         if ( !suppressDone ) {
1067             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1068                              _("Raise to next layer"));
1069         }
1070     } else {
1071         no_more = true;
1072     }
1074     if (no_more) {
1075         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1076     }
1078     g_slist_free ((GSList *) items);
1081 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1083     Inkscape::Selection *selection = sp_desktop_selection(dt);
1085     // check if something is selected
1086     if (selection->isEmpty()) {
1087         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1088         return;
1089     }
1091     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1093     bool no_more = false; // Set to true, if no more layers below
1094     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1095     if (next) {
1096         GSList *temp_clip = NULL;
1097         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
1098         sp_selection_delete_impl (items, false, false);
1099         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1100         GSList *copied;
1101         if(next) {
1102             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1103         } else {
1104             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1105             no_more = true;
1106         }
1107         selection->setReprList((GSList const *) copied);
1108         g_slist_free (copied);
1109         if (temp_clip) g_slist_free (temp_clip);
1110         if (next) dt->setCurrentLayer(next);
1111         if ( !suppressDone ) {
1112             sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1113                              _("Lower to previous layer"));
1114         }
1115     } else {
1116         no_more = true;
1117     }
1119     if (no_more) {
1120         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1121     }
1123     g_slist_free ((GSList *) items);
1126 bool
1127 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1129     bool contains_original = false;
1131     bool is_use = SP_IS_USE(item);
1132     SPItem *item_use = item;
1133     SPItem *item_use_first = item;
1134     while (is_use && item_use && !contains_original)
1135     {
1136         item_use = sp_use_get_original (SP_USE(item_use));
1137         contains_original |= selection->includes(item_use);
1138         if (item_use == item_use_first)
1139             break;
1140         is_use = SP_IS_USE(item_use);
1141     }
1143     // If it's a tref, check whether the object containing the character
1144     // data is part of the selection
1145     if (!contains_original && SP_IS_TREF(item)) {
1146         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1147     }
1149     return contains_original;
1153 bool
1154 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1156     bool clone_with_original = false;
1157     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1158         SPItem *item = SP_ITEM(l->data);
1159         clone_with_original |= selection_contains_original(item, selection);
1160         if (clone_with_original)
1161             break;
1162     }
1163     return clone_with_original;
1167 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1168 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1169 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1170 that case, items are already in the new position, but the repr is in the old, and this function
1171 then simply updates the repr from item->transform.
1172  */
1173 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1175     if (selection->isEmpty())
1176         return;
1178     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1179         SPItem *item = SP_ITEM(l->data);
1181         Geom::Point old_center(0,0);
1182         if (set_i2d && item->isCenterSet())
1183             old_center = item->getCenter();
1185 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1186          At the time of writing, this is the only place to re-enable. */
1187         sp_item_update_cns(*item, selection->desktop());
1188 #endif
1190         // we're moving both a clone and its original or any ancestor in clone chain?
1191         bool transform_clone_with_original = selection_contains_original(item, selection);
1192         // ...both a text-on-path and its path?
1193         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)))) ));
1194         // ...both a flowtext and its frame?
1195         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)
1196         // ...both an offset and its source?
1197         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1199         // If we're moving a connector, we want to detach it
1200         // from shapes that aren't part of the selection, but
1201         // leave it attached if they are
1202         if (cc_item_is_connector(item)) {
1203             SPItem *attItem[2];
1204             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1206             for (int n = 0; n < 2; ++n) {
1207                 if (!selection->includes(attItem[n])) {
1208                     sp_conn_end_detach(item, n);
1209                 }
1210             }
1211         }
1213         // "clones are unmoved when original is moved" preference
1214         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1215         int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1216         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1217         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1219         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1220         // transform of its original and respond to it itself. Without this, a clone is doubly
1221         // transformed, very unintuitive.
1222       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1223       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1224       // Same for linked offset if we are also moving its source: do not move it.
1225         if (transform_textpath_with_path || transform_offset_with_source) {
1226                 // restore item->transform field from the repr, in case it was changed by seltrans
1227             sp_object_read_attr (SP_OBJECT (item), "transform");
1229         } else if (transform_flowtext_with_frame) {
1230             // apply the inverse of the region's transform to the <use> so that the flow remains
1231             // the same (even though the output itself gets transformed)
1232             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1233                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1234                     continue;
1235                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1236                     if (!SP_IS_USE(use)) continue;
1237                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1238                 }
1239             }
1240         } else if (transform_clone_with_original) {
1241             // We are transforming a clone along with its original. The below matrix juggling is
1242             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1243             // transform and its move compensation are both cancelled out.
1245             // restore item->transform field from the repr, in case it was changed by seltrans
1246             sp_object_read_attr (SP_OBJECT (item), "transform");
1248             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1249             Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1250             Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1251             Geom::Matrix t_inv = t.inverse();
1252             Geom::Matrix result = t_inv * item->transform * t;
1254             if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1255                 // we need to cancel out the move compensation, too
1257                 // find out the clone move, same as in sp_use_move_compensate
1258                 Geom::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1259                 Geom::Matrix clone_move = parent.inverse() * t * parent;
1261                 if (prefs_parallel) {
1262                     Geom::Matrix move = result * clone_move * t_inv;
1263                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1265                 } else if (prefs_unmoved) {
1266                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1267                     //    clone_move = Geom::identity();
1268                     Geom::Matrix move = result * clone_move;
1269                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1270                 }
1272             } else {
1273                 // just apply the result
1274                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1275             }
1277         } else {
1278             if (set_i2d) {
1279                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1280             }
1281             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1282         }
1284         // if we're moving the actual object, not just updating the repr, we can transform the
1285         // center by the same matrix (only necessary for non-translations)
1286         if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1287             item->setCenter(old_center * affine);
1288             SP_OBJECT(item)->updateRepr();
1289         }
1290     }
1293 void sp_selection_remove_transform(SPDesktop *desktop)
1295     if (desktop == NULL)
1296         return;
1298     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1300     GSList const *l = (GSList *) selection->reprList();
1301     while (l != NULL) {
1302         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1303         l = l->next;
1304     }
1306     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1307                      _("Remove transform"));
1310 void
1311 sp_selection_scale_absolute(Inkscape::Selection *selection,
1312                             double const x0, double const x1,
1313                             double const y0, double const y1)
1315     if (selection->isEmpty())
1316         return;
1318     Geom::OptRect const bbox(selection->bounds());
1319     if ( !bbox ) {
1320         return;
1321     }
1323     Geom::Translate const p2o(-bbox->min());
1325     Geom::Scale const newSize(x1 - x0,
1326                             y1 - y0);
1327     Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1328     Geom::Translate const o2n(x0, y0);
1329     Geom::Matrix const final( p2o * scale * o2n );
1331     sp_selection_apply_affine(selection, final);
1335 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1337     if (selection->isEmpty())
1338         return;
1340     Geom::OptRect const bbox(selection->bounds());
1342     if ( !bbox ) {
1343         return;
1344     }
1346     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1347     if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6  ||
1348          bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1349     {
1350         return;
1351     }
1353     Geom::Translate const n2d(-align);
1354     Geom::Translate const d2n(align);
1355     Geom::Matrix const final( n2d * scale * d2n );
1356     sp_selection_apply_affine(selection, final);
1359 void
1360 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const &center, gdouble const angle_degrees)
1362     Geom::Translate const d2n(center);
1363     Geom::Translate const n2d(-center);
1364     Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1365     Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1366     sp_selection_apply_affine(selection, final);
1369 void
1370 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1372     Geom::Translate const d2n(align);
1373     Geom::Translate const n2d(-align);
1374     Geom::Matrix const skew(1, dy,
1375                             dx, 1,
1376                             0, 0);
1377     Geom::Matrix const final( n2d * skew * d2n );
1378     sp_selection_apply_affine(selection, final);
1381 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1383     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)));
1386 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1388     sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1391 /**
1392  * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1393  */
1394 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1396     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1398     if (selection->isEmpty())
1399         return;
1401     GSList const *l = selection->itemList();
1402     Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1403     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1404         SPItem *item = SP_ITEM(l2->data);
1405         sp_item_rotate_rel(item, rot_90);
1406     }
1408     sp_document_done(sp_desktop_document(desktop),
1409                      ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1410                      ccw ? _("Rotate 90&#176; CCW") : _("Rotate 90&#176; CW"));
1413 void
1414 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1416     if (selection->isEmpty())
1417         return;
1419     boost::optional<Geom::Point> center = selection->center();
1420     if (!center) {
1421         return;
1422     }
1424     sp_selection_rotate_relative(selection, *center, angle_degrees);
1426     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1427                            ( ( angle_degrees > 0 )
1428                              ? "selector:rotate:ccw"
1429                              : "selector:rotate:cw" ),
1430                            SP_VERB_CONTEXT_SELECT,
1431                            _("Rotate"));
1434 // helper function:
1435 static
1436 Geom::Point
1437 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1438     Geom::Point m = r.midpoint();
1439     unsigned i = 0;
1440     if (p[X] < m[X]) {
1441         i = 1;
1442     }
1443     if (p[Y] < m[Y]) {
1444         i = 3 - i;
1445     }
1446     return r.corner(i);
1449 /**
1450 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1451 */
1452 void
1453 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1455     if (selection->isEmpty())
1456         return;
1458     Geom::OptRect const bbox(selection->bounds());
1459     boost::optional<Geom::Point> center = selection->center();
1461     if ( !bbox || !center ) {
1462         return;
1463     }
1465     gdouble const zoom = selection->desktop()->current_zoom();
1466     gdouble const zmove = angle / zoom;
1467     gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1469     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1471     sp_selection_rotate_relative(selection, *center, zangle);
1473     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1474                            ( (angle > 0)
1475                              ? "selector:rotate:ccw"
1476                              : "selector:rotate:cw" ),
1477                            SP_VERB_CONTEXT_SELECT,
1478                            _("Rotate by pixels"));
1481 void
1482 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1484     if (selection->isEmpty())
1485         return;
1487     Geom::OptRect const bbox(selection->bounds());
1488     if (!bbox) {
1489         return;
1490     }
1492     Geom::Point const center(bbox->midpoint());
1494     // you can't scale "do nizhe pola" (below zero)
1495     double const max_len = bbox->maxExtent();
1496     if ( max_len + grow <= 1e-3 ) {
1497         return;
1498     }
1500     double const times = 1.0 + grow / max_len;
1501     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1503     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1504                            ( (grow > 0)
1505                              ? "selector:scale:larger"
1506                              : "selector:scale:smaller" ),
1507                            SP_VERB_CONTEXT_SELECT,
1508                            _("Scale"));
1511 void
1512 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1514     sp_selection_scale(selection,
1515                        grow_pixels / selection->desktop()->current_zoom());
1518 void
1519 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1521     if (selection->isEmpty())
1522         return;
1524     Geom::OptRect sel_bbox = selection->bounds();
1526     if (!sel_bbox) {
1527         return;
1528     }
1530     Geom::Point const center(sel_bbox->midpoint());
1531     sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1532     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1533                      _("Scale by whole factor"));
1536 void
1537 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1539     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1540     if (selection->isEmpty()) {
1541         return;
1542     }
1544     sp_selection_move_relative(selection, dx, dy);
1546     if (dx == 0) {
1547         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1548                                _("Move vertically"));
1549     } else if (dy == 0) {
1550         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1551                                _("Move horizontally"));
1552     } else {
1553         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1554                          _("Move"));
1555     }
1558 void
1559 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1561     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1562     if (selection->isEmpty()) {
1563         return;
1564     }
1566     // same as sp_selection_move but divide deltas by zoom factor
1567     gdouble const zoom = desktop->current_zoom();
1568     gdouble const zdx = dx / zoom;
1569     gdouble const zdy = dy / zoom;
1570     sp_selection_move_relative(selection, zdx, zdy);
1572     if (dx == 0) {
1573         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1574                                _("Move vertically by pixels"));
1575     } else if (dy == 0) {
1576         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1577                                _("Move horizontally by pixels"));
1578     } else {
1579         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1580                          _("Move"));
1581     }
1584 namespace {
1586 template <typename D>
1587 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1588                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1590 template <typename D>
1591 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1592                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1594 struct Forward {
1595     typedef SPObject *Iterator;
1597     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1598     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1599     static void dispose(Iterator /*i*/) {}
1601     static SPObject *object(Iterator i) { return i; }
1602     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1603 };
1605 struct Reverse {
1606     typedef GSList *Iterator;
1608     static Iterator children(SPObject *o) {
1609         return make_list(o->firstChild(), NULL);
1610     }
1611     static Iterator siblings_after(SPObject *o) {
1612         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1613     }
1614     static void dispose(Iterator i) {
1615         g_slist_free(i);
1616     }
1618     static SPObject *object(Iterator i) {
1619         return reinterpret_cast<SPObject *>(i->data);
1620     }
1621     static Iterator next(Iterator i) { return i->next; }
1623 private:
1624     static GSList *make_list(SPObject *object, SPObject *limit) {
1625         GSList *list=NULL;
1626         while ( object != limit ) {
1627             list = g_slist_prepend(list, object);
1628             object = SP_OBJECT_NEXT(object);
1629         }
1630         return list;
1631     }
1632 };
1636 void
1637 sp_selection_item_next(SPDesktop *desktop)
1639     g_return_if_fail(desktop != NULL);
1640     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1642     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1643     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1644     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1645     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1647     SPObject *root;
1648     if (PREFS_SELECTION_ALL != inlayer) {
1649         root = selection->activeContext();
1650     } else {
1651         root = desktop->currentRoot();
1652     }
1654     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1656     if (item) {
1657         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1658         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1659             scroll_to_show_item(desktop, item);
1660         }
1661     }
1664 void
1665 sp_selection_item_prev(SPDesktop *desktop)
1667     SPDocument *document = sp_desktop_document(desktop);
1668     g_return_if_fail(document != NULL);
1669     g_return_if_fail(desktop != NULL);
1670     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1672     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1673     PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1674     bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1675     bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1677     SPObject *root;
1678     if (PREFS_SELECTION_ALL != inlayer) {
1679         root = selection->activeContext();
1680     } else {
1681         root = desktop->currentRoot();
1682     }
1684     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1686     if (item) {
1687         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1688         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1689             scroll_to_show_item(desktop, item);
1690         }
1691     }
1694 void sp_selection_next_patheffect_param(SPDesktop * dt)
1696     if (!dt) return;
1698     Inkscape::Selection *selection = sp_desktop_selection(dt);
1699     if ( selection && !selection->isEmpty() ) {
1700         SPItem *item = selection->singleItem();
1701         if ( item && SP_IS_SHAPE(item)) {
1702             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1703                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1704             } else {
1705                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1706             }
1707         }
1708     }
1711 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1713     if (!dt) return;
1715     Inkscape::Selection *selection = sp_desktop_selection(dt);
1716     if ( selection && !selection->isEmpty() ) {
1717         SPItem *item = selection->singleItem();
1718         if ( item ) {
1719             SPObject *obj = NULL;
1720             if (clip)
1721                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1722             else
1723                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1725             if (obj) {
1726                 // obj is a group object, the children are the actual clippers
1727                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1728                     if ( SP_IS_ITEM(child) ) {
1729                         // If not already in nodecontext, goto it!
1730                         if (!tools_isactive(dt, TOOLS_NODES)) {
1731                             tools_switch(dt, TOOLS_NODES);
1732                         }
1734                         ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
1735                         // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1736                         shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1737                         shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1738                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1739                         if (np) {
1740                             // take colors from prefs (same as used in outline mode)
1741                             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1742                             np->helperpath_rgba = clip ? 
1743                                 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) : 
1744                                 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1745                             np->helperpath_width = 1.0;
1746                             sp_nodepath_show_helperpath(np, true);
1747                         }
1748                         break; // break out of for loop after 1st encountered item
1749                     }
1750                 }
1751             } else if (clip) {
1752                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1753             } else {
1754                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1755             }
1756         }
1757     }
1761 namespace {
1763 template <typename D>
1764 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1765                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1767     SPObject *current=root;
1768     while (items) {
1769         SPItem *item=SP_ITEM(items->data);
1770         if ( root->isAncestorOf(item) &&
1771              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1772         {
1773             current = item;
1774             break;
1775         }
1776         items = items->next;
1777     }
1779     GSList *path=NULL;
1780     while ( current != root ) {
1781         path = g_slist_prepend(path, current);
1782         current = SP_OBJECT_PARENT(current);
1783     }
1785     SPItem *next;
1786     // first, try from the current object
1787     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1788     g_slist_free(path);
1790     if (!next) { // if we ran out of objects, start over at the root
1791         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1792     }
1794     return next;
1797 template <typename D>
1798 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1799                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1801     typename D::Iterator children;
1802     typename D::Iterator iter;
1804     SPItem *found=NULL;
1806     if (path) {
1807         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1808         g_assert(SP_OBJECT_PARENT(object) == root);
1809         if (desktop->isLayer(object)) {
1810             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1811         }
1812         iter = children = D::siblings_after(object);
1813     } else {
1814         iter = children = D::children(root);
1815     }
1817     while ( iter && !found ) {
1818         SPObject *object=D::object(iter);
1819         if (desktop->isLayer(object)) {
1820             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1821                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1822             }
1823         } else if ( SP_IS_ITEM(object) &&
1824                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1825                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1826                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1827                     !desktop->isLayer(SP_ITEM(object)) )
1828         {
1829             found = SP_ITEM(object);
1830         }
1831         iter = D::next(iter);
1832     }
1834     D::dispose(children);
1836     return found;
1841 /**
1842  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1843  * \a item.
1844  */
1845 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1847     Geom::Rect dbox = desktop->get_display_area();
1848     Geom::OptRect sbox = sp_item_bbox_desktop(item);
1850     if ( sbox && dbox.contains(*sbox) == false ) {
1851         Geom::Point const s_dt = sbox->midpoint();
1852         Geom::Point const s_w = desktop->d2w(s_dt);
1853         Geom::Point const d_dt = dbox.midpoint();
1854         Geom::Point const d_w = desktop->d2w(d_dt);
1855         Geom::Point const moved_w( d_w - s_w );
1856         gint const dx = (gint) moved_w[X];
1857         gint const dy = (gint) moved_w[Y];
1858         desktop->scroll_world(dx, dy);
1859     }
1863 void
1864 sp_selection_clone(SPDesktop *desktop)
1866     if (desktop == NULL)
1867         return;
1869     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1871     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1873     // check if something is selected
1874     if (selection->isEmpty()) {
1875         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1876         return;
1877     }
1879     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1881     selection->clear();
1883     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1884     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1886     GSList *newsel = NULL;
1888     while (reprs) {
1889         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1890         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1892         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1893         clone->setAttribute("x", "0", false);
1894         clone->setAttribute("y", "0", false);
1895         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1896         
1897         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1898         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1900         // add the new clone to the top of the original's parent
1901         parent->appendChild(clone);
1903         newsel = g_slist_prepend(newsel, clone);
1904         reprs = g_slist_remove(reprs, sel_repr);
1905         Inkscape::GC::release(clone);
1906     }
1908     // TRANSLATORS: only translate "string" in "context|string".
1909     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1910     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1911                      Q_("action|Clone"));
1913     selection->setReprList(newsel);
1915     g_slist_free(newsel);
1918 void
1919 sp_selection_relink(SPDesktop *desktop)
1921     if (!desktop)
1922         return;
1924     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1926     if (selection->isEmpty()) {
1927         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1928         return;
1929     }
1931     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1932     const gchar *newid = cm->getFirstObjectID();
1933     if (!newid) {
1934         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1935         return;
1936     }
1937     gchar *newref = g_strdup_printf ("#%s", newid);
1939     // Get a copy of current selection.
1940     bool relinked = false;
1941     for (GSList *items = (GSList *) selection->itemList();
1942          items != NULL;
1943          items = items->next)
1944     {
1945         SPItem *item = (SPItem *) items->data;
1947         if (!SP_IS_USE(item))
1948             continue;
1950         SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1951         SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1952         relinked = true;
1953     }
1955     g_free(newref);
1957     if (!relinked) {
1958         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1959     } else {
1960         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1961                      _("Relink clone"));
1962     }
1966 void
1967 sp_selection_unlink(SPDesktop *desktop)
1969     if (!desktop)
1970         return;
1972     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1974     if (selection->isEmpty()) {
1975         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1976         return;
1977     }
1979     // Get a copy of current selection.
1980     GSList *new_select = NULL;
1981     bool unlinked = false;
1982     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1983          items != NULL;
1984          items = items->next)
1985     {
1986         SPItem *item = (SPItem *) items->data;
1988         if (SP_IS_TEXT(item)) {
1989             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1991             if (tspan) {
1992                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1993             }
1995             // Set unlink to true, and fall into the next if which
1996             // will include this text item in the new selection
1997             unlinked = true;
1998         }
2000         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2001             // keep the non-use item in the new selection
2002             new_select = g_slist_prepend(new_select, item);
2003             continue;
2004         }
2006         SPItem *unlink;
2007         if (SP_IS_USE(item)) {
2008             unlink = sp_use_unlink(SP_USE(item));
2009         } else /*if (SP_IS_TREF(use))*/ {
2010             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2011         }
2013         unlinked = true;
2014         // Add ungrouped items to the new selection.
2015         new_select = g_slist_prepend(new_select, unlink);
2016     }
2018     if (new_select) { // set new selection
2019         selection->clear();
2020         selection->setList(new_select);
2021         g_slist_free(new_select);
2022     }
2023     if (!unlinked) {
2024         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2025     }
2027     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2028                      _("Unlink clone"));
2031 void
2032 sp_select_clone_original(SPDesktop *desktop)
2034     if (desktop == NULL)
2035         return;
2037     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2039     SPItem *item = selection->singleItem();
2041     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.");
2043     // Check if other than two objects are selected
2044     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2045         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2046         return;
2047     }
2049     SPItem *original = NULL;
2050     if (SP_IS_USE(item)) {
2051         original = sp_use_get_original (SP_USE(item));
2052     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2053         original = sp_offset_get_source (SP_OFFSET(item));
2054     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2055         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2056     } else if (SP_IS_FLOWTEXT(item)) {
2057         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2058     } else { // it's an object that we don't know what to do with
2059         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2060         return;
2061     }
2063     if (!original) {
2064         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2065         return;
2066     }
2068     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2069         if (SP_IS_DEFS (o)) {
2070             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2071             return;
2072         }
2073     }
2075     if (original) {
2076         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2077         bool highlight = prefs->getBool("/options/highlightoriginal/value");
2078         if (highlight) {
2079             Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2080             Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2081             if ( a && b ) {
2082                 // draw a flashing line between the objects
2083                 SPCurve *curve = new SPCurve();
2084                 curve->moveto(a->midpoint());
2085                 curve->lineto(b->midpoint());
2087                 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2088                 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2089                 sp_canvas_item_show(canvasitem);
2090                 curve->unref();
2091                 desktop->add_temporary_canvasitem (canvasitem, 1000);
2092             }
2093         }
2095         selection->clear();
2096         selection->set(original);
2097         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2098             scroll_to_show_item(desktop, original);
2099         }
2100     }
2104 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2106     if (desktop == NULL)
2107         return;
2109     SPDocument *doc = sp_desktop_document(desktop);
2110     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2112     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2114     // check if something is selected
2115     if (selection->isEmpty()) {
2116         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2117         return;
2118     }
2120     sp_document_ensure_up_to_date(doc);
2121     Geom::OptRect r = selection->bounds();
2122     boost::optional<Geom::Point> c = selection->center();
2123     if ( !r || !c ) {
2124         return;
2125     }
2127     // calculate the transform to be applied to objects to move them to 0,0
2128     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2129     move_p[Geom::Y] = -move_p[Geom::Y];
2130     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2132     GSList *items = g_slist_copy((GSList *) selection->itemList());
2134     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2136     // bottommost object, after sorting
2137     SPObject *parent = SP_OBJECT_PARENT (items->data);
2139     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2141     // remember the position of the first item
2142     gint pos = SP_OBJECT_REPR (items->data)->position();
2143     (void)pos; // TODO check why this was remembered
2145     // create a list of duplicates
2146     GSList *repr_copies = NULL;
2147     for (GSList *i = items; i != NULL; i = i->next) {
2148         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2149         repr_copies = g_slist_prepend (repr_copies, dup);
2150     }
2152     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2154     if (apply) {
2155         // delete objects so that their clones don't get alerted; this object will be restored shortly
2156         for (GSList *i = items; i != NULL; i = i->next) {
2157             SPObject *item = SP_OBJECT (i->data);
2158             item->deleteObject (false);
2159         }
2160     }
2162     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2163     // without disturbing clones.
2164     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2165     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2166     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2167     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2169     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2170                                            ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2171                                                                               Geom::Point(r->min()[Geom::X],
2172                                                                                           r->max()[Geom::Y]))))
2173                                              * parent_transform.inverse() ),
2174                                            parent_transform * move);
2175     (void)mark_id;
2177     // restore compensation setting
2178     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2181     g_slist_free (items);
2183     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2184                       _("Objects to marker"));
2187 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2188     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2189         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2190             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2191         }
2192     } else {
2193         sp_item_convert_item_to_guides(item);
2195         if (deleteitem) {
2196             SP_OBJECT(item)->deleteObject(true);
2197         }
2198     }
2201 void sp_selection_to_guides(SPDesktop *desktop)
2203     if (desktop == NULL)
2204         return;
2206     SPDocument *doc = sp_desktop_document(desktop);
2207     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2208     // we need to copy the list because it gets reset when objects are deleted
2209     GSList *items = g_slist_copy((GSList *) selection->itemList());
2211     if (!items) {
2212         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2213         return;
2214     }
2215     
2216     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2217     bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2218     bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2220     for (GSList const *i = items; i != NULL; i = i->next) {
2221         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2222     }
2224     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2227 void
2228 sp_selection_tile(SPDesktop *desktop, bool apply)
2230     if (desktop == NULL)
2231         return;
2233     SPDocument *doc = sp_desktop_document(desktop);
2234     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2236     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2238     // check if something is selected
2239     if (selection->isEmpty()) {
2240         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2241         return;
2242     }
2244     sp_document_ensure_up_to_date(doc);
2245     Geom::OptRect r = selection->bounds();
2246     if ( !r ) {
2247         return;
2248     }
2250     // calculate the transform to be applied to objects to move them to 0,0
2251     Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point (0, r->dimensions()[Geom::Y]));
2252     move_p[Geom::Y] = -move_p[Geom::Y];
2253     Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2255     GSList *items = g_slist_copy((GSList *) selection->itemList());
2257     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2259     // bottommost object, after sorting
2260     SPObject *parent = SP_OBJECT_PARENT (items->data);
2262     Geom::Matrix parent_transform (sp_item_i2doc_affine(SP_ITEM(parent)));
2264     // remember the position of the first item
2265     gint pos = SP_OBJECT_REPR (items->data)->position();
2267     // create a list of duplicates
2268     GSList *repr_copies = NULL;
2269     for (GSList *i = items; i != NULL; i = i->next) {
2270         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2271         repr_copies = g_slist_prepend (repr_copies, dup);
2272     }
2273     // restore the z-order after prepends
2274     repr_copies = g_slist_reverse (repr_copies);
2276     Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2278     if (apply) {
2279         // delete objects so that their clones don't get alerted; this object will be restored shortly
2280         for (GSList *i = items; i != NULL; i = i->next) {
2281             SPObject *item = SP_OBJECT (i->data);
2282             item->deleteObject (false);
2283         }
2284     }
2286     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2287     // without disturbing clones.
2288     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2289     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2290     int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2291     prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2293     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2294                                        ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2295                                                                                             r->max()[Geom::Y]))))
2296                                          * to_2geom(parent_transform.inverse()) ),
2297                                        parent_transform * move);
2299     // restore compensation setting
2300     prefs->setInt("/options/clonecompensation/value", saved_compensation);
2302     if (apply) {
2303         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2304         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2306         Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2307         Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2309         sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2310         sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2311         sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2312         sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2314         // restore parent and position
2315         SP_OBJECT_REPR (parent)->appendChild(rect);
2316         rect->setPosition(pos > 0 ? pos : 0);
2317         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2319         Inkscape::GC::release(rect);
2321         selection->clear();
2322         selection->set(rectangle);
2323     }
2325     g_slist_free (items);
2327     sp_document_done (doc, SP_VERB_EDIT_TILE,
2328                       _("Objects to pattern"));
2331 void
2332 sp_selection_untile(SPDesktop *desktop)
2334     if (desktop == NULL)
2335         return;
2337     SPDocument *doc = sp_desktop_document(desktop);
2338     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2340     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2342     // check if something is selected
2343     if (selection->isEmpty()) {
2344         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2345         return;
2346     }
2348     GSList *new_select = NULL;
2350     bool did = false;
2352     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2353          items != NULL;
2354          items = items->next) {
2356         SPItem *item = (SPItem *) items->data;
2358         SPStyle *style = SP_OBJECT_STYLE (item);
2360         if (!style || !style->fill.isPaintserver())
2361             continue;
2363         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2365         if (!SP_IS_PATTERN(server))
2366             continue;
2368         did = true;
2370         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2372         Geom::Matrix pat_transform = to_2geom(pattern_patternTransform (SP_PATTERN (server)));
2373         pat_transform *= item->transform;
2375         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2376             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2377             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2379            // FIXME: relink clones to the new canvas objects
2380            // use SPObject::setid when mental finishes it to steal ids of
2382             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2383             sp_document_ensure_up_to_date (doc);
2385             Geom::Matrix transform( i->transform * pat_transform );
2386             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2388             new_select = g_slist_prepend(new_select, i);
2389         }
2391         SPCSSAttr *css = sp_repr_css_attr_new ();
2392         sp_repr_css_set_property (css, "fill", "none");
2393         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2394     }
2396     if (!did) {
2397         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2398     } else {
2399         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2400                          _("Pattern to objects"));
2401         selection->setList(new_select);
2402     }
2405 void
2406 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2408     if (selection->isEmpty()) {
2409         return;
2410     }
2412     GSList const *reprlst = selection->reprList();
2413     bool filename_search = TRUE;
2414     bool xdpi_search = TRUE;
2415     bool ydpi_search = TRUE;
2417     for(; reprlst != NULL &&
2418             filename_search &&
2419             xdpi_search &&
2420             ydpi_search;
2421         reprlst = reprlst->next) {
2422         gchar const *dpi_string;
2423         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2425         if (filename_search) {
2426             *filename = repr->attribute("inkscape:export-filename");
2427             if (*filename != NULL)
2428                 filename_search = FALSE;
2429         }
2431         if (xdpi_search) {
2432             dpi_string = NULL;
2433             dpi_string = repr->attribute("inkscape:export-xdpi");
2434             if (dpi_string != NULL) {
2435                 *xdpi = atof(dpi_string);
2436                 xdpi_search = FALSE;
2437             }
2438         }
2440         if (ydpi_search) {
2441             dpi_string = NULL;
2442             dpi_string = repr->attribute("inkscape:export-ydpi");
2443             if (dpi_string != NULL) {
2444                 *ydpi = atof(dpi_string);
2445                 ydpi_search = FALSE;
2446             }
2447         }
2448     }
2451 void
2452 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2454     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2455     gchar const *dpi_string;
2457     *filename = repr->attribute("inkscape:export-filename");
2459     dpi_string = NULL;
2460     dpi_string = repr->attribute("inkscape:export-xdpi");
2461     if (dpi_string != NULL) {
2462         *xdpi = atof(dpi_string);
2463     }
2465     dpi_string = NULL;
2466     dpi_string = repr->attribute("inkscape:export-ydpi");
2467     if (dpi_string != NULL) {
2468         *ydpi = atof(dpi_string);
2469     }
2472 void
2473 sp_selection_create_bitmap_copy (SPDesktop *desktop)
2475     if (desktop == NULL)
2476         return;
2478     SPDocument *document = sp_desktop_document(desktop);
2479     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2481     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2483     // check if something is selected
2484     if (selection->isEmpty()) {
2485         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2486         return;
2487     }
2489     desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2490     // set "busy" cursor
2491     desktop->setWaitingCursor();
2493     // Get the bounding box of the selection
2494     NRRect bbox;
2495     sp_document_ensure_up_to_date (document);
2496     selection->bounds(&bbox);
2497     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2498         desktop->clearWaitingCursor();
2499         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2500     }
2502     // List of the items to show; all others will be hidden
2503     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2505     // Sort items so that the topmost comes last
2506     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2508     // Generate a random value from the current time (you may create bitmap from the same object(s)
2509     // multiple times, and this is done so that they don't clash)
2510     GTimeVal cu;
2511     g_get_current_time (&cu);
2512     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2514     // Create the filename
2515     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2516     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2517     // digits, and a few other chars, with "_"
2518     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2519     // Build the complete path by adding document->base if set
2520     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2522     //g_print ("%s\n", filepath);
2524     // Remember parent and z-order of the topmost one
2525     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2526     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2527     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2529     // Calculate resolution
2530     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2531     double res;
2532     int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2533     int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2534     if (0 < prefs_res) {
2535         // If it's given explicitly in prefs, take it
2536         res = prefs_res;
2537     } else if (0 < prefs_min) {
2538         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2539         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2540     } else {
2541         float hint_xdpi = 0, hint_ydpi = 0;
2542         char const *hint_filename;
2543         // take resolution hint from the selected objects
2544         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2545         if (hint_xdpi != 0) {
2546             res = hint_xdpi;
2547         } else {
2548             // take resolution hint from the document
2549             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2550             if (hint_xdpi != 0) {
2551                 res = hint_xdpi;
2552             } else {
2553                 // if all else fails, take the default 90 dpi
2554                 res = PX_PER_IN;
2555             }
2556         }
2557     }
2559     // The width and height of the bitmap in pixels
2560     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2561     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2563     // Find out if we have to run an external filter
2564     gchar const *run = NULL;
2565     Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2566     if (!filter.empty()) {
2567         // filter command is given;
2568         // see if we have a parameter to pass to it
2569         Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2570         if (!param1.empty()) {
2571             if (param1[param1.length() - 1] == '%') {
2572                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2573                 gchar p1[256];
2574                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1.data(), NULL) * MAX(width, height) / 100));
2575                 // the first param is always the image filename, the second is param1
2576                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, p1);
2577             } else {
2578                 // otherwise pass the param1 unchanged
2579                 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, param1.data());
2580             }
2581         } else {
2582             // run without extra parameter
2583             run = g_strdup_printf ("%s \"%s\"", filter.data(), filepath);
2584         }
2585     }
2587     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2588     Geom::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2589     Geom::Matrix t;
2591     double shift_x = bbox.x0;
2592     double shift_y = bbox.y1;
2593     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2594         shift_x = round (shift_x);
2595         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2596     }
2597     t = Geom::Scale(1, -1) * Geom::Translate (shift_x, shift_y) * eek.inverse();
2599     // Do the export
2600     sp_export_png_file(document, filepath,
2601                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2602                    width, height, res, res,
2603                    (guint32) 0xffffff00,
2604                    NULL, NULL,
2605                    true,  /*bool force_overwrite,*/
2606                    items);
2608     g_slist_free (items);
2610     // Run filter, if any
2611     if (run) {
2612         g_print ("Running external filter: %s\n", run);
2613         int retval;
2614         retval = system (run);
2615     }
2617     // Import the image back
2618     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2619     if (pb) {
2620         // Create the repr for the image
2621         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2622         repr->setAttribute("xlink:href", filename);
2623         repr->setAttribute("sodipodi:absref", filepath);
2624         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2625             sp_repr_set_svg_double(repr, "width", width);
2626             sp_repr_set_svg_double(repr, "height", height);
2627         } else {
2628             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2629             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2630         }
2632         // Write transform
2633         gchar *c=sp_svg_transform_write(t);
2634         repr->setAttribute("transform", c);
2635         g_free(c);
2637         // add the new repr to the parent
2638         parent->appendChild(repr);
2640         // move to the saved position
2641         repr->setPosition(pos > 0 ? pos + 1 : 1);
2643         // Set selection to the new image
2644         selection->clear();
2645         selection->add(repr);
2647         // Clean up
2648         Inkscape::GC::release(repr);
2649         gdk_pixbuf_unref (pb);
2651         // Complete undoable transaction
2652         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2653                           _("Create bitmap"));
2654     }
2656     desktop->clearWaitingCursor();
2658     g_free (filename);
2659     g_free (filepath);
2662 /**
2663  * \brief Creates a mask or clipPath from selection
2664  * Two different modes:
2665  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2666  *       and is applied to current layer
2667  *  otherwise, topmost object is used as mask for other objects
2668  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2669  *
2670  */
2671 void
2672 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2674     if (desktop == NULL)
2675         return;
2677     SPDocument *doc = sp_desktop_document(desktop);
2678     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2680     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2682     // check if something is selected
2683     bool is_empty = selection->isEmpty();
2684     if ( apply_to_layer && is_empty) {
2685         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2686         return;
2687     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2688         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2689         return;
2690     }
2692     // FIXME: temporary patch to prevent crash!
2693     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2694     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2695     if (clone_with_original) {
2696         return; // in this version, you cannot clip/mask an object with its own clone
2697     }
2698     // /END FIXME
2700     sp_document_ensure_up_to_date(doc);
2702     GSList *items = g_slist_copy((GSList *) selection->itemList());
2704     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2706     // create a list of duplicates
2707     GSList *mask_items = NULL;
2708     GSList *apply_to_items = NULL;
2709     GSList *items_to_delete = NULL;
2710     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2711     bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2712     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2714     if (apply_to_layer) {
2715         // all selected items are used for mask, which is applied to a layer
2716         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2718         for (GSList *i = items; i != NULL; i = i->next) {
2719             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2720             mask_items = g_slist_prepend (mask_items, dup);
2722             if (remove_original) {
2723                 SPObject *item = SP_OBJECT (i->data);
2724                 items_to_delete = g_slist_prepend (items_to_delete, item);
2725             }
2726         }
2727     } else if (!topmost) {
2728         // topmost item is used as a mask, which is applied to other items in a selection
2729         GSList *i = items;
2730         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2731         mask_items = g_slist_prepend (mask_items, dup);
2733         if (remove_original) {
2734             SPObject *item = SP_OBJECT (i->data);
2735             items_to_delete = g_slist_prepend (items_to_delete, item);
2736         }
2738         for (i = i->next; i != NULL; i = i->next) {
2739             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2740         }
2741     } else {
2742         GSList *i = NULL;
2743         for (i = items; NULL != i->next; i = i->next) {
2744             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2745         }
2747         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2748         mask_items = g_slist_prepend (mask_items, dup);
2750         if (remove_original) {
2751             SPObject *item = SP_OBJECT (i->data);
2752             items_to_delete = g_slist_prepend (items_to_delete, item);
2753         }
2754     }
2756     g_slist_free (items);
2757     items = NULL;
2759     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2760     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2761         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2762         // inverted object transform should be applied to a mask object,
2763         // as mask is calculated in user space (after applying transform)
2764         Geom::Matrix maskTransform (item->transform.inverse());
2766         GSList *mask_items_dup = NULL;
2767         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2768             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2769             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2770         }
2772         gchar const *mask_id = NULL;
2773         if (apply_clip_path) {
2774             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2775         } else {
2776             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2777         }
2779         g_slist_free (mask_items_dup);
2780         mask_items_dup = NULL;
2782         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2783     }
2785     g_slist_free (mask_items);
2786     g_slist_free (apply_to_items);
2788     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2789         SPObject *item = SP_OBJECT (i->data);
2790         item->deleteObject (false);
2791     }
2792     g_slist_free (items_to_delete);
2794     if (apply_clip_path)
2795         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2796     else
2797         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2800 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2801     if (desktop == NULL)
2802         return;
2804     SPDocument *doc = sp_desktop_document(desktop);
2805     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2806     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2808     // check if something is selected
2809     if (selection->isEmpty()) {
2810         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2811         return;
2812     }
2814     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2815     bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2816     sp_document_ensure_up_to_date(doc);
2818     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2819     std::map<SPObject*,SPItem*> referenced_objects; 
2820     // SPObject* refers to a group containing the clipped path or mask itself, 
2821     // whereas SPItem* refers to the item being clipped or masked
2822     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2823         if (remove_original) {
2824             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2825             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2826             Inkscape::URIReference *uri_ref = NULL;
2828             if (apply_clip_path) {
2829                 uri_ref = item->clip_ref;
2830             } else {
2831                 uri_ref = item->mask_ref;
2832             }
2834             // collect distinct mask object (and associate with item to apply transform)
2835             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2836                 referenced_objects[uri_ref->getObject()] = item;
2837             }
2838         }
2840         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2841     }
2843     // restore mask objects into a document
2844     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2845         SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2846         GSList *items_to_move = NULL;
2847         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2848             // Collect all clipped paths and masks within a single group 
2849             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2850             items_to_move = g_slist_prepend (items_to_move, copy);
2851         }
2853         if (!obj->isReferenced()) {
2854             // delete from defs if no other object references this mask
2855             obj->deleteObject(false);
2856         }
2858         // remember parent and position of the item to which the clippath/mask was applied
2859         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2860         gint pos = SP_OBJECT_REPR((*it).second)->position();
2862         // Iterate through all clipped paths / masks
2863         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2864             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2866             // insert into parent, restore pos
2867             parent->appendChild(repr);
2868             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2870             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2871             selection->add(repr);
2873             // transform mask, so it is moved the same spot where mask was applied
2874             Geom::Matrix transform (mask_item->transform);
2875             transform *= (*it).second->transform;
2876             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2877         }
2879         g_slist_free (items_to_move);
2880     }
2882     if (apply_clip_path)
2883         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2884     else
2885         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2888 /**
2889  * Returns true if an undoable change should be recorded.
2890  */
2891 bool
2892 fit_canvas_to_selection(SPDesktop *desktop)
2894     g_return_val_if_fail(desktop != NULL, false);
2895     SPDocument *doc = sp_desktop_document(desktop);
2897     g_return_val_if_fail(doc != NULL, false);
2898     g_return_val_if_fail(desktop->selection != NULL, false);
2900     if (desktop->selection->isEmpty()) {
2901         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2902         return false;
2903     }
2904     Geom::OptRect const bbox(desktop->selection->bounds());
2905     if (bbox) {
2906         doc->fitToRect(*bbox);
2907         return true;
2908     } else {
2909         return false;
2910     }
2913 /**
2914  * Fit canvas to the bounding box of the selection, as an undoable action.
2915  */
2916 void
2917 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2919     if (fit_canvas_to_selection(desktop)) {
2920         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2921                          _("Fit Page to Selection"));
2922     }
2925 bool
2926 fit_canvas_to_drawing(SPDocument *doc)
2928     g_return_val_if_fail(doc != NULL, false);
2930     sp_document_ensure_up_to_date(doc);
2931     SPItem const *const root = SP_ITEM(doc->root);
2932     Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2933     if (bbox) {
2934         doc->fitToRect(*bbox);
2935         return true;
2936     } else {
2937         return false;
2938     }
2941 void
2942 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2944     if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2945         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2946                          _("Fit Page to Drawing"));
2947     }
2950 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2951     g_return_if_fail(desktop != NULL);
2952     SPDocument *doc = sp_desktop_document(desktop);
2954     g_return_if_fail(doc != NULL);
2955     g_return_if_fail(desktop->selection != NULL);
2957     bool const changed = ( desktop->selection->isEmpty()
2958                            ? fit_canvas_to_drawing(doc)
2959                            : fit_canvas_to_selection(desktop) );
2960     if (changed) {
2961         sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2962                          _("Fit Page to Selection or Drawing"));
2963     }
2964 };
2966 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2967     // don't operate on layers
2968     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2969         f(SP_ITEM(root), desktop);
2970     }
2971     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2972         //don't recurse into locked layers
2973         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2974             itemtree_map(f, iter, desktop);
2975         }
2976     }
2979 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2980     if (item->isLocked()) {
2981         item->setLocked(FALSE);
2982     }
2985 static void unhide(SPItem *item, SPDesktop *desktop) {
2986     if (desktop->itemIsHidden(item)) {
2987         item->setExplicitlyHidden(FALSE);
2988     }
2991 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2992     if (!dt) return;
2994     SPObject *root;
2995     if (layer_only) {
2996         root = dt->currentLayer();
2997     } else {
2998         root = dt->currentRoot();
2999     }
3001     itemtree_map(f, root, dt);
3004 void unlock_all(SPDesktop *dt) {
3005     process_all(&unlock, dt, true);
3008 void unlock_all_in_all_layers(SPDesktop *dt) {
3009     process_all(&unlock, dt, false);
3012 void unhide_all(SPDesktop *dt) {
3013     process_all(&unhide, dt, true);
3016 void unhide_all_in_all_layers(SPDesktop *dt) {
3017     process_all(&unhide, dt, false);
3021 /*
3022   Local Variables:
3023   mode:c++
3024   c-file-style:"stroustrup"
3025   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3026   indent-tabs-mode:nil
3027   fill-column:99
3028   End:
3029 */
3030 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :