Code

LPE STACKING!
[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 "inkscape.h"
29 #include "desktop.h"
30 //#include "desktop-style.h"
31 #include "selection.h"
32 #include "tools-switch.h"
33 #include "desktop-handles.h"
34 #include "message-stack.h"
35 #include "sp-item-transform.h"
36 #include "marker.h"
37 #include "sp-use.h"
38 #include "sp-textpath.h"
39 #include "sp-tspan.h"
40 #include "sp-tref.h"
41 #include "sp-flowtext.h"
42 #include "sp-flowregion.h"
43 #include "text-editing.h"
44 #include "text-context.h"
45 #include "connector-context.h"
46 #include "sp-path.h"
47 #include "sp-conn-end.h"
48 #include "dropper-context.h"
49 #include <glibmm/i18n.h>
50 #include "libnr/nr-matrix-rotate-ops.h"
51 #include "libnr/nr-matrix-translate-ops.h"
52 #include "libnr/nr-rotate-fns.h"
53 #include "libnr/nr-scale-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-translate-matrix-ops.h"
56 #include "libnr/nr-translate-scale-ops.h"
57 #include "xml/repr.h"
58 #include "style.h"
59 #include "document-private.h"
60 #include "sp-gradient.h"
61 #include "sp-gradient-reference.h"
62 #include "sp-linear-gradient-fns.h"
63 #include "sp-pattern.h"
64 #include "sp-radial-gradient-fns.h"
65 #include "sp-namedview.h"
66 #include "prefs-utils.h"
67 #include "sp-offset.h"
68 #include "sp-clippath.h"
69 #include "sp-mask.h"
70 #include "file.h"
71 #include "helper/png-write.h"
72 #include "layer-fns.h"
73 #include "context-fns.h"
74 #include <map>
75 #include <cstring>
76 #include <string>
77 #include "helper/units.h"
78 #include "sp-item.h"
79 #include "box3d.h"
80 #include "unit-constants.h"
81 #include "xml/simple-document.h"
82 #include "sp-filter-reference.h"
83 #include "gradient-drag.h"
84 #include "uri-references.h"
85 #include "libnr/nr-convert2geom.h"
87 // For clippath editing
88 #include "tools-switch.h"
89 #include "shape-editor.h"
90 #include "node-context.h"
91 #include "nodepath.h"
93 #include "ui/clipboard.h"
95 using NR::X;
96 using NR::Y;
98 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
99 because the layer manipulation code uses them. It should be rewritten specifically
100 for that purpose. */
102 /**
103  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
104  * then prepends the copy to 'clip'.
105  */
106 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
108     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
110     // copy complete inherited style
111     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
112     sp_repr_css_set(copy, css, "style");
113     sp_repr_css_attr_unref(css);
115     // write the complete accumulated transform passed to us
116     // (we're dealing with unattached repr, so we write to its attr
117     // instead of using sp_item_set_transform)
118     gchar *affinestr=sp_svg_transform_write(full_t);
119     copy->setAttribute("transform", affinestr);
120     g_free(affinestr);
122     *clip = g_slist_prepend(*clip, copy);
125 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
127     // Sort items:
128     GSList *sorted_items = g_slist_copy ((GSList *) items);
129     sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
131     // Copy item reprs:
132     for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
133         sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
134     }
136     *clip = g_slist_reverse(*clip);
137     g_slist_free ((GSList *) sorted_items);
140 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
142     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
144     GSList *copied = NULL;
145     // add objects to document
146     for (GSList *l = *clip; l != NULL; l = l->next) {
147         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
148         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
150         // premultiply the item transform by the accumulated parent transform in the paste layer
151         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
152         if (!local.test_identity()) {
153             gchar const *t_str = copy->attribute("transform");
154             NR::Matrix item_t (NR::identity());
155             if (t_str)
156                 sp_svg_transform_read(t_str, &item_t);
157             item_t *= local.inverse();
158             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
159             gchar *affinestr=sp_svg_transform_write(item_t);
160             copy->setAttribute("transform", affinestr);
161             g_free(affinestr);
162         }
164         parent->appendChildRepr(copy);
165         copied = g_slist_prepend(copied, copy);
166         Inkscape::GC::release(copy);
167     }
168     return copied;
171 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
173     for (GSList const *i = items ; i ; i = i->next ) {
174         sp_object_ref((SPObject *)i->data, NULL);
175     }
176     for (GSList const *i = items; i != NULL; i = i->next) {
177         SPItem *item = (SPItem *) i->data;
178         SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
179         sp_object_unref((SPObject *)item, NULL);
180     }
184 void sp_selection_delete()
186     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
187     if (desktop == NULL) {
188         return;
189     }
191     if (tools_isactive (desktop, TOOLS_TEXT))
192         if (sp_text_delete_selection(desktop->event_context)) {
193             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
194                              _("Delete text"));
195             return;
196         }
198     Inkscape::Selection *selection = sp_desktop_selection(desktop);
200     // check if something is selected
201     if (selection->isEmpty()) {
202         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
203         return;
204     }
206     GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
207     selection->clear();
208     sp_selection_delete_impl (selected);
209     g_slist_free ((GSList *) selected);
211     /* a tool may have set up private information in it's selection context
212      * that depends on desktop items.  I think the only sane way to deal with
213      * this currently is to reset the current tool, which will reset it's
214      * associated selection context.  For example: deleting an object
215      * while moving it around the canvas.
216      */
217     tools_switch ( desktop, tools_active ( desktop ) );
219     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
220                      _("Delete"));
223 /* fixme: sequencing */
224 void sp_selection_duplicate()
226     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
227     if (desktop == NULL)
228         return;
230     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
231     Inkscape::Selection *selection = sp_desktop_selection(desktop);
233     // check if something is selected
234     if (selection->isEmpty()) {
235         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
236         return;
237     }
239     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
241     selection->clear();
243     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
244     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
246     GSList *newsel = NULL;
248     while (reprs) {
249         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
250         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
252         parent->appendChild(copy);
254         newsel = g_slist_prepend(newsel, copy);
255         reprs = g_slist_remove(reprs, reprs->data);
256         Inkscape::GC::release(copy);
257     }
259     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
260                      _("Duplicate"));
262     selection->setReprList(newsel);
264     g_slist_free(newsel);
267 void sp_edit_clear_all()
269     SPDesktop *dt = SP_ACTIVE_DESKTOP;
270     if (!dt)
271         return;
273     SPDocument *doc = sp_desktop_document(dt);
274     sp_desktop_selection(dt)->clear();
276     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
277     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
279     while (items) {
280         SP_OBJECT (items->data)->deleteObject();
281         items = g_slist_remove(items, items->data);
282     }
284     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
285                      _("Delete all"));
288 GSList *
289 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
291     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
292         if (SP_IS_ITEM(child) &&
293             !desktop->isLayer(SP_ITEM(child)) &&
294             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
295             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
296             (!exclude || !g_slist_find ((GSList *) exclude, child))
297             )
298         {
299             list = g_slist_prepend (list, SP_ITEM(child));
300         }
302         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
303             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
304         }
305     }
307     return list;
310 void sp_edit_select_all_full (bool force_all_layers, bool invert)
312     SPDesktop *dt = SP_ACTIVE_DESKTOP;
313     if (!dt)
314         return;
316     Inkscape::Selection *selection = sp_desktop_selection(dt);
318     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
320     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
321     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
322     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
324     GSList *items = NULL;
326     GSList const *exclude = NULL;
327     if (invert) {
328         exclude = selection->itemList();
329     }
331     if (force_all_layers)
332         inlayer = PREFS_SELECTION_ALL;
334     switch (inlayer) {
335         case PREFS_SELECTION_LAYER: {
336         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
337              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
338         return;
340         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
342         for (GSList *i = all_items; i; i = i->next) {
343             SPItem *item = SP_ITEM (i->data);
345             if (item && (!onlysensitive || !item->isLocked())) {
346                 if (!onlyvisible || !dt->itemIsHidden(item)) {
347                     if (!dt->isLayer(item)) {
348                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
349                             items = g_slist_prepend (items, item); // leave it in the list
350                         }
351                     }
352                 }
353             }
354         }
356         g_slist_free (all_items);
357             break;
358         }
359         case PREFS_SELECTION_LAYER_RECURSIVE: {
360             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
361             break;
362         }
363         default: {
364         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
365             break;
366     }
367     }
369     selection->setList (items);
371     if (items) {
372         g_slist_free (items);
373     }
376 void sp_edit_select_all ()
378     sp_edit_select_all_full (false, false);
381 void sp_edit_select_all_in_all_layers ()
383     sp_edit_select_all_full (true, false);
386 void sp_edit_invert ()
388     sp_edit_select_all_full (false, true);
391 void sp_edit_invert_in_all_layers ()
393     sp_edit_select_all_full (true, true);
396 void sp_selection_group()
398     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
399     if (desktop == NULL)
400         return;
402     SPDocument *doc = sp_desktop_document (desktop);
403     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
405     Inkscape::Selection *selection = sp_desktop_selection(desktop);
407     // Check if something is selected.
408     if (selection->isEmpty()) {
409         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
410         return;
411     }
413     GSList const *l = (GSList *) selection->reprList();
415     GSList *p = g_slist_copy((GSList *) l);
417     selection->clear();
419     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
421     // Remember the position and parent of the topmost object.
422     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
423     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
425     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
427     while (p) {
428         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
430         if (current->parent() == topmost_parent) {
431             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
432             sp_repr_unparent(current);
433             group->appendChild(spnew);
434             Inkscape::GC::release(spnew);
435             topmost --; // only reduce count for those items deleted from topmost_parent
436         } else { // move it to topmost_parent first
437                 GSList *temp_clip = NULL;
439                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
440                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
441                 gchar const *t_str = current->attribute("transform");
442                 NR::Matrix item_t (NR::identity());
443                 if (t_str)
444                     sp_svg_transform_read(t_str, &item_t);
445                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
446                 //FIXME: when moving both clone and original from a transformed group (either by
447                 //grouping into another parent, or by cut/paste) the transform from the original's
448                 //parent becomes embedded into original itself, and this affects its clones. Fix
449                 //this by remembering the transform diffs we write to each item into an array and
450                 //then, if this is clone, looking up its original in that array and pre-multiplying
451                 //it by the inverse of that original's transform diff.
453                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
454                 sp_repr_unparent(current);
456                 // paste into topmost_parent (temporarily)
457                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
458                 if (temp_clip) g_slist_free (temp_clip);
459                 if (copied) { // if success,
460                     // take pasted object (now in topmost_parent)
461                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
462                     // make a copy
463                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
464                     // remove pasted
465                     sp_repr_unparent(in_topmost);
466                     // put its copy into group
467                     group->appendChild(spnew);
468                     Inkscape::GC::release(spnew);
469                     g_slist_free (copied);
470                 }
471         }
472         p = g_slist_remove(p, current);
473     }
475     // Add the new group to the topmost members' parent
476     topmost_parent->appendChild(group);
478     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
479     group->setPosition(topmost + 1);
481     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
482                      _("Group"));
484     selection->set(group);
485     Inkscape::GC::release(group);
488 void sp_selection_ungroup()
490     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
491     if (desktop == NULL)
492         return;
494     Inkscape::Selection *selection = sp_desktop_selection(desktop);
496     if (selection->isEmpty()) {
497         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
498         return;
499     }
501     GSList *items = g_slist_copy((GSList *) selection->itemList());
502     selection->clear();
504     // Get a copy of current selection.
505     GSList *new_select = NULL;
506     bool ungrouped = false;
507     for (GSList *i = items;
508          i != NULL;
509          i = i->next)
510     {
511         SPItem *group = (SPItem *) i->data;
513         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
514         if (!SP_IS_OBJECT(group)) {
515             continue;
516         }
518         /* We do not allow ungrouping <svg> etc. (lauris) */
519         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
520             // keep the non-group item in the new selection
521             selection->add(group);
522             continue;
523         }
525         GSList *children = NULL;
526         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
527         sp_item_group_ungroup(SP_GROUP(group), &children, false);
528         ungrouped = true;
529         // Add ungrouped items to the new selection.
530         new_select = g_slist_concat(new_select, children);
531     }
533     if (new_select) { // Set new selection.
534         selection->addList(new_select);
535         g_slist_free(new_select);
536     }
537     if (!ungrouped) {
538         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
539     }
541     g_slist_free(items);
543     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
544                      _("Ungroup"));
547 static SPGroup *
548 sp_item_list_common_parent_group(GSList const *items)
550     if (!items) {
551         return NULL;
552     }
553     SPObject *parent = SP_OBJECT_PARENT(items->data);
554     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
555     if (!SP_IS_GROUP(parent)) {
556         return NULL;
557     }
558     for (items = items->next; items; items = items->next) {
559         if (SP_OBJECT_PARENT(items->data) != parent) {
560             return NULL;
561         }
562     }
564     return SP_GROUP(parent);
567 /** Finds out the minimum common bbox of the selected items. */
568 static NR::Maybe<NR::Rect>
569 enclose_items(GSList const *items)
571     g_assert(items != NULL);
573     NR::Maybe<NR::Rect> r = NR::Nothing();
574     for (GSList const *i = items; i; i = i->next) {
575         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
576     }
577     return r;
580 SPObject *
581 prev_sibling(SPObject *child)
583     SPObject *parent = SP_OBJECT_PARENT(child);
584     if (!SP_IS_GROUP(parent)) {
585         return NULL;
586     }
587     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
588         if (i->next == child)
589             return i;
590     }
591     return NULL;
594 void
595 sp_selection_raise()
597     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
598     if (!desktop)
599         return;
601     Inkscape::Selection *selection = sp_desktop_selection(desktop);
603     GSList const *items = (GSList *) selection->itemList();
604     if (!items) {
605         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
606         return;
607     }
609     SPGroup const *group = sp_item_list_common_parent_group(items);
610     if (!group) {
611         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
612         return;
613     }
615     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
617     /* Construct reverse-ordered list of selected children. */
618     GSList *rev = g_slist_copy((GSList *) items);
619     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
621     // Determine the common bbox of the selected items.
622     NR::Maybe<NR::Rect> selected = enclose_items(items);
624     // Iterate over all objects in the selection (starting from top).
625     if (selected) {
626         while (rev) {
627             SPObject *child = SP_OBJECT(rev->data);
628             // for each selected object, find the next sibling
629             for (SPObject *newref = child->next; newref; newref = newref->next) {
630                 // if the sibling is an item AND overlaps our selection,
631                 if (SP_IS_ITEM(newref)) {
632                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
633                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
634                         // AND if it's not one of our selected objects,
635                         if (!g_slist_find((GSList *) items, newref)) {
636                             // move the selected object after that sibling
637                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
638                         }
639                         break;
640                     }
641                 }
642             }
643             rev = g_slist_remove(rev, child);
644         }
645     } else {
646         g_slist_free(rev);
647     }
649     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
650                      //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
651                      Q_("undo_action|Raise"));
654 void sp_selection_raise_to_top()
656     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
657     if (desktop == NULL)
658         return;
660     SPDocument *document = sp_desktop_document(desktop);
661     Inkscape::Selection *selection = sp_desktop_selection(desktop);
663     if (selection->isEmpty()) {
664         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
665         return;
666     }
668     GSList const *items = (GSList *) selection->itemList();
670     SPGroup const *group = sp_item_list_common_parent_group(items);
671     if (!group) {
672         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
673         return;
674     }
676     GSList *rl = g_slist_copy((GSList *) selection->reprList());
677     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
679     for (GSList *l = rl; l != NULL; l = l->next) {
680         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
681         repr->setPosition(-1);
682     }
684     g_slist_free(rl);
686     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
687                      _("Raise to top"));
690 void
691 sp_selection_lower()
693     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
694     if (desktop == NULL)
695         return;
697     Inkscape::Selection *selection = sp_desktop_selection(desktop);
699     GSList const *items = (GSList *) selection->itemList();
700     if (!items) {
701         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
702         return;
703     }
705     SPGroup const *group = sp_item_list_common_parent_group(items);
706     if (!group) {
707         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
708         return;
709     }
711     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
713     // Determine the common bbox of the selected items.
714     NR::Maybe<NR::Rect> selected = enclose_items(items);
716     /* Construct direct-ordered list of selected children. */
717     GSList *rev = g_slist_copy((GSList *) items);
718     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
719     rev = g_slist_reverse(rev);
721     // Iterate over all objects in the selection (starting from top).
722     if (selected) {
723         while (rev) {
724             SPObject *child = SP_OBJECT(rev->data);
725             // for each selected object, find the prev sibling
726             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
727                 // if the sibling is an item AND overlaps our selection,
728                 if (SP_IS_ITEM(newref)) {
729                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
730                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
731                         // AND if it's not one of our selected objects,
732                         if (!g_slist_find((GSList *) items, newref)) {
733                             // move the selected object before that sibling
734                             SPObject *put_after = prev_sibling(newref);
735                             if (put_after)
736                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
737                             else
738                                 SP_OBJECT_REPR(child)->setPosition(0);
739                         }
740                         break;
741                     }
742                 }
743             }
744             rev = g_slist_remove(rev, child);
745         }
746     } else {
747         g_slist_free(rev);
748     }
750     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
751                      _("Lower"));
754 void sp_selection_lower_to_bottom()
756     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
757     if (desktop == NULL)
758         return;
760     SPDocument *document = sp_desktop_document(desktop);
761     Inkscape::Selection *selection = sp_desktop_selection(desktop);
763     if (selection->isEmpty()) {
764         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
765         return;
766     }
768     GSList const *items = (GSList *) selection->itemList();
770     SPGroup const *group = sp_item_list_common_parent_group(items);
771     if (!group) {
772         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
773         return;
774     }
776     GSList *rl;
777     rl = g_slist_copy((GSList *) selection->reprList());
778     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
779     rl = g_slist_reverse(rl);
781     for (GSList *l = rl; l != NULL; l = l->next) {
782         gint minpos;
783         SPObject *pp, *pc;
784         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
785         pp = document->getObjectByRepr(sp_repr_parent(repr));
786         minpos = 0;
787         g_assert(SP_IS_GROUP(pp));
788         pc = sp_object_first_child(pp);
789         while (!SP_IS_ITEM(pc)) {
790             minpos += 1;
791             pc = pc->next;
792         }
793         repr->setPosition(minpos);
794     }
796     g_slist_free(rl);
798     sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
799                      _("Lower to bottom"));
802 void
803 sp_undo(SPDesktop *desktop, SPDocument *)
805         if (!sp_document_undo(sp_desktop_document(desktop)))
806             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
809 void
810 sp_redo(SPDesktop *desktop, SPDocument *)
812         if (!sp_document_redo(sp_desktop_document(desktop)))
813             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
816 void sp_selection_cut()
818     sp_selection_copy();
819     sp_selection_delete();
822 /**
823  * \pre item != NULL
824  */
825 SPCSSAttr *
826 take_style_from_item (SPItem *item)
828     // write the complete cascaded style, context-free
829     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
830     if (css == NULL)
831         return NULL;
833     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
834         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
835         // if this is a text with exactly one tspan child, merge the style of that tspan as well
836         // If this is a group, merge the style of its topmost (last) child with style
837         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
838             if (SP_OBJECT_STYLE (last_element) != NULL) {
839                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
840                 if (temp) {
841                     sp_repr_css_merge (css, temp);
842                     sp_repr_css_attr_unref (temp);
843                 }
844                 break;
845             }
846         }
847     }
848     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
849         // do not copy text properties from non-text objects, it's confusing
850         css = sp_css_attr_unset_text (css);
851     }
853     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
854     double ex = NR::expansion(sp_item_i2doc_affine(item));
855     if (ex != 1.0) {
856         css = sp_css_attr_scale (css, ex);
857     }
859     return css;
863 void sp_selection_copy()
865     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
866     cm->copy();
869 void sp_selection_paste(bool in_place)
871     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
872     if(cm->paste(in_place))
873         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE, _("Paste"));
876 void sp_selection_paste_style()
878     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
879     if(cm->pasteStyle())
880         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
884 void sp_selection_paste_livepatheffect()
886     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
887     if(cm->pastePathEffect())
888         sp_document_done(SP_ACTIVE_DOCUMENT, SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
889                      _("Paste live path effect"));
893 void sp_selection_remove_livepatheffect_impl(SPItem *item)
895     if ( item && SP_IS_LPE_ITEM(item) ) {
896         sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
897     }
900 void sp_selection_remove_livepatheffect()
902     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
903     if (desktop == NULL) return;
905     Inkscape::Selection *selection = sp_desktop_selection(desktop);
907     // check if something is selected
908     if (selection->isEmpty()) {
909         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
910         return;
911     }
913     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
914         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
916         sp_selection_remove_livepatheffect_impl(item);
918     }
920     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
921                      _("Remove live path effect"));
924 void sp_selection_paste_size (bool apply_x, bool apply_y)
926     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
927     if(cm->pasteSize(false, apply_x, apply_y))
928         sp_document_done(sp_desktop_document(SP_ACTIVE_DESKTOP), SP_VERB_EDIT_PASTE_SIZE,
929                      _("Paste size"));
932 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
934     Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
935     if(cm->pasteSize(true, apply_x, apply_y))
936         sp_document_done(sp_desktop_document(SP_ACTIVE_DESKTOP), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
937                      _("Paste size separately"));
940 void sp_selection_to_next_layer ()
942     SPDesktop *dt = SP_ACTIVE_DESKTOP;
944     Inkscape::Selection *selection = sp_desktop_selection(dt);
946     // check if something is selected
947     if (selection->isEmpty()) {
948         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
949         return;
950     }
952     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
954     bool no_more = false; // Set to true, if no more layers above
955     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
956     if (next) {
957         GSList *temp_clip = NULL;
958         sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
959         sp_selection_delete_impl (items, false, false);
960         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
961         GSList *copied;
962         if(next) {
963             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
964         } else {
965             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
966             no_more = true;
967         }
968         selection->setReprList((GSList const *) copied);
969         g_slist_free (copied);
970         if (temp_clip) g_slist_free (temp_clip);
971         if (next) dt->setCurrentLayer(next);
972         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
973                          _("Raise to next layer"));
974     } else {
975         no_more = true;
976     }
978     if (no_more) {
979         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
980     }
982     g_slist_free ((GSList *) items);
985 void sp_selection_to_prev_layer ()
987     SPDesktop *dt = SP_ACTIVE_DESKTOP;
989     Inkscape::Selection *selection = sp_desktop_selection(dt);
991     // check if something is selected
992     if (selection->isEmpty()) {
993         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
994         return;
995     }
997     GSList const *items = g_slist_copy ((GSList *) selection->itemList());
999     bool no_more = false; // Set to true, if no more layers below
1000     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1001     if (next) {
1002         GSList *temp_clip = NULL;
1003         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
1004         sp_selection_delete_impl (items, false, false);
1005         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1006         GSList *copied;
1007         if(next) {
1008             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1009         } else {
1010             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1011             no_more = true;
1012         }
1013         selection->setReprList((GSList const *) copied);
1014         g_slist_free (copied);
1015         if (temp_clip) g_slist_free (temp_clip);
1016         if (next) dt->setCurrentLayer(next);
1017         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1018                          _("Lower to previous layer"));
1019     } else {
1020         no_more = true;
1021     }
1023     if (no_more) {
1024         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1025     }
1027     g_slist_free ((GSList *) items);
1030 bool
1031 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1033     bool contains_original = false;
1035     bool is_use = SP_IS_USE(item);
1036     SPItem *item_use = item;
1037     SPItem *item_use_first = item;
1038     while (is_use && item_use && !contains_original)
1039     {
1040         item_use = sp_use_get_original (SP_USE(item_use));
1041         contains_original |= selection->includes(item_use);
1042         if (item_use == item_use_first)
1043             break;
1044         is_use = SP_IS_USE(item_use);
1045     }
1047     // If it's a tref, check whether the object containing the character
1048     // data is part of the selection
1049     if (!contains_original && SP_IS_TREF(item)) {
1050         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1051     }
1053     return contains_original;
1057 bool
1058 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1060     bool clone_with_original = false;
1061     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1062         SPItem *item = SP_ITEM(l->data);
1063         clone_with_original |= selection_contains_original(item, selection);
1064         if (clone_with_original)
1065             break;
1066     }
1067     return clone_with_original;
1071 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1072 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1073 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1074 that case, items are already in the new position, but the repr is in the old, and this function
1075 then simply updates the repr from item->transform.
1076  */
1077 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1079     if (selection->isEmpty())
1080         return;
1082     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1083         SPItem *item = SP_ITEM(l->data);
1085         NR::Point old_center(0,0);
1086         if (set_i2d && item->isCenterSet())
1087             old_center = item->getCenter();
1089 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1090          At the time of writing, this is the only place to re-enable. */
1091         sp_item_update_cns(*item, selection->desktop());
1092 #endif
1094         // we're moving both a clone and its original or any ancestor in clone chain?
1095         bool transform_clone_with_original = selection_contains_original(item, selection);
1096         // ...both a text-on-path and its path?
1097         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)))) ));
1098         // ...both a flowtext and its frame?
1099         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)
1100         // ...both an offset and its source?
1101         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1103         // If we're moving a connector, we want to detach it
1104         // from shapes that aren't part of the selection, but
1105         // leave it attached if they are
1106         if (cc_item_is_connector(item)) {
1107             SPItem *attItem[2];
1108             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1110             for (int n = 0; n < 2; ++n) {
1111                 if (!selection->includes(attItem[n])) {
1112                     sp_conn_end_detach(item, n);
1113                 }
1114             }
1115         }
1117         // "clones are unmoved when original is moved" preference
1118         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1119         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1120         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1122         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1123         // transform of its original and respond to it itself. Without this, a clone is doubly
1124         // transformed, very unintuitive.
1125       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1126       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1127       // Same for linked offset if we are also moving its source: do not move it.
1128         if (transform_textpath_with_path || transform_offset_with_source) {
1129                 // restore item->transform field from the repr, in case it was changed by seltrans
1130             sp_object_read_attr (SP_OBJECT (item), "transform");
1132         } else if (transform_flowtext_with_frame) {
1133             // apply the inverse of the region's transform to the <use> so that the flow remains
1134             // the same (even though the output itself gets transformed)
1135             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1136                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1137                     continue;
1138                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1139                     if (!SP_IS_USE(use)) continue;
1140                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1141                 }
1142             }
1143         } else if (transform_clone_with_original) {
1144             // We are transforming a clone along with its original. The below matrix juggling is
1145             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1146             // transform and its move compensation are both cancelled out.
1148             // restore item->transform field from the repr, in case it was changed by seltrans
1149             sp_object_read_attr (SP_OBJECT (item), "transform");
1151             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1152             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1153             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1154             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1155             NR::Matrix result = t_inv * item->transform * t;
1157             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1158                 // we need to cancel out the move compensation, too
1160                 // find out the clone move, same as in sp_use_move_compensate
1161                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1162                 NR::Matrix clone_move = parent.inverse() * t * parent;
1164                 if (prefs_parallel) {
1165                     NR::Matrix move = result * clone_move * t_inv;
1166                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1168                 } else if (prefs_unmoved) {
1169                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1170                     //    clone_move = NR::identity();
1171                     NR::Matrix move = result * clone_move;
1172                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1173                 }
1175             } else {
1176                 // just apply the result
1177                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1178             }
1180         } else {
1181             if (set_i2d) {
1182                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1183             }
1184             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1185         }
1187         // if we're moving the actual object, not just updating the repr, we can transform the
1188         // center by the same matrix (only necessary for non-translations)
1189         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1190             item->setCenter(old_center * affine);
1191             SP_OBJECT(item)->updateRepr();
1192         }
1193     }
1196 void sp_selection_remove_transform()
1198     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1199     if (desktop == NULL)
1200         return;
1202     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1204     GSList const *l = (GSList *) selection->reprList();
1205     while (l != NULL) {
1206         ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1207         l = l->next;
1208     }
1210     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1211                      _("Remove transform"));
1214 void
1215 sp_selection_scale_absolute(Inkscape::Selection *selection,
1216                             double const x0, double const x1,
1217                             double const y0, double const y1)
1219     if (selection->isEmpty())
1220         return;
1222     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1223     if ( !bbox || bbox->isEmpty() ) {
1224         return;
1225     }
1227     NR::translate const p2o(-bbox->min());
1229     NR::scale const newSize(x1 - x0,
1230                             y1 - y0);
1231     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1232     NR::translate const o2n(x0, y0);
1233     NR::Matrix const final( p2o * scale * o2n );
1235     sp_selection_apply_affine(selection, final);
1239 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1241     if (selection->isEmpty())
1242         return;
1244     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1246     if ( !bbox || bbox->isEmpty() ) {
1247         return;
1248     }
1250     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1251     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1252          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1253     {
1254         return;
1255     }
1257     NR::translate const n2d(-align);
1258     NR::translate const d2n(align);
1259     NR::Matrix const final( n2d * scale * d2n );
1260     sp_selection_apply_affine(selection, final);
1263 void
1264 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1266     NR::translate const d2n(center);
1267     NR::translate const n2d(-center);
1268     NR::rotate const rotate(rotate_degrees(angle_degrees));
1269     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1270     sp_selection_apply_affine(selection, final);
1273 void
1274 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1276     NR::translate const d2n(align);
1277     NR::translate const n2d(-align);
1278     NR::Matrix const skew(1, dy,
1279                           dx, 1,
1280                           0, 0);
1281     NR::Matrix const final( n2d * skew * d2n );
1282     sp_selection_apply_affine(selection, final);
1285 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1287     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1290 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1292     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1296 /**
1297  * \brief sp_selection_rotate_90
1298  *
1299  * This function rotates selected objects 90 degrees clockwise.
1300  *
1301  */
1303 void sp_selection_rotate_90_cw()
1305     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1307     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1309     if (selection->isEmpty())
1310         return;
1312     GSList const *l = selection->itemList();
1313     NR::rotate const rot_neg_90(NR::Point(0, -1));
1314     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1315         SPItem *item = SP_ITEM(l2->data);
1316         sp_item_rotate_rel(item, rot_neg_90);
1317     }
1319     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1320                      _("Rotate 90&#176; CW"));
1324 /**
1325  * @brief Rotates selected objects 90 degrees counter-clockwise.
1326  */
1327 void sp_selection_rotate_90_ccw()
1329     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1331     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1333     if (selection->isEmpty())
1334         return;
1336     GSList const *l = selection->itemList();
1337     NR::rotate const rot_neg_90(NR::Point(0, 1));
1338     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1339         SPItem *item = SP_ITEM(l2->data);
1340         sp_item_rotate_rel(item, rot_neg_90);
1341     }
1343     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1344                      _("Rotate 90&#176; CCW"));
1347 void
1348 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1350     if (selection->isEmpty())
1351         return;
1353     NR::Maybe<NR::Point> center = selection->center();
1354     if (!center) {
1355         return;
1356     }
1358     sp_selection_rotate_relative(selection, *center, angle_degrees);
1360     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1361                            ( ( angle_degrees > 0 )
1362                              ? "selector:rotate:ccw"
1363                              : "selector:rotate:cw" ),
1364                            SP_VERB_CONTEXT_SELECT,
1365                            _("Rotate"));
1368 /**
1369 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1370 */
1371 void
1372 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1374     if (selection->isEmpty())
1375         return;
1377     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1378     NR::Maybe<NR::Point> center = selection->center();
1380     if ( !bbox || !center ) {
1381         return;
1382     }
1384     gdouble const zoom = selection->desktop()->current_zoom();
1385     gdouble const zmove = angle / zoom;
1386     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1388     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1390     sp_selection_rotate_relative(selection, *center, zangle);
1392     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1393                            ( (angle > 0)
1394                              ? "selector:rotate:ccw"
1395                              : "selector:rotate:cw" ),
1396                            SP_VERB_CONTEXT_SELECT,
1397                            _("Rotate by pixels"));
1400 void
1401 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1403     if (selection->isEmpty())
1404         return;
1406     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1407     if (!bbox) {
1408         return;
1409     }
1411     NR::Point const center(bbox->midpoint());
1413     // you can't scale "do nizhe pola" (below zero)
1414     double const max_len = bbox->maxExtent();
1415     if ( max_len + grow <= 1e-3 ) {
1416         return;
1417     }
1419     double const times = 1.0 + grow / max_len;
1420     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1422     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1423                            ( (grow > 0)
1424                              ? "selector:scale:larger"
1425                              : "selector:scale:smaller" ),
1426                            SP_VERB_CONTEXT_SELECT,
1427                            _("Scale"));
1430 void
1431 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1433     sp_selection_scale(selection,
1434                        grow_pixels / selection->desktop()->current_zoom());
1437 void
1438 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1440     if (selection->isEmpty())
1441         return;
1443     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1445     if (!sel_bbox) {
1446         return;
1447     }
1449     NR::Point const center(sel_bbox->midpoint());
1450     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1451     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1452                      _("Scale by whole factor"));
1455 void
1456 sp_selection_move(gdouble dx, gdouble dy)
1458     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1459     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1460     if (selection->isEmpty()) {
1461         return;
1462     }
1464     sp_selection_move_relative(selection, dx, dy);
1466     if (dx == 0) {
1467         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1468                                _("Move vertically"));
1469     } else if (dy == 0) {
1470         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1471                                _("Move horizontally"));
1472     } else {
1473         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1474                          _("Move"));
1475     }
1478 void
1479 sp_selection_move_screen(gdouble dx, gdouble dy)
1481     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1483     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1484     if (selection->isEmpty()) {
1485         return;
1486     }
1488     // same as sp_selection_move but divide deltas by zoom factor
1489     gdouble const zoom = desktop->current_zoom();
1490     gdouble const zdx = dx / zoom;
1491     gdouble const zdy = dy / zoom;
1492     sp_selection_move_relative(selection, zdx, zdy);
1494     if (dx == 0) {
1495         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1496                                _("Move vertically by pixels"));
1497     } else if (dy == 0) {
1498         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1499                                _("Move horizontally by pixels"));
1500     } else {
1501         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1502                          _("Move"));
1503     }
1506 namespace {
1508 template <typename D>
1509 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1510                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1512 template <typename D>
1513 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1514                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1516 struct Forward {
1517     typedef SPObject *Iterator;
1519     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1520     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1521     static void dispose(Iterator /*i*/) {}
1523     static SPObject *object(Iterator i) { return i; }
1524     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1525 };
1527 struct Reverse {
1528     typedef GSList *Iterator;
1530     static Iterator children(SPObject *o) {
1531         return make_list(o->firstChild(), NULL);
1532     }
1533     static Iterator siblings_after(SPObject *o) {
1534         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1535     }
1536     static void dispose(Iterator i) {
1537         g_slist_free(i);
1538     }
1540     static SPObject *object(Iterator i) {
1541         return reinterpret_cast<SPObject *>(i->data);
1542     }
1543     static Iterator next(Iterator i) { return i->next; }
1545 private:
1546     static GSList *make_list(SPObject *object, SPObject *limit) {
1547         GSList *list=NULL;
1548         while ( object != limit ) {
1549             list = g_slist_prepend(list, object);
1550             object = SP_OBJECT_NEXT(object);
1551         }
1552         return list;
1553     }
1554 };
1558 void
1559 sp_selection_item_next(void)
1561     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1562     g_return_if_fail(desktop != NULL);
1563     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1565     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1566     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1567     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1569     SPObject *root;
1570     if (PREFS_SELECTION_ALL != inlayer) {
1571         root = selection->activeContext();
1572     } else {
1573         root = desktop->currentRoot();
1574     }
1576     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1578     if (item) {
1579         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1580         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1581             scroll_to_show_item(desktop, item);
1582         }
1583     }
1586 void
1587 sp_selection_item_prev(void)
1589     SPDocument *document = SP_ACTIVE_DOCUMENT;
1590     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1591     g_return_if_fail(document != NULL);
1592     g_return_if_fail(desktop != NULL);
1593     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1595     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1596     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1597     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1599     SPObject *root;
1600     if (PREFS_SELECTION_ALL != inlayer) {
1601         root = selection->activeContext();
1602     } else {
1603         root = desktop->currentRoot();
1604     }
1606     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1608     if (item) {
1609         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1610         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1611             scroll_to_show_item(desktop, item);
1612         }
1613     }
1616 void sp_selection_next_patheffect_param(SPDesktop * dt)
1618     if (!dt) return;
1620     Inkscape::Selection *selection = sp_desktop_selection(dt);
1621     if ( selection && !selection->isEmpty() ) {
1622         SPItem *item = selection->singleItem();
1623         if ( item && SP_IS_SHAPE(item)) {
1624             if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1625                 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1626             } else {
1627                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1628             }
1629         }
1630     }
1633 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1635     if (!dt) return;
1637     Inkscape::Selection *selection = sp_desktop_selection(dt);
1638     if ( selection && !selection->isEmpty() ) {
1639         SPItem *item = selection->singleItem();
1640         if ( item ) {
1641             SPObject *obj = NULL;
1642             if (clip)
1643                 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1644             else
1645                 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1647             if (obj) {
1648                 // obj is a group object, the children are the actual clippers
1649                 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1650                     if ( SP_IS_ITEM(child) ) {
1651                         // If not already in nodecontext, goto it!
1652                         if (!tools_isactive(dt, TOOLS_NODES)) {
1653                             tools_switch_current(TOOLS_NODES);
1654                         }
1656                         ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
1657                         shape_editor->set_item(SP_ITEM(child));
1658                         Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1659                         if (np) {
1660                             // take colors from prefs (same as used in outline mode)
1661                             np->helperpath_rgba = clip ? 
1662                                 prefs_get_int_attribute("options.wireframecolors", "clips", 0x00ff00ff) : 
1663                                 prefs_get_int_attribute("options.wireframecolors", "masks", 0x0000ffff);
1664                             np->helperpath_width = 1.0;
1665                             sp_nodepath_show_helperpath(np, true);
1666                         }
1667                         break; // break out of for loop after 1st encountered item
1668                     }
1669                 }
1670             } else if (clip) {
1671                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1672             } else {
1673                 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1674             }
1675         }
1676     }
1680 namespace {
1682 template <typename D>
1683 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1684                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1686     SPObject *current=root;
1687     while (items) {
1688         SPItem *item=SP_ITEM(items->data);
1689         if ( root->isAncestorOf(item) &&
1690              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1691         {
1692             current = item;
1693             break;
1694         }
1695         items = items->next;
1696     }
1698     GSList *path=NULL;
1699     while ( current != root ) {
1700         path = g_slist_prepend(path, current);
1701         current = SP_OBJECT_PARENT(current);
1702     }
1704     SPItem *next;
1705     // first, try from the current object
1706     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1707     g_slist_free(path);
1709     if (!next) { // if we ran out of objects, start over at the root
1710         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1711     }
1713     return next;
1716 template <typename D>
1717 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1718                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1720     typename D::Iterator children;
1721     typename D::Iterator iter;
1723     SPItem *found=NULL;
1725     if (path) {
1726         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1727         g_assert(SP_OBJECT_PARENT(object) == root);
1728         if (desktop->isLayer(object)) {
1729             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1730         }
1731         iter = children = D::siblings_after(object);
1732     } else {
1733         iter = children = D::children(root);
1734     }
1736     while ( iter && !found ) {
1737         SPObject *object=D::object(iter);
1738         if (desktop->isLayer(object)) {
1739             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1740                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1741             }
1742         } else if ( SP_IS_ITEM(object) &&
1743                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1744                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1745                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1746                     !desktop->isLayer(SP_ITEM(object)) )
1747         {
1748             found = SP_ITEM(object);
1749         }
1750         iter = D::next(iter);
1751     }
1753     D::dispose(children);
1755     return found;
1760 /**
1761  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1762  * \a item.
1763  */
1764 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1766     NR::Rect dbox = desktop->get_display_area();
1767     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
1769     if ( sbox && dbox.contains(*sbox) == false ) {
1770         NR::Point const s_dt = sbox->midpoint();
1771         NR::Point const s_w = desktop->d2w(s_dt);
1772         NR::Point const d_dt = dbox.midpoint();
1773         NR::Point const d_w = desktop->d2w(d_dt);
1774         NR::Point const moved_w( d_w - s_w );
1775         gint const dx = (gint) moved_w[X];
1776         gint const dy = (gint) moved_w[Y];
1777         desktop->scroll_world(dx, dy);
1778     }
1782 void
1783 sp_selection_clone()
1785     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1786     if (desktop == NULL)
1787         return;
1789     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1791     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1793     // check if something is selected
1794     if (selection->isEmpty()) {
1795         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1796         return;
1797     }
1799     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1801     selection->clear();
1803     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1804     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1806     GSList *newsel = NULL;
1808     while (reprs) {
1809         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1810         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1812         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1813         clone->setAttribute("x", "0", false);
1814         clone->setAttribute("y", "0", false);
1815         clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1816         
1817         clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1818         clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1820         // add the new clone to the top of the original's parent
1821         parent->appendChild(clone);
1823         newsel = g_slist_prepend(newsel, clone);
1824         reprs = g_slist_remove(reprs, sel_repr);
1825         Inkscape::GC::release(clone);
1826     }
1828     // TRANSLATORS: only translate "string" in "context|string".
1829     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1830     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1831                      Q_("action|Clone"));
1833     selection->setReprList(newsel);
1835     g_slist_free(newsel);
1838 void
1839 sp_selection_unlink()
1841     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1842     if (!desktop)
1843         return;
1845     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1847     if (selection->isEmpty()) {
1848         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
1849         return;
1850     }
1852     // Get a copy of current selection.
1853     GSList *new_select = NULL;
1854     bool unlinked = false;
1855     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1856          items != NULL;
1857          items = items->next)
1858     {
1859         SPItem *item = (SPItem *) items->data;
1861         if (SP_IS_TEXT(item)) {
1862             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1864             if (tspan) {
1865                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1866             }
1868             // Set unlink to true, and fall into the next if which
1869             // will include this text item in the new selection
1870             unlinked = true;
1871         }
1873         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
1874             // keep the non-use item in the new selection
1875             new_select = g_slist_prepend(new_select, item);
1876             continue;
1877         }
1879         SPItem *unlink;
1880         if (SP_IS_USE(item)) {
1881             unlink = sp_use_unlink(SP_USE(item));
1882         } else /*if (SP_IS_TREF(use))*/ {
1883             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
1884         }
1886         unlinked = true;
1887         // Add ungrouped items to the new selection.
1888         new_select = g_slist_prepend(new_select, unlink);
1889     }
1891     if (new_select) { // set new selection
1892         selection->clear();
1893         selection->setList(new_select);
1894         g_slist_free(new_select);
1895     }
1896     if (!unlinked) {
1897         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1898     }
1900     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1901                      _("Unlink clone"));
1904 void
1905 sp_select_clone_original()
1907     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1908     if (desktop == NULL)
1909         return;
1911     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1913     SPItem *item = selection->singleItem();
1915     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.");
1917     // Check if other than two objects are selected
1918     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
1919         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1920         return;
1921     }
1923     SPItem *original = NULL;
1924     if (SP_IS_USE(item)) {
1925         original = sp_use_get_original (SP_USE(item));
1926     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
1927         original = sp_offset_get_source (SP_OFFSET(item));
1928     } else if (SP_IS_TEXT_TEXTPATH(item)) {
1929         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
1930     } else if (SP_IS_FLOWTEXT(item)) {
1931         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
1932     } else { // it's an object that we don't know what to do with
1933         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1934         return;
1935     }
1937     if (!original) {
1938         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
1939         return;
1940     }
1942     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
1943         if (SP_IS_DEFS (o)) {
1944             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
1945             return;
1946         }
1947     }
1949     if (original) {
1950         selection->clear();
1951         selection->set(original);
1952         if (SP_CYCLING == SP_CYCLE_FOCUS) {
1953             scroll_to_show_item(desktop, original);
1954         }
1955     }
1959 void sp_selection_to_marker(bool apply)
1961     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1962     if (desktop == NULL)
1963         return;
1965     SPDocument *doc = sp_desktop_document(desktop);
1966     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
1968     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1970     // check if something is selected
1971     if (selection->isEmpty()) {
1972         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
1973         return;
1974     }
1976     sp_document_ensure_up_to_date(doc);
1977     NR::Maybe<NR::Rect> r = selection->bounds();
1978     NR::Maybe<NR::Point> c = selection->center();
1979     if ( !r || !c || r->isEmpty() ) {
1980         return;
1981     }
1983     // calculate the transform to be applied to objects to move them to 0,0
1984     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - *c;
1985     move_p[NR::Y] = -move_p[NR::Y];
1986     NR::Matrix move = NR::Matrix (NR::translate (move_p));
1988     GSList *items = g_slist_copy((GSList *) selection->itemList());
1990     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
1992     // bottommost object, after sorting
1993     SPObject *parent = SP_OBJECT_PARENT (items->data);
1995     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
1997     // remember the position of the first item
1998     gint pos = SP_OBJECT_REPR (items->data)->position();
1999     (void)pos; // TODO check why this was remembered
2001     // create a list of duplicates
2002     GSList *repr_copies = NULL;
2003     for (GSList *i = items; i != NULL; i = i->next) {
2004         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2005         repr_copies = g_slist_prepend (repr_copies, dup);
2006     }
2008     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2010     if (apply) {
2011         // delete objects so that their clones don't get alerted; this object will be restored shortly
2012         for (GSList *i = items; i != NULL; i = i->next) {
2013             SPObject *item = SP_OBJECT (i->data);
2014             item->deleteObject (false);
2015         }
2016     }
2018     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2019     // without disturbing clones.
2020     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2021     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2022     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2024     gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2025                                            ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2026                                                                                                 r->max()[NR::Y]))))
2027                                              * parent_transform.inverse() ),
2028                                            parent_transform * move);
2029     (void)mark_id;
2031     // restore compensation setting
2032     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2035     g_slist_free (items);
2037     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2038                       _("Objects to marker"));
2041 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2042     if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2043         for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2044             sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2045         }
2046     } else {
2047         sp_item_convert_item_to_guides(item);
2049         if (deleteitem) {
2050             SP_OBJECT(item)->deleteObject(true);
2051         }
2052     }
2055 void sp_selection_to_guides()
2057     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2058     if (desktop == NULL)
2059         return;
2061     SPDocument *doc = sp_desktop_document(desktop);
2062     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2063     // we need to copy the list because it gets reset when objects are deleted
2064     GSList *items = g_slist_copy((GSList *) selection->itemList());
2066     if (!items) {
2067         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2068         return;
2069     }
2070  
2071     bool deleteitem = (prefs_get_int_attribute("tools", "cvg_keep_objects", 0) == 0);
2072     bool wholegroups = (prefs_get_int_attribute("tools", "cvg_convert_whole_groups", 0) != 0);
2074     for (GSList const *i = items; i != NULL; i = i->next) {
2075         sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2076     }
2078     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2081 void
2082 sp_selection_tile(bool apply)
2084     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2085     if (desktop == NULL)
2086         return;
2088     SPDocument *doc = sp_desktop_document(desktop);
2089     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2091     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2093     // check if something is selected
2094     if (selection->isEmpty()) {
2095         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2096         return;
2097     }
2099     sp_document_ensure_up_to_date(doc);
2100     NR::Maybe<NR::Rect> r = selection->bounds();
2101     if ( !r || r->isEmpty() ) {
2102         return;
2103     }
2105     // calculate the transform to be applied to objects to move them to 0,0
2106     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2107     move_p[NR::Y] = -move_p[NR::Y];
2108     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2110     GSList *items = g_slist_copy((GSList *) selection->itemList());
2112     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2114     // bottommost object, after sorting
2115     SPObject *parent = SP_OBJECT_PARENT (items->data);
2117     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2119     // remember the position of the first item
2120     gint pos = SP_OBJECT_REPR (items->data)->position();
2122     // create a list of duplicates
2123     GSList *repr_copies = NULL;
2124     for (GSList *i = items; i != NULL; i = i->next) {
2125         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2126         repr_copies = g_slist_prepend (repr_copies, dup);
2127     }
2128     // restore the z-order after prepends
2129     repr_copies = g_slist_reverse (repr_copies);
2131     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2133     if (apply) {
2134         // delete objects so that their clones don't get alerted; this object will be restored shortly
2135         for (GSList *i = items; i != NULL; i = i->next) {
2136             SPObject *item = SP_OBJECT (i->data);
2137             item->deleteObject (false);
2138         }
2139     }
2141     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2142     // without disturbing clones.
2143     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2144     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2145     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2147     gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2148                                        ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2149                                                                                             r->max()[NR::Y]))))
2150                                          * parent_transform.inverse() ),
2151                                        parent_transform * move);
2153     // restore compensation setting
2154     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2156     if (apply) {
2157         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2158         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2160         NR::Point min = bounds.min() * parent_transform.inverse();
2161         NR::Point max = bounds.max() * parent_transform.inverse();
2163         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2164         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2165         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2166         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2168         // restore parent and position
2169         SP_OBJECT_REPR (parent)->appendChild(rect);
2170         rect->setPosition(pos > 0 ? pos : 0);
2171         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2173         Inkscape::GC::release(rect);
2175         selection->clear();
2176         selection->set(rectangle);
2177     }
2179     g_slist_free (items);
2181     sp_document_done (doc, SP_VERB_EDIT_TILE,
2182                       _("Objects to pattern"));
2185 void
2186 sp_selection_untile()
2188     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2189     if (desktop == NULL)
2190         return;
2192     SPDocument *doc = sp_desktop_document(desktop);
2193     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2195     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2197     // check if something is selected
2198     if (selection->isEmpty()) {
2199         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2200         return;
2201     }
2203     GSList *new_select = NULL;
2205     bool did = false;
2207     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2208          items != NULL;
2209          items = items->next) {
2211         SPItem *item = (SPItem *) items->data;
2213         SPStyle *style = SP_OBJECT_STYLE (item);
2215         if (!style || !style->fill.isPaintserver())
2216             continue;
2218         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2220         if (!SP_IS_PATTERN(server))
2221             continue;
2223         did = true;
2225         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2227         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2228         pat_transform *= item->transform;
2230         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2231             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2232             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2234            // FIXME: relink clones to the new canvas objects
2235            // use SPObject::setid when mental finishes it to steal ids of
2237             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2238             sp_document_ensure_up_to_date (doc);
2240             NR::Matrix transform( i->transform * pat_transform );
2241             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2243             new_select = g_slist_prepend(new_select, i);
2244         }
2246         SPCSSAttr *css = sp_repr_css_attr_new ();
2247         sp_repr_css_set_property (css, "fill", "none");
2248         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2249     }
2251     if (!did) {
2252         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2253     } else {
2254         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2255                          _("Pattern to objects"));
2256         selection->setList(new_select);
2257     }
2260 void
2261 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2263     if (selection->isEmpty()) {
2264         return;
2265     }
2267     GSList const *reprlst = selection->reprList();
2268     bool filename_search = TRUE;
2269     bool xdpi_search = TRUE;
2270     bool ydpi_search = TRUE;
2272     for(; reprlst != NULL &&
2273             filename_search &&
2274             xdpi_search &&
2275             ydpi_search;
2276         reprlst = reprlst->next) {
2277         gchar const *dpi_string;
2278         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2280         if (filename_search) {
2281             *filename = repr->attribute("inkscape:export-filename");
2282             if (*filename != NULL)
2283                 filename_search = FALSE;
2284         }
2286         if (xdpi_search) {
2287             dpi_string = NULL;
2288             dpi_string = repr->attribute("inkscape:export-xdpi");
2289             if (dpi_string != NULL) {
2290                 *xdpi = atof(dpi_string);
2291                 xdpi_search = FALSE;
2292             }
2293         }
2295         if (ydpi_search) {
2296             dpi_string = NULL;
2297             dpi_string = repr->attribute("inkscape:export-ydpi");
2298             if (dpi_string != NULL) {
2299                 *ydpi = atof(dpi_string);
2300                 ydpi_search = FALSE;
2301             }
2302         }
2303     }
2306 void
2307 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2309     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2310     gchar const *dpi_string;
2312     *filename = repr->attribute("inkscape:export-filename");
2314     dpi_string = NULL;
2315     dpi_string = repr->attribute("inkscape:export-xdpi");
2316     if (dpi_string != NULL) {
2317         *xdpi = atof(dpi_string);
2318     }
2320     dpi_string = NULL;
2321     dpi_string = repr->attribute("inkscape:export-ydpi");
2322     if (dpi_string != NULL) {
2323         *ydpi = atof(dpi_string);
2324     }
2327 void
2328 sp_selection_create_bitmap_copy ()
2330     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2331     if (desktop == NULL)
2332         return;
2334     SPDocument *document = sp_desktop_document(desktop);
2335     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2337     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2339     // check if something is selected
2340     if (selection->isEmpty()) {
2341         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2342         return;
2343     }
2345     // Get the bounding box of the selection
2346     NRRect bbox;
2347     sp_document_ensure_up_to_date (document);
2348     selection->bounds(&bbox);
2349     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2350         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2351     }
2353     // List of the items to show; all others will be hidden
2354     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2356     // Sort items so that the topmost comes last
2357     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2359     // Generate a random value from the current time (you may create bitmap from the same object(s)
2360     // multiple times, and this is done so that they don't clash)
2361     GTimeVal cu;
2362     g_get_current_time (&cu);
2363     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2365     // Create the filename
2366     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2367     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2368     // digits, and a few other chars, with "_"
2369     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2370     // Build the complete path by adding document->base if set
2371     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2373     //g_print ("%s\n", filepath);
2375     // Remember parent and z-order of the topmost one
2376     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2377     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2378     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2380     // Calculate resolution
2381     double res;
2382     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2383     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2384     if (0 < prefs_res) {
2385         // If it's given explicitly in prefs, take it
2386         res = prefs_res;
2387     } else if (0 < prefs_min) {
2388         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2389         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2390     } else {
2391         float hint_xdpi = 0, hint_ydpi = 0;
2392         char const *hint_filename;
2393         // take resolution hint from the selected objects
2394         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2395         if (hint_xdpi != 0) {
2396             res = hint_xdpi;
2397         } else {
2398             // take resolution hint from the document
2399             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2400             if (hint_xdpi != 0) {
2401                 res = hint_xdpi;
2402             } else {
2403                 // if all else fails, take the default 90 dpi
2404                 res = PX_PER_IN;
2405             }
2406         }
2407     }
2409     // The width and height of the bitmap in pixels
2410     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2411     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2413     // Find out if we have to run a filter
2414     gchar const *run = NULL;
2415     gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2416     if (filter) {
2417         // filter command is given;
2418         // see if we have a parameter to pass to it
2419         gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2420         if (param1) {
2421             if (param1[strlen(param1) - 1] == '%') {
2422                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2423                 gchar p1[256];
2424                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2425                 // the first param is always the image filename, the second is param1
2426                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2427             } else {
2428                 // otherwise pass the param1 unchanged
2429                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2430             }
2431         } else {
2432             // run without extra parameter
2433             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2434         }
2435     }
2437     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2438     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2439     NR::Matrix t;
2441     double shift_x = bbox.x0;
2442     double shift_y = bbox.y1;
2443     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2444         shift_x = round (shift_x);
2445         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2446     }
2447     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2449     // Do the export
2450     sp_export_png_file(document, filepath,
2451                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2452                    width, height, res, res,
2453                    (guint32) 0xffffff00,
2454                    NULL, NULL,
2455                    true,  /*bool force_overwrite,*/
2456                    items);
2458     g_slist_free (items);
2460     // Run filter, if any
2461     if (run) {
2462         g_print ("Running external filter: %s\n", run);
2463         system (run);
2464     }
2466     // Import the image back
2467     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2468     if (pb) {
2469         // Create the repr for the image
2470         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2471         repr->setAttribute("xlink:href", filename);
2472         repr->setAttribute("sodipodi:absref", filepath);
2473         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2474             sp_repr_set_svg_double(repr, "width", width);
2475             sp_repr_set_svg_double(repr, "height", height);
2476         } else {
2477             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2478             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2479         }
2481         // Write transform
2482         gchar *c=sp_svg_transform_write(t);
2483         repr->setAttribute("transform", c);
2484         g_free(c);
2486         // add the new repr to the parent
2487         parent->appendChild(repr);
2489         // move to the saved position
2490         repr->setPosition(pos > 0 ? pos + 1 : 1);
2492         // Set selection to the new image
2493         selection->clear();
2494         selection->add(repr);
2496         // Clean up
2497         Inkscape::GC::release(repr);
2498         gdk_pixbuf_unref (pb);
2500         // Complete undoable transaction
2501         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2502                           _("Create bitmap"));
2503     }
2505     g_free (filename);
2506     g_free (filepath);
2509 /**
2510  * \brief Creates a mask or clipPath from selection
2511  * Two different modes:
2512  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2513  *       and is applied to current layer
2514  *  otherwise, topmost object is used as mask for other objects
2515  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2516  *
2517  */
2518 void
2519 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2521     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2522     if (desktop == NULL)
2523         return;
2525     SPDocument *doc = sp_desktop_document(desktop);
2526     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2528     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2530     // check if something is selected
2531     bool is_empty = selection->isEmpty();
2532     if ( apply_to_layer && is_empty) {
2533         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2534         return;
2535     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2536         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2537         return;
2538     }
2540     // FIXME: temporary patch to prevent crash!
2541     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2542     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2543     if (clone_with_original) {
2544         return; // in this version, you cannot clip/mask an object with its own clone
2545     }
2546     // /END FIXME
2548     sp_document_ensure_up_to_date(doc);
2550     GSList *items = g_slist_copy((GSList *) selection->itemList());
2552     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2554     // create a list of duplicates
2555     GSList *mask_items = NULL;
2556     GSList *apply_to_items = NULL;
2557     GSList *items_to_delete = NULL;
2558     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2559     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2561     if (apply_to_layer) {
2562         // all selected items are used for mask, which is applied to a layer
2563         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2565         for (GSList *i = items; i != NULL; i = i->next) {
2566             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2567             mask_items = g_slist_prepend (mask_items, dup);
2569             if (remove_original) {
2570                 SPObject *item = SP_OBJECT (i->data);
2571                 items_to_delete = g_slist_prepend (items_to_delete, item);
2572             }
2573         }
2574     } else if (!topmost) {
2575         // topmost item is used as a mask, which is applied to other items in a selection
2576         GSList *i = items;
2577         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2578         mask_items = g_slist_prepend (mask_items, dup);
2580         if (remove_original) {
2581             SPObject *item = SP_OBJECT (i->data);
2582             items_to_delete = g_slist_prepend (items_to_delete, item);
2583         }
2585         for (i = i->next; i != NULL; i = i->next) {
2586             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2587         }
2588     } else {
2589         GSList *i = NULL;
2590         for (i = items; NULL != i->next; i = i->next) {
2591             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2592         }
2594         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2595         mask_items = g_slist_prepend (mask_items, dup);
2597         if (remove_original) {
2598             SPObject *item = SP_OBJECT (i->data);
2599             items_to_delete = g_slist_prepend (items_to_delete, item);
2600         }
2601     }
2603     g_slist_free (items);
2604     items = NULL;
2606     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2607     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2608         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2609         // inverted object transform should be applied to a mask object,
2610         // as mask is calculated in user space (after applying transform)
2611         NR::Matrix maskTransform (item->transform.inverse());
2613         GSList *mask_items_dup = NULL;
2614         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2615             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2616             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2617         }
2619         gchar const *mask_id = NULL;
2620         if (apply_clip_path) {
2621             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2622         } else {
2623             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2624         }
2626         g_slist_free (mask_items_dup);
2627         mask_items_dup = NULL;
2629         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2630     }
2632     g_slist_free (mask_items);
2633     g_slist_free (apply_to_items);
2635     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2636         SPObject *item = SP_OBJECT (i->data);
2637         item->deleteObject (false);
2638     }
2639     g_slist_free (items_to_delete);
2641     if (apply_clip_path)
2642         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2643     else
2644         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2647 void sp_selection_unset_mask(bool apply_clip_path) {
2648     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2649     if (desktop == NULL)
2650         return;
2652     SPDocument *doc = sp_desktop_document(desktop);
2653     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2654     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2656     // check if something is selected
2657     if (selection->isEmpty()) {
2658         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2659         return;
2660     }
2662     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2663     sp_document_ensure_up_to_date(doc);
2665     gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2666     std::map<SPObject*,SPItem*> referenced_objects;
2667     for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2668         if (remove_original) {
2669             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2670             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2671             Inkscape::URIReference *uri_ref = NULL;
2673             if (apply_clip_path) {
2674                 uri_ref = item->clip_ref;
2675             } else {
2676                 uri_ref = item->mask_ref;
2677             }
2679             // collect distinct mask object (and associate with item to apply transform)
2680             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2681                 referenced_objects[uri_ref->getObject()] = item;
2682             }
2683         }
2685         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2686     }
2688     // restore mask objects into a document
2689     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2690         SPObject *obj = (*it).first;
2691         GSList *items_to_move = NULL;
2692         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2693             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2694             items_to_move = g_slist_prepend (items_to_move, copy);
2695         }
2697         if (!obj->isReferenced()) {
2698             // delete from defs if no other object references this mask
2699             obj->deleteObject(false);
2700         }
2702         // remember parent and position of the item to which the clippath/mask was applied
2703         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2704         gint pos = SP_OBJECT_REPR((*it).second)->position();
2706         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2707             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2709             // insert into parent, restore pos
2710             parent->appendChild(repr);
2711             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2713             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2714             selection->add(repr);
2716             // transform mask, so it is moved the same spot where mask was applied
2717             NR::Matrix transform (mask_item->transform);
2718             transform *= (*it).second->transform;
2719             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2720         }
2722         g_slist_free (items_to_move);
2723     }
2725     if (apply_clip_path)
2726         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2727     else
2728         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2731 void fit_canvas_to_selection(SPDesktop *desktop) {
2732     g_return_if_fail(desktop != NULL);
2733     SPDocument *doc = sp_desktop_document(desktop);
2735     g_return_if_fail(doc != NULL);
2736     g_return_if_fail(desktop->selection != NULL);
2738     if (desktop->selection->isEmpty()) {
2739         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2740         return;
2741     }
2742     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
2743     if (bbox && !bbox->isEmpty()) {
2744         doc->fitToRect(*bbox);
2745     }
2746 };
2748 void fit_canvas_to_drawing(SPDocument *doc) {
2749     g_return_if_fail(doc != NULL);
2751     sp_document_ensure_up_to_date(doc);
2752     SPItem const *const root = SP_ITEM(doc->root);
2753     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
2754     if (bbox && !bbox->isEmpty()) {
2755         doc->fitToRect(*bbox);
2756     }
2757 };
2759 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2760     g_return_if_fail(desktop != NULL);
2761     SPDocument *doc = sp_desktop_document(desktop);
2763     g_return_if_fail(doc != NULL);
2764     g_return_if_fail(desktop->selection != NULL);
2766     if (desktop->selection->isEmpty()) {
2767         fit_canvas_to_drawing(doc);
2768     } else {
2769         fit_canvas_to_selection(desktop);
2770     }
2772     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
2773                      _("Fit page to selection"));
2774 };
2776 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2777     // don't operate on layers
2778     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2779         f(SP_ITEM(root), desktop);
2780     }
2781     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2782         //don't recurse into locked layers
2783         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2784             itemtree_map(f, iter, desktop);
2785         }
2786     }
2789 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2790     if (item->isLocked()) {
2791         item->setLocked(FALSE);
2792     }
2795 static void unhide(SPItem *item, SPDesktop *desktop) {
2796     if (desktop->itemIsHidden(item)) {
2797         item->setExplicitlyHidden(FALSE);
2798     }
2801 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2802     if (!dt) return;
2804     SPObject *root;
2805     if (layer_only) {
2806         root = dt->currentLayer();
2807     } else {
2808         root = dt->currentRoot();
2809     }
2811     itemtree_map(f, root, dt);
2814 void unlock_all(SPDesktop *dt) {
2815     process_all(&unlock, dt, true);
2818 void unlock_all_in_all_layers(SPDesktop *dt) {
2819     process_all(&unlock, dt, false);
2822 void unhide_all(SPDesktop *dt) {
2823     process_all(&unhide, dt, true);
2826 void unhide_all_in_all_layers(SPDesktop *dt) {
2827     process_all(&unhide, dt, false);
2831 /*
2832   Local Variables:
2833   mode:c++
2834   c-file-style:"stroustrup"
2835   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2836   indent-tabs-mode:nil
2837   fill-column:99
2838   End:
2839 */
2840 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :