Code

undo annotations
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * 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 <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "sp-marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-flowtext.h"
39 #include "sp-flowregion.h"
40 #include "text-editing.h"
41 #include "text-context.h"
42 #include "connector-context.h"
43 #include "sp-path.h"
44 #include "sp-conn-end.h"
45 #include "dropper-context.h"
46 #include <glibmm/i18n.h>
47 #include "libnr/nr-matrix-rotate-ops.h"
48 #include "libnr/nr-matrix-translate-ops.h"
49 #include "libnr/nr-rotate-fns.h"
50 #include "libnr/nr-scale-ops.h"
51 #include "libnr/nr-scale-translate-ops.h"
52 #include "libnr/nr-translate-matrix-ops.h"
53 #include "libnr/nr-translate-scale-ops.h"
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "prefs-utils.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "layer-fns.h"
69 #include "context-fns.h"
70 #include <map>
71 #include "helper/units.h"
72 #include "sp-item.h"
73 using NR::X;
74 using NR::Y;
76 #include "selection-chemistry.h"
78 /* fixme: find a better place */
79 GSList *clipboard = NULL;
80 GSList *defs_clipboard = NULL;
81 SPCSSAttr *style_clipboard = NULL;
82 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
84 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
86 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
87 {
88     Inkscape::XML::Node *copy = repr->duplicate();
90     // copy complete inherited style
91     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
92     sp_repr_css_set(copy, css, "style");
93     sp_repr_css_attr_unref(css);
95     // write the complete accummulated transform passed to us
96     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
97     gchar affinestr[80];
98     if (sp_svg_transform_write(affinestr, 79, full_t)) {
99         copy->setAttribute("transform", affinestr);
100     } else {
101         copy->setAttribute("transform", NULL);
102     }
104     *clip = g_slist_prepend(*clip, copy);
107 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
110     // Copy stuff referenced by all items to defs_clip:
111     if (defs_clip) {
112         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
113             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
114         }
115         *defs_clip = g_slist_reverse(*defs_clip);
116     }
118     // Store style:
119     if (style_clip) {
120         SPItem *item = SP_ITEM (items->data); // take from the first selected item
121         *style_clip = take_style_from_item (item);
122     }
124     if (clip) {
125         // Sort items:
126         GSList *sorted_items = g_slist_copy ((GSList *) items);
127         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
129         // Copy item reprs:
130         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
131             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
132         }
134         *clip = g_slist_reverse(*clip);
135         g_slist_free ((GSList *) sorted_items);
136     }
139 /**
140 Add gradients/patterns/markers referenced by copied objects to defs
141 */
142 void
143 paste_defs (GSList **defs_clip, SPDocument *doc)
145     if (!defs_clip)
146         return;
148     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
149         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
150         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
151         gchar const *id = repr->attribute("id");
152         if (!id || !doc->getObjectById(id)) {
153             Inkscape::XML::Node *copy = repr->duplicate();
154             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
155             Inkscape::GC::release(copy);
156         }
157     }
160 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
162     paste_defs (defs_clip, document);
164     GSList *copied = NULL;
165     // add objects to document
166     for (GSList *l = *clip; l != NULL; l = l->next) {
167         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
168         Inkscape::XML::Node *copy = repr->duplicate();
170         // premultiply the item transform by the accumulated parent transform in the paste layer
171         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
172         if (!local.test_identity()) {
173             gchar const *t_str = copy->attribute("transform");
174             NR::Matrix item_t (NR::identity());
175             if (t_str)
176                 sp_svg_transform_read(t_str, &item_t);
177             item_t *= local.inverse();
178             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
179             gchar affinestr[80];
180             if (sp_svg_transform_write(affinestr, 79, item_t)) {
181                 copy->setAttribute("transform", affinestr);
182             } else {
183                 copy->setAttribute("transform", NULL);
184             }
185         }
187         parent->appendChildRepr(copy);
188         copied = g_slist_prepend(copied, copy);
189         Inkscape::GC::release(copy);
190     }
191     return copied;
194 void sp_selection_delete_impl(const GSList *items)
196     for (const GSList *i = items ; i ; i = i->next ) {
197         sp_object_ref((SPObject *)i->data, NULL);
198     }
199     for (const GSList *i = items; i != NULL; i = i->next) {
200         SPItem *item = (SPItem *) i->data;
201         SP_OBJECT(item)->deleteObject();
202         sp_object_unref((SPObject *)item, NULL);
203     }
207 void sp_selection_delete()
209     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
210     if (desktop == NULL) {
211         return;
212     }
214     if (tools_isactive (desktop, TOOLS_TEXT))
215         if (sp_text_delete_selection(desktop->event_context)) {
216             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
217                              _("Delete text"));
218             return;
219         }
221     Inkscape::Selection *selection = sp_desktop_selection(desktop);
223     // check if something is selected
224     if (selection->isEmpty()) {
225         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
226         return;
227     }
229     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
230     selection->clear();
231     sp_selection_delete_impl (selected);
232     g_slist_free ((GSList *) selected);
234     /* a tool may have set up private information in it's selection context
235      * that depends on desktop items.  I think the only sane way to deal with
236      * this currently is to reset the current tool, which will reset it's
237      * associated selection context.  For example: deleting an object
238      * while moving it around the canvas.
239      */
240     tools_switch ( desktop, tools_active ( desktop ) );
242     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
243                      _("Delete"));
246 /* fixme: sequencing */
247 void sp_selection_duplicate()
249     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
250     if (desktop == NULL)
251         return;
253     Inkscape::Selection *selection = sp_desktop_selection(desktop);
255     // check if something is selected
256     if (selection->isEmpty()) {
257         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
258         return;
259     }
261     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
263     selection->clear();
265     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
266     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
268     GSList *newsel = NULL;
270     while (reprs) {
271         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
272         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
274         parent->appendChild(copy);
276         newsel = g_slist_prepend(newsel, copy);
277         reprs = g_slist_remove(reprs, reprs->data);
278         Inkscape::GC::release(copy);
279     }
281     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
282                      _("Duplicate"));
284     selection->setReprList(newsel);
286     g_slist_free(newsel);
289 void sp_edit_clear_all()
291     SPDesktop *dt = SP_ACTIVE_DESKTOP;
292     if (!dt)
293         return;
295     SPDocument *doc = sp_desktop_document(dt);
296     sp_desktop_selection(dt)->clear();
298     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
299     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
301     while (items) {
302         SP_OBJECT (items->data)->deleteObject();
303         items = g_slist_remove(items, items->data);
304     }
306     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
307                      _("Delete all"));
310 GSList *
311 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
313     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
314         if (SP_IS_ITEM(child) &&
315             !desktop->isLayer(SP_ITEM(child)) &&
316             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
317             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
318             (!exclude || !g_slist_find ((GSList *) exclude, child))
319             )
320         {
321             list = g_slist_prepend (list, SP_ITEM(child));
322         }
324         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
325             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
326         }
327     }
329     return list;
332 void sp_edit_select_all_full (bool force_all_layers, bool invert)
334     SPDesktop *dt = SP_ACTIVE_DESKTOP;
335     if (!dt)
336         return;
338     Inkscape::Selection *selection = sp_desktop_selection(dt);
340     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
342     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
343     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
344     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
346     GSList *items = NULL;
348     const GSList *exclude = NULL;
349     if (invert) {
350         exclude = selection->itemList();
351     }
353     if (force_all_layers)
354         inlayer = PREFS_SELECTION_ALL;
356     switch (inlayer) {
357         case PREFS_SELECTION_LAYER: {
358         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
359              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
360         return;
362         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
364         for (GSList *i = all_items; i; i = i->next) {
365             SPItem *item = SP_ITEM (i->data);
367             if (item && (!onlysensitive || !item->isLocked())) {
368                 if (!onlyvisible || !dt->itemIsHidden(item)) {
369                     if (!dt->isLayer(item)) {
370                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
371                             items = g_slist_prepend (items, item); // leave it in the list
372                         }
373                     }
374                 }
375             }
376         }
378         g_slist_free (all_items);
379             break;
380         }
381         case PREFS_SELECTION_LAYER_RECURSIVE: {
382             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
383             break;
384         }
385         default: {
386         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
387             break;
388     }
389     }
391     selection->setList (items);
393     if (items) {
394         g_slist_free (items);
395     }
398 void sp_edit_select_all ()
400     sp_edit_select_all_full (false, false);
403 void sp_edit_select_all_in_all_layers ()
405     sp_edit_select_all_full (true, false);
408 void sp_edit_invert ()
410     sp_edit_select_all_full (false, true);
413 void sp_edit_invert_in_all_layers ()
415     sp_edit_select_all_full (true, true);
418 void sp_selection_group()
420     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
421     if (desktop == NULL)
422         return;
424     SPDocument *document = sp_desktop_document (desktop);
426     Inkscape::Selection *selection = sp_desktop_selection(desktop);
428     // Check if something is selected.
429     if (selection->isEmpty()) {
430         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
431         return;
432     }
434     GSList const *l = (GSList *) selection->reprList();
436     // Check if at least two objects are selected.
437     if (l->next == NULL) {
438         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
439         return;
440     }
442     GSList *p = g_slist_copy((GSList *) l);
444     selection->clear();
446     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
448     // Remember the position and parent of the topmost object.
449     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
450     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
452     Inkscape::XML::Node *group = sp_repr_new("svg:g");
454     while (p) {
455         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
457         if (current->parent() == topmost_parent) {
458             Inkscape::XML::Node *spnew = current->duplicate();
459             sp_repr_unparent(current);
460             group->appendChild(spnew);
461             Inkscape::GC::release(spnew);
462             topmost --; // only reduce count for those items deleted from topmost_parent
463         } else { // move it to topmost_parent first
464                 GSList *temp_clip = NULL;
466                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
467                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
468                 gchar const *t_str = current->attribute("transform");
469                 NR::Matrix item_t (NR::identity());
470                 if (t_str)
471                     sp_svg_transform_read(t_str, &item_t);
472                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
473                 //FIXME: when moving both clone and original from a transformed group (either by
474                 //grouping into another parent, or by cut/paste) the transform from the original's
475                 //parent becomes embedded into original itself, and this affects its clones. Fix
476                 //this by remembering the transform diffs we write to each item into an array and
477                 //then, if this is clone, looking up its original in that array and pre-multiplying
478                 //it by the inverse of that original's transform diff.
480                 sp_selection_copy_one (current, item_t, &temp_clip);
481                 sp_repr_unparent(current);
483                 // paste into topmost_parent (temporarily)
484                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
485                 if (temp_clip) g_slist_free (temp_clip);
486                 if (copied) { // if success,
487                     // take pasted object (now in topmost_parent)
488                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
489                     // make a copy
490                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
491                     // remove pasted
492                     sp_repr_unparent(in_topmost);
493                     // put its copy into group
494                     group->appendChild(spnew);
495                     Inkscape::GC::release(spnew);
496                     g_slist_free (copied);
497                 }
498         }
499         p = g_slist_remove(p, current);
500     }
502     // Add the new group to the topmost members' parent
503     topmost_parent->appendChild(group);
505     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
506     group->setPosition(topmost + 1);
508     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
509                      _("Group"));
511     selection->set(group);
512     Inkscape::GC::release(group);
515 void sp_selection_ungroup()
517     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
518     if (desktop == NULL)
519         return;
521     Inkscape::Selection *selection = sp_desktop_selection(desktop);
523     if (selection->isEmpty()) {
524         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
525         return;
526     }
528     GSList *items = g_slist_copy((GSList *) selection->itemList());
529     selection->clear();
531     // Get a copy of current selection.
532     GSList *new_select = NULL;
533     bool ungrouped = false;
534     for (GSList *i = items;
535          i != NULL;
536          i = i->next)
537     {
538         SPItem *group = (SPItem *) i->data;
540         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
541         if (!SP_IS_OBJECT(group)) {
542             continue;
543         }
545         /* We do not allow ungrouping <svg> etc. (lauris) */
546         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
547             // keep the non-group item in the new selection
548             selection->add(group);
549             continue;
550         }
552         GSList *children = NULL;
553         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
554         sp_item_group_ungroup(SP_GROUP(group), &children, false);
555         ungrouped = true;
556         // Add ungrouped items to the new selection.
557         new_select = g_slist_concat(new_select, children);
558     }
560     if (new_select) { // Set new selection.
561         selection->addList(new_select);
562         g_slist_free(new_select);
563     }
564     if (!ungrouped) {
565         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
566     }
568     g_slist_free(items);
570     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
571                      _("Ungroup"));
574 static SPGroup *
575 sp_item_list_common_parent_group(const GSList *items)
577     if (!items) {
578         return NULL;
579     }
580     SPObject *parent = SP_OBJECT_PARENT(items->data);
581     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
582     if (!SP_IS_GROUP(parent)) {
583         return NULL;
584     }
585     for (items = items->next; items; items = items->next) {
586         if (SP_OBJECT_PARENT(items->data) != parent) {
587             return NULL;
588         }
589     }
591     return SP_GROUP(parent);
594 /** Finds out the minimum common bbox of the selected items
595  */
596 NR::Rect
597 enclose_items(const GSList *items)
599     g_assert(items != NULL);
601     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
603     for (GSList *i = items->next; i; i = i->next) {
604         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
605     }
607     return r;
610 SPObject *
611 prev_sibling(SPObject *child)
613     SPObject *parent = SP_OBJECT_PARENT(child);
614     if (!SP_IS_GROUP(parent)) {
615         return NULL;
616     }
617     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
618         if (i->next == child)
619             return i;
620     }
621     return NULL;
624 void
625 sp_selection_raise()
627     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
628     if (!desktop)
629         return;
631     Inkscape::Selection *selection = sp_desktop_selection(desktop);
633     GSList const *items = (GSList *) selection->itemList();
634     if (!items) {
635         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
636         return;
637     }
639     SPGroup const *group = sp_item_list_common_parent_group(items);
640     if (!group) {
641         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
642         return;
643     }
645     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
647     /* construct reverse-ordered list of selected children */
648     GSList *rev = g_slist_copy((GSList *) items);
649     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
651     // find out the common bbox of the selected items
652     NR::Rect selected = enclose_items(items);
654     // for all objects in the selection (starting from top)
655     while (rev) {
656         SPObject *child = SP_OBJECT(rev->data);
657         // for each selected object, find the next sibling
658         for (SPObject *newref = child->next; newref; newref = newref->next) {
659             // if the sibling is an item AND overlaps our selection,
660             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
661                 // AND if it's not one of our selected objects,
662                 if (!g_slist_find((GSList *) items, newref)) {
663                     // move the selected object after that sibling
664                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
665                 }
666                 break;
667             }
668         }
669         rev = g_slist_remove(rev, child);
670     }
672     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
673                      _("Raise"));
676 void sp_selection_raise_to_top()
678     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
679     if (desktop == NULL)
680         return;
682     SPDocument *document = sp_desktop_document(desktop);
683     Inkscape::Selection *selection = sp_desktop_selection(desktop);
685     if (selection->isEmpty()) {
686         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
687         return;
688     }
690     GSList const *items = (GSList *) selection->itemList();
692     SPGroup const *group = sp_item_list_common_parent_group(items);
693     if (!group) {
694         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
695         return;
696     }
698     GSList *rl = g_slist_copy((GSList *) selection->reprList());
699     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
701     for (GSList *l = rl; l != NULL; l = l->next) {
702         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
703         repr->setPosition(-1);
704     }
706     g_slist_free(rl);
708     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
709                      _("Raise to top"));
712 void
713 sp_selection_lower()
715     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
716     if (desktop == NULL)
717         return;
719     Inkscape::Selection *selection = sp_desktop_selection(desktop);
721     GSList const *items = (GSList *) selection->itemList();
722     if (!items) {
723         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
724         return;
725     }
727     SPGroup const *group = sp_item_list_common_parent_group(items);
728     if (!group) {
729         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
730         return;
731     }
733     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
735     // find out the common bbox of the selected items
736     NR::Rect selected = enclose_items(items);
738     /* construct direct-ordered list of selected children */
739     GSList *rev = g_slist_copy((GSList *) items);
740     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
741     rev = g_slist_reverse(rev);
743     // for all objects in the selection (starting from top)
744     while (rev) {
745         SPObject *child = SP_OBJECT(rev->data);
746         // for each selected object, find the prev sibling
747         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
748             // if the sibling is an item AND overlaps our selection,
749             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
750                 // AND if it's not one of our selected objects,
751                 if (!g_slist_find((GSList *) items, newref)) {
752                     // move the selected object before that sibling
753                     SPObject *put_after = prev_sibling(newref);
754                     if (put_after)
755                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
756                     else
757                         SP_OBJECT_REPR(child)->setPosition(0);
758                 }
759                 break;
760             }
761         }
762         rev = g_slist_remove(rev, child);
763     }
765     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
766                      _("Lower"));
770 void sp_selection_lower_to_bottom()
772     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
773     if (desktop == NULL)
774         return;
776     SPDocument *document = sp_desktop_document(desktop);
777     Inkscape::Selection *selection = sp_desktop_selection(desktop);
779     if (selection->isEmpty()) {
780         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
781         return;
782     }
784     GSList const *items = (GSList *) selection->itemList();
786     SPGroup const *group = sp_item_list_common_parent_group(items);
787     if (!group) {
788         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
789         return;
790     }
792     GSList *rl;
793     rl = g_slist_copy((GSList *) selection->reprList());
794     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
795     rl = g_slist_reverse(rl);
797     for (GSList *l = rl; l != NULL; l = l->next) {
798         gint minpos;
799         SPObject *pp, *pc;
800         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
801         pp = document->getObjectByRepr(sp_repr_parent(repr));
802         minpos = 0;
803         g_assert(SP_IS_GROUP(pp));
804         pc = sp_object_first_child(pp);
805         while (!SP_IS_ITEM(pc)) {
806             minpos += 1;
807             pc = pc->next;
808         }
809         repr->setPosition(minpos);
810     }
812     g_slist_free(rl);
814     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
815                      _("Lower to bottom"));
818 void
819 sp_undo(SPDesktop *desktop, SPDocument *)
821         if (!sp_document_undo(sp_desktop_document(desktop)))
822             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
825 void
826 sp_redo(SPDesktop *desktop, SPDocument *)
828         if (!sp_document_redo(sp_desktop_document(desktop)))
829             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
832 void sp_selection_cut()
834     sp_selection_copy();
835     sp_selection_delete();
838 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
840     SPGradient *ref = gradient;
842     while (ref) {
843         // climb up the refs, copying each one in the chain
844         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
845         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
847         ref = ref->ref->getObject();
848     }
851 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
853     SPPattern *ref = pattern;
855     while (ref) {
856         // climb up the refs, copying each one in the chain
857         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
858         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
860         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
861         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
862             if (!SP_IS_ITEM (child))
863                 continue;
864             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
865         }
867         ref = ref->ref->getObject();
868     }
871 void sp_copy_single (GSList **defs_clip, SPObject *thing)
873     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
874     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
878 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
880     SPItem *path = sp_textpath_get_path_item (tp);
881     if (!path)
882         return;
883     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
884         return;
885     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
886     *defs_clip = g_slist_prepend (*defs_clip, repr);
889 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
891     SPStyle *style = SP_OBJECT_STYLE (item);
893     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
894         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
895         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
896             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
897         if (SP_IS_PATTERN (server))
898             sp_copy_pattern (defs_clip, SP_PATTERN(server));
899     }
901     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
902         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
903         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
904             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
905         if (SP_IS_PATTERN (server))
906             sp_copy_pattern (defs_clip, SP_PATTERN(server));
907     }
909     if (SP_IS_SHAPE (item)) {
910         SPShape *shape = SP_SHAPE (item);
911         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
912             if (shape->marker[i]) {
913                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
914             }
915         }
916     }
918     if (SP_IS_TEXT_TEXTPATH (item)) {
919         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
920     }
922     if (item->clip_ref->getObject()) {
923         sp_copy_single (defs_clip, item->clip_ref->getObject());
924     }
926     if (item->mask_ref->getObject()) {
927         SPObject *mask = item->mask_ref->getObject();
928         sp_copy_single (defs_clip, mask);
929         // recurse into the mask for its gradients etc.
930         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
931             if (SP_IS_ITEM(o))
932                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
933         }
934     }
936     // recurse
937     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
938         if (SP_IS_ITEM(o))
939             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
940     }
943 /**
944  * \pre item != NULL
945  */
946 SPCSSAttr *
947 take_style_from_item (SPItem *item)
949     // write the complete cascaded style, context-free
950     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
951     if (css == NULL)
952         return NULL;
954     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
955         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
956         // if this is a text with exactly one tspan child, merge the style of that tspan as well
957         // If this is a group, merge the style of its topmost (last) child with style
958         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
959             if (SP_OBJECT_STYLE (last_element) != NULL) {
960                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
961                 if (temp) {
962                     sp_repr_css_merge (css, temp);
963                     sp_repr_css_attr_unref (temp);
964                 }
965                 break;
966             }
967         }
968     }
969     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
970         // do not copy text properties from non-text objects, it's confusing
971         css = sp_css_attr_unset_text (css);
972     }
974     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
975     double ex = NR::expansion(sp_item_i2doc_affine(item));
976     if (ex != 1.0) {
977         css = sp_css_attr_scale (css, ex);
978     }
980     return css;
984 void sp_selection_copy()
986     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
987     if (desktop == NULL)
988         return;
990     Inkscape::Selection *selection = sp_desktop_selection(desktop);
992     if (tools_isactive (desktop, TOOLS_DROPPER)) {
993         sp_dropper_context_copy(desktop->event_context);
994         return; // copied color under cursor, nothing else to do
995     }
997     // check if something is selected
998     if (selection->isEmpty()) {
999         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1000         return;
1001     }
1003     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1005     // 0. Copy text to system clipboard
1006     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1007     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1008     Glib::ustring text;
1009     if (tools_isactive (desktop, TOOLS_TEXT)) {
1010         text = sp_text_get_selected_text(desktop->event_context);
1011     }
1013     if (text.empty()) {
1014         guint texts = 0;
1015         for (GSList *i = (GSList *) items; i; i = i->next) {
1016             SPItem *item = SP_ITEM (i->data);
1017             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1018                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1019                     text += " ";
1020                 gchar *this_text = sp_te_get_string_multiline (item);
1021                 if (this_text) {
1022                     text += this_text;
1023                     g_free(this_text);
1024                 }
1025                 texts++;
1026             }
1027         }
1028     }
1029     if (!text.empty()) {
1030         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1031         refClipboard->set_text(text);
1032     }
1034     // clear old defs clipboard
1035     while (defs_clipboard) {
1036         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1037         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1038     }
1040     // clear style clipboard
1041     if (style_clipboard) {
1042         sp_repr_css_attr_unref (style_clipboard);
1043         style_clipboard = NULL;
1044     }
1046     //clear main clipboard
1047     while (clipboard) {
1048         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1049         clipboard = g_slist_remove(clipboard, clipboard->data);
1050     }
1052     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1054     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1055         SPStyle *const query = sp_style_new();
1056         if (sp_desktop_query_style_all (desktop, query)) {
1057             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1058             if (css != NULL) {
1059                 // clear style clipboard
1060                 if (style_clipboard) {
1061                     sp_repr_css_attr_unref (style_clipboard);
1062                     style_clipboard = NULL;
1063                 }
1064                 //sp_repr_css_print (css);
1065                 style_clipboard = css;
1066             }
1067         }
1068         g_free (query);
1069     }
1071     size_clipboard = selection->bounds();
1073     g_slist_free ((GSList *) items);
1076 void sp_selection_paste(bool in_place)
1078     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1080     if (desktop == NULL) {
1081         return;
1082     }
1084     SPDocument *document = sp_desktop_document(desktop);
1086     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1087         return;
1088     }
1090     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1092     if (tools_isactive (desktop, TOOLS_TEXT)) {
1093         if (sp_text_paste_inline(desktop->event_context))
1094             return; // pasted from system clipboard into text, nothing else to do
1095     }
1097     // check if something is in the clipboard
1098     if (clipboard == NULL) {
1099         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1100         return;
1101     }
1103     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1104     // add pasted objects to selection
1105     selection->setReprList((GSList const *) copied);
1106     g_slist_free (copied);
1108     if (!in_place) {
1109         sp_document_ensure_up_to_date(document);
1111         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1113         /* Snap the offset of the new item(s) to the grid */
1114         /* FIXME: this gridsnap fiddling is a hack. */
1115         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1116         gdouble const curr_gridsnap = s.getDistance();
1117         s.setDistance(NR_HUGE);
1118         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1119         s.setDistance(curr_gridsnap);
1120         sp_selection_move_relative(selection, m);
1121     }
1123     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1124                      _("Paste"));
1127 void sp_selection_paste_style()
1129     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1130     if (desktop == NULL) return;
1132     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1134     // check if something is in the clipboard
1135     if (clipboard == NULL) {
1136         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1137         return;
1138     }
1140     // check if something is selected
1141     if (selection->isEmpty()) {
1142         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1143         return;
1144     }
1146     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1148     sp_desktop_set_style (desktop, style_clipboard);
1150     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1151                      _("Paste style"));
1154 void sp_selection_paste_size (bool apply_x, bool apply_y)
1156     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1157     if (desktop == NULL) return;
1159     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1161     // check if something is in the clipboard
1162     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1163         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1164         return;
1165     }
1167     // check if something is selected
1168     if (selection->isEmpty()) {
1169         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1170         return;
1171     }
1173     NR::Rect current = selection->bounds();
1174     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1175         return;
1176     }
1178     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1179     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1181     sp_selection_scale_relative (selection, current.midpoint(), 
1182                                  NR::scale(
1183                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1184                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1186     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1187                      _("Paste size"));
1190 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1192     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1193     if (desktop == NULL) return;
1195     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1197     // check if something is in the clipboard
1198     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1199         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1200         return;
1201     }
1203     // check if something is selected
1204     if (selection->isEmpty()) {
1205         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1206         return;
1207     }
1209     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1210         SPItem *item = SP_ITEM(l->data);
1212         NR::Rect current = sp_item_bbox_desktop(item);
1213         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1214             continue;
1215         }
1217         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1218         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1220         sp_item_scale_rel (item,
1221                                  NR::scale(
1222                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1223                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1225     }
1227     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1228                      _("Paste size separately"));
1231 void sp_selection_to_next_layer ()
1233     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1235     Inkscape::Selection *selection = sp_desktop_selection(dt);
1237     // check if something is selected
1238     if (selection->isEmpty()) {
1239         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1240         return;
1241     }
1243     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1245     bool no_more = false; // Set to true, if no more layers above
1246     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1247     if (next) {
1248         GSList *temp_clip = NULL;
1249         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1250         sp_selection_delete_impl (items);
1251         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1252         GSList *copied;
1253         if(next) {
1254             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1255         } else {
1256             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1257             no_more = true;
1258         }
1259         selection->setReprList((GSList const *) copied);
1260         g_slist_free (copied);
1261         if (temp_clip) g_slist_free (temp_clip);
1262         if (next) dt->setCurrentLayer(next);
1263         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1264                          _("Raise to next layer"));
1265     } else {
1266         no_more = true;
1267     }
1269     if (no_more) {
1270         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1271     }
1273     g_slist_free ((GSList *) items);
1276 void sp_selection_to_prev_layer ()
1278     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1280     Inkscape::Selection *selection = sp_desktop_selection(dt);
1282     // check if something is selected
1283     if (selection->isEmpty()) {
1284         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1285         return;
1286     }
1288     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1290     bool no_more = false; // Set to true, if no more layers below
1291     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1292     if (next) {
1293         GSList *temp_clip = NULL;
1294         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1295         sp_selection_delete_impl (items);
1296         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1297         GSList *copied;
1298         if(next) {
1299             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1300         } else {
1301             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1302             no_more = true;
1303         }
1304         selection->setReprList((GSList const *) copied);
1305         g_slist_free (copied);
1306         if (temp_clip) g_slist_free (temp_clip);
1307         if (next) dt->setCurrentLayer(next);
1308         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1309                          _("Lower to previous layer"));
1310     } else {
1311         no_more = true;
1312     }
1314     if (no_more) {
1315         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1316     }
1318     g_slist_free ((GSList *) items);
1321 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1322 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1323 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1324 that case, items are already in the new position, but the repr is in the old, and this function
1325 then simply updates the repr from item->transform.
1326  */
1327 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1329     if (selection->isEmpty())
1330         return;
1332     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1333         SPItem *item = SP_ITEM(l->data);
1335         NR::Point old_center(0,0);
1336         if (set_i2d && item->isCenterSet())
1337             old_center = item->getCenter();
1339 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1340          At the time of writing, this is the only place to re-enable. */
1341         sp_item_update_cns(*item, selection->desktop());
1342 #endif
1344         // we're moving both a clone and its original
1345         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1346         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)))) ));
1347         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1348         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1349        
1350         // If we're moving a connector, we want to detach it
1351         // from shapes that aren't part of the selection, but
1352         // leave it attached if they are
1353         if (cc_item_is_connector(item)) {
1354             SPItem *attItem[2];
1355             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1356             
1357             for (int n = 0; n < 2; ++n) {
1358                 if (!selection->includes(attItem[n])) {
1359                     sp_conn_end_detach(item, n);
1360                 }
1361             }
1362         }
1363         
1364         // "clones are unmoved when original is moved" preference
1365         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1366         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1367         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1369         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1370         // transform of its original and respond to it itself. Without this, a clone is doubly
1371         // transformed, very unintuitive.
1372       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1373       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1374       // Same for linked offset if we are also moving its source: do not move it.
1375         if (transform_textpath_with_path || transform_offset_with_source) {
1376                 // restore item->transform field from the repr, in case it was changed by seltrans
1377             sp_object_read_attr (SP_OBJECT (item), "transform");
1379         } else if (transform_flowtext_with_frame) {
1380             // apply the inverse of the region's transform to the <use> so that the flow remains
1381             // the same (even though the output itself gets transformed)
1382             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1383                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1384                     continue;
1385                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1386                     if (!SP_IS_USE(use)) continue;
1387                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1388                 }
1389             }
1390         } else if (transform_clone_with_original) {
1391             // We are transforming a clone along with its original. The below matrix juggling is
1392             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1393             // transform and its move compensation are both cancelled out.
1395             // restore item->transform field from the repr, in case it was changed by seltrans
1396             sp_object_read_attr (SP_OBJECT (item), "transform");
1398             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1399             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1400             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1401             NR::Matrix result = t_inv * item->transform * t;
1403             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1404                 // we need to cancel out the move compensation, too
1406                 // find out the clone move, same as in sp_use_move_compensate
1407                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1408                 NR::Matrix clone_move = parent.inverse() * t * parent;
1410                 if (prefs_parallel) {
1411                     NR::Matrix move = result * clone_move * t_inv;
1412                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1414                 } else if (prefs_unmoved) {
1415                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1416                         clone_move = NR::identity();
1417                     NR::Matrix move = result * clone_move;
1418                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1419                 }
1421             } else {
1422                 // just apply the result
1423                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1424             }
1426         } else {
1427             if (set_i2d) {
1428                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1429             }
1430             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1431         }
1433         // if we're moving the actual object, not just updating the repr, we can transform the
1434         // center by the same matrix (only necessary for non-translations)
1435         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1436             item->setCenter(old_center * affine);
1437             SP_OBJECT(item)->updateRepr();
1438         }
1439     }
1442 void sp_selection_remove_transform()
1444     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1445     if (desktop == NULL)
1446         return;
1448     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1450     GSList const *l = (GSList *) selection->reprList();
1451     while (l != NULL) {
1452         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1453         l = l->next;
1454     }
1456     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1457                      _("Remove transform"));
1460 void
1461 sp_selection_scale_absolute(Inkscape::Selection *selection,
1462                             double const x0, double const x1,
1463                             double const y0, double const y1)
1465     if (selection->isEmpty())
1466         return;
1468     NR::Rect const bbox(selection->bounds());
1469     if (bbox.isEmpty()) {
1470         return;
1471     }
1473     NR::translate const p2o(-bbox.min());
1475     NR::scale const newSize(x1 - x0,
1476                             y1 - y0);
1477     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1478     NR::translate const o2n(x0, y0);
1479     NR::Matrix const final( p2o * scale * o2n );
1481     sp_selection_apply_affine(selection, final);
1485 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1487     if (selection->isEmpty())
1488         return;
1490     NR::Rect const bbox(selection->bounds());
1492     if (bbox.isEmpty()) {
1493         return;
1494     }
1496     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1497     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1498          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1499     {
1500         return;
1501     }
1503     NR::translate const n2d(-align);
1504     NR::translate const d2n(align);
1505     NR::Matrix const final( n2d * scale * d2n );
1506     sp_selection_apply_affine(selection, final);
1509 void
1510 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1512     NR::translate const d2n(center);
1513     NR::translate const n2d(-center);
1514     NR::rotate const rotate(rotate_degrees(angle_degrees));
1515     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1516     sp_selection_apply_affine(selection, final);
1519 void
1520 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1522     NR::translate const d2n(align);
1523     NR::translate const n2d(-align);
1524     NR::Matrix const skew(1, dy,
1525                           dx, 1,
1526                           0, 0);
1527     NR::Matrix const final( n2d * skew * d2n );
1528     sp_selection_apply_affine(selection, final);
1531 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1533     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1536 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1538     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1542 /**
1543  * \brief sp_selection_rotate_90
1544  *
1545  * This function rotates selected objects 90 degrees clockwise.
1546  *
1547  */
1549 void sp_selection_rotate_90_cw()
1551     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1553     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1555     if (selection->isEmpty())
1556         return;
1558     GSList const *l = selection->itemList();
1559     NR::rotate const rot_neg_90(NR::Point(0, -1));
1560     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1561         SPItem *item = SP_ITEM(l2->data);
1562         sp_item_rotate_rel(item, rot_neg_90);
1563     }
1565     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1566                      _("Rotate 90&#176; CW"));
1570 /**
1571  * \brief sp_selection_rotate_90_ccw
1572  *
1573  * This function rotates selected objects 90 degrees counter-clockwise.
1574  *
1575  */
1577 void sp_selection_rotate_90_ccw()
1579     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1581     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1583     if (selection->isEmpty())
1584         return;
1586     GSList const *l = selection->itemList();
1587     NR::rotate const rot_neg_90(NR::Point(0, 1));
1588     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1589         SPItem *item = SP_ITEM(l2->data);
1590         sp_item_rotate_rel(item, rot_neg_90);
1591     }
1593     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1594                      _("Rotate 90&#176; CCW"));
1597 void
1598 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1600     if (selection->isEmpty())
1601         return;
1603     NR::Point center = selection->center();
1605     sp_selection_rotate_relative(selection, center, angle_degrees);
1607     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1608                            ( ( angle_degrees > 0 )
1609                              ? "selector:rotate:ccw"
1610                              : "selector:rotate:cw" ), 
1611                            SP_VERB_CONTEXT_SELECT, 
1612                            _("Rotate"));
1615 /**
1616 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1617 */
1618 void
1619 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1621     if (selection->isEmpty())
1622         return;
1624     NR::Rect const bbox(selection->bounds());
1626     NR::Point center = selection->center();
1628     gdouble const zoom = selection->desktop()->current_zoom();
1629     gdouble const zmove = angle / zoom;
1630     gdouble const r = NR::L2(bbox.max() - center);
1632     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1634     sp_selection_rotate_relative(selection, center, zangle);
1636     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1637                            ( (angle > 0)
1638                              ? "selector:rotate:ccw"
1639                              : "selector:rotate:cw" ),
1640                            SP_VERB_CONTEXT_SELECT, 
1641                            _("Rotate by pixels"));
1644 void
1645 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1647     if (selection->isEmpty())
1648         return;
1650     NR::Rect const bbox(selection->bounds());
1651     NR::Point const center(bbox.midpoint());
1652     double const max_len = bbox.maxExtent();
1654     // you can't scale "do nizhe pola" (below zero)
1655     if ( max_len + grow <= 1e-3 ) {
1656         return;
1657     }
1659     double const times = 1.0 + grow / max_len;
1660     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1662     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1663                            ( (grow > 0)
1664                              ? "selector:scale:larger"
1665                              : "selector:scale:smaller" ),
1666                            SP_VERB_CONTEXT_SELECT,
1667                            _("Scale"));
1670 void
1671 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1673     sp_selection_scale(selection,
1674                        grow_pixels / selection->desktop()->current_zoom());
1677 void
1678 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1680     if (selection->isEmpty())
1681         return;
1683     NR::Point const center(selection->bounds().midpoint());
1684     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1685     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1686                      _("Scale by whole factor"));
1689 void
1690 sp_selection_move(gdouble dx, gdouble dy)
1692     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1693     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1694     if (selection->isEmpty()) {
1695         return;
1696     }
1698     sp_selection_move_relative(selection, dx, dy);
1700     if (dx == 0) {
1701         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1702                                _("Move vertically"));
1703     } else if (dy == 0) {
1704         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1705                                _("Move horizontally"));
1706     } else {
1707         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1708                          _("Move"));
1709     }
1712 void
1713 sp_selection_move_screen(gdouble dx, gdouble dy)
1715     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1717     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1718     if (selection->isEmpty()) {
1719         return;
1720     }
1722     // same as sp_selection_move but divide deltas by zoom factor
1723     gdouble const zoom = desktop->current_zoom();
1724     gdouble const zdx = dx / zoom;
1725     gdouble const zdy = dy / zoom;
1726     sp_selection_move_relative(selection, zdx, zdy);
1728     if (dx == 0) {
1729         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1730                                _("Nudge vertically by pixels"));
1731     } else if (dy == 0) {
1732         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1733                                _("Nudge horizontally by pixels"));
1734     } else {
1735         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1736                          _("Move"));
1737     }
1740 namespace {
1742 template <typename D>
1743 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1744                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1746 template <typename D>
1747 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1748                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1750 struct Forward {
1751     typedef SPObject *Iterator;
1753     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1754     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1755     static void dispose(Iterator i) {}
1757     static SPObject *object(Iterator i) { return i; }
1758     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1759 };
1761 struct Reverse {
1762     typedef GSList *Iterator;
1764     static Iterator children(SPObject *o) {
1765         return make_list(o->firstChild(), NULL);
1766     }
1767     static Iterator siblings_after(SPObject *o) {
1768         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1769     }
1770     static void dispose(Iterator i) {
1771         g_slist_free(i);
1772     }
1774     static SPObject *object(Iterator i) {
1775         return reinterpret_cast<SPObject *>(i->data);
1776     }
1777     static Iterator next(Iterator i) { return i->next; }
1779 private:
1780     static GSList *make_list(SPObject *object, SPObject *limit) {
1781         GSList *list=NULL;
1782         while ( object != limit ) {
1783             list = g_slist_prepend(list, object);
1784             object = SP_OBJECT_NEXT(object);
1785         }
1786         return list;
1787     }
1788 };
1792 void
1793 sp_selection_item_next(void)
1795     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1796     g_return_if_fail(desktop != NULL);
1797     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1799     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1800     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1801     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1803     SPObject *root;
1804     if (PREFS_SELECTION_ALL != inlayer) {
1805         root = selection->activeContext();
1806     } else {
1807         root = desktop->currentRoot();
1808     }
1810     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1812     if (item) {
1813         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1814         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1815             scroll_to_show_item(desktop, item);
1816         }
1817     }
1820 void
1821 sp_selection_item_prev(void)
1823     SPDocument *document = SP_ACTIVE_DOCUMENT;
1824     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1825     g_return_if_fail(document != NULL);
1826     g_return_if_fail(desktop != NULL);
1827     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1829     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1830     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1831     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1833     SPObject *root;
1834     if (PREFS_SELECTION_ALL != inlayer) {
1835         root = selection->activeContext();
1836     } else {
1837         root = desktop->currentRoot();
1838     }
1840     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1842     if (item) {
1843         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1844         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1845             scroll_to_show_item(desktop, item);
1846         }
1847     }
1850 namespace {
1852 template <typename D>
1853 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1854                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1856     SPObject *current=root;
1857     while (items) {
1858         SPItem *item=SP_ITEM(items->data);
1859         if ( root->isAncestorOf(item) &&
1860              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1861         {
1862             current = item;
1863             break;
1864         }
1865         items = items->next;
1866     }
1868     GSList *path=NULL;
1869     while ( current != root ) {
1870         path = g_slist_prepend(path, current);
1871         current = SP_OBJECT_PARENT(current);
1872     }
1874     SPItem *next;
1875     // first, try from the current object
1876     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1877     g_slist_free(path);
1879     if (!next) { // if we ran out of objects, start over at the root
1880         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1881     }
1883     return next;
1886 template <typename D>
1887 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1888                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1890     typename D::Iterator children;
1891     typename D::Iterator iter;
1893     SPItem *found=NULL;
1895     if (path) {
1896         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1897         g_assert(SP_OBJECT_PARENT(object) == root);
1898         if (desktop->isLayer(object)) {
1899             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1900         }
1901         iter = children = D::siblings_after(object);
1902     } else {
1903         iter = children = D::children(root);
1904     }
1906     while ( iter && !found ) {
1907         SPObject *object=D::object(iter);
1908         if (desktop->isLayer(object)) {
1909             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1910                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1911             }
1912         } else if ( SP_IS_ITEM(object) &&
1913                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1914                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1915                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1916                     !desktop->isLayer(SP_ITEM(object)) )
1917         {
1918             found = SP_ITEM(object);
1919         }
1920         iter = D::next(iter);
1921     }
1923     D::dispose(children);
1925     return found;
1930 /**
1931  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1932  * \a item.
1933  */
1934 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1936     NR::Rect dbox = desktop->get_display_area();
1937     NR::Rect sbox = sp_item_bbox_desktop(item);
1939     if (dbox.contains(sbox) == false) {
1940         NR::Point const s_dt = sbox.midpoint();
1941         NR::Point const s_w = desktop->d2w(s_dt);
1942         NR::Point const d_dt = dbox.midpoint();
1943         NR::Point const d_w = desktop->d2w(d_dt);
1944         NR::Point const moved_w( d_w - s_w );
1945         gint const dx = (gint) moved_w[X];
1946         gint const dy = (gint) moved_w[Y];
1947         desktop->scroll_world(dx, dy);
1948     }
1952 void
1953 sp_selection_clone()
1955     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1956     if (desktop == NULL)
1957         return;
1959     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1961     // check if something is selected
1962     if (selection->isEmpty()) {
1963         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1964         return;
1965     }
1967     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1968   
1969     selection->clear();
1970   
1971     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1972     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1974     GSList *newsel = NULL;
1975  
1976     while (reprs) {
1977         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1978         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1980         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1981         sp_repr_set_attr(clone, "x", "0");
1982         sp_repr_set_attr(clone, "y", "0");
1983         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1985         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1986         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1987         
1988         // add the new clone to the top of the original's parent
1989         parent->appendChild(clone);
1991         newsel = g_slist_prepend(newsel, clone);
1992         reprs = g_slist_remove(reprs, sel_repr);
1993         Inkscape::GC::release(clone);
1994     }
1995     
1996     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
1997                      _("Clone"));
1999     selection->setReprList(newsel);
2000  
2001     g_slist_free(newsel);
2004 void
2005 sp_selection_unlink()
2007     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2008     if (!desktop)
2009         return;
2011     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2013     if (selection->isEmpty()) {
2014         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2015         return;
2016     }
2018     // Get a copy of current selection.
2019     GSList *new_select = NULL;
2020     bool unlinked = false;
2021     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2022          items != NULL;
2023          items = items->next)
2024     {
2025         SPItem *use = (SPItem *) items->data;
2027         if (!SP_IS_USE(use)) {
2028             // keep the non-yse item in the new selection
2029             new_select = g_slist_prepend(new_select, use);
2030             continue;
2031         }
2033         SPItem *unlink = sp_use_unlink(SP_USE(use));
2034         unlinked = true;
2035         // Add ungrouped items to the new selection.
2036         new_select = g_slist_prepend(new_select, unlink);
2037     }
2039     if (new_select) { // set new selection
2040         selection->clear();
2041         selection->setList(new_select);
2042         g_slist_free(new_select);
2043     }
2044     if (!unlinked) {
2045         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2046     }
2048     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2049                      _("Unlink clone"));
2052 void
2053 sp_select_clone_original()
2055     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2056     if (desktop == NULL)
2057         return;
2059     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2061     SPItem *item = selection->singleItem();
2063     const gchar *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.");
2065     // Check if other than two objects are selected
2066     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2067         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2068         return;
2069     }
2071     SPItem *original = NULL;
2072     if (SP_IS_USE(item)) {
2073         original = sp_use_get_original (SP_USE(item));
2074     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2075         original = sp_offset_get_source (SP_OFFSET(item));
2076     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2077         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2078     } else if (SP_IS_FLOWTEXT(item)) {
2079         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2080     } else { // it's an object that we don't know what to do with
2081         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2082         return;
2083     }
2085     if (!original) {
2086         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2087         return;
2088     }
2090     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2091         if (SP_IS_DEFS (o)) {
2092             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2093             return;
2094         }
2095     }
2097     if (original) {
2098         selection->clear();
2099         selection->set(original);
2100         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2101             scroll_to_show_item(desktop, original);
2102         }
2103     }
2106 void
2107 sp_selection_tile(bool apply)
2109     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2110     if (desktop == NULL)
2111         return;
2113     SPDocument *document = sp_desktop_document(desktop);
2115     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2117     // check if something is selected
2118     if (selection->isEmpty()) {
2119         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2120         return;
2121     }
2123     sp_document_ensure_up_to_date(document);
2124     NR::Rect r = selection->bounds();
2125     if (r.isEmpty()) {
2126         return;
2127     }
2129     // calculate the transform to be applied to objects to move them to 0,0
2130     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2131     move_p[NR::Y] = -move_p[NR::Y];
2132     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2134     GSList *items = g_slist_copy((GSList *) selection->itemList());
2136     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2138     // bottommost object, after sorting
2139     SPObject *parent = SP_OBJECT_PARENT (items->data);
2141     // remember the position of the first item
2142     gint pos = SP_OBJECT_REPR (items->data)->position();
2144     // create a list of duplicates
2145     GSList *repr_copies = NULL;
2146     for (GSList *i = items; i != NULL; i = i->next) {
2147         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2148         repr_copies = g_slist_prepend (repr_copies, dup);
2149     }
2151     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2153     if (apply) {
2154         // delete objects so that their clones don't get alerted; this object will be restored shortly
2155         for (GSList *i = items; i != NULL; i = i->next) {
2156             SPObject *item = SP_OBJECT (i->data);
2157             item->deleteObject (false);
2158         }
2159     }
2161     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2162     // without disturbing clones.
2163     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2164     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2165     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2167     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2168                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))), move);
2170     // restore compensation setting
2171     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2173     if (apply) {
2174         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2175         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2176         sp_repr_set_svg_double(rect, "width", bounds.extent(NR::X));
2177         sp_repr_set_svg_double(rect, "height", bounds.extent(NR::Y));
2178         sp_repr_set_svg_double(rect, "x", bounds.min()[NR::X]);
2179         sp_repr_set_svg_double(rect, "y", bounds.min()[NR::Y]);
2181         // restore parent and position
2182         SP_OBJECT_REPR (parent)->appendChild(rect);
2183         rect->setPosition(pos > 0 ? pos : 0);
2184         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2186         Inkscape::GC::release(rect);
2188         selection->clear();
2189         selection->set(rectangle);
2190     }
2192     g_slist_free (items);
2194     sp_document_done (document, SP_VERB_EDIT_TILE, 
2195                       _("Objects to pattern"));
2198 void
2199 sp_selection_untile()
2201     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2202     if (desktop == NULL)
2203         return;
2205     SPDocument *document = sp_desktop_document(desktop);
2207     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2209     // check if something is selected
2210     if (selection->isEmpty()) {
2211         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2212         return;
2213     }
2215     GSList *new_select = NULL;
2217     bool did = false;
2219     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2220          items != NULL;
2221          items = items->next) {
2223         SPItem *item = (SPItem *) items->data;
2225         SPStyle *style = SP_OBJECT_STYLE (item);
2227         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2228             continue;
2230         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2232         if (!SP_IS_PATTERN(server))
2233             continue;
2235         did = true;
2237         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2239         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2240         pat_transform *= item->transform;
2242         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2243             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2244             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2246            // FIXME: relink clones to the new canvas objects
2247            // use SPObject::setid when mental finishes it to steal ids of
2249             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2250             sp_document_ensure_up_to_date (document);
2252             NR::Matrix transform( i->transform * pat_transform );
2253             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2255             new_select = g_slist_prepend(new_select, i);
2256         }
2258         SPCSSAttr *css = sp_repr_css_attr_new ();
2259         sp_repr_css_set_property (css, "fill", "none");
2260         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2261     }
2263     if (!did) {
2264         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2265     } else {
2266         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2267                          _("Pattern to objects"));
2268         selection->setList(new_select);
2269     }
2272 void
2273 sp_selection_create_bitmap_copy ()
2275     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2276     if (desktop == NULL)
2277         return;
2279     SPDocument *document = sp_desktop_document(desktop);
2281     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2283     // check if something is selected
2284     if (selection->isEmpty()) {
2285         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2286         return;
2287     }
2289     // Get the bounding box of the selection
2290     NRRect bbox;
2291     sp_document_ensure_up_to_date (document);
2292     selection->bounds(&bbox);
2293     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2294         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2295     }
2297     // List of the items to show; all others will be hidden
2298     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2300     // Sort items so that the topmost comes last
2301     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2303     // Generate a random value from the current time (you may create bitmap from the same object(s)
2304     // multiple times, and this is done so that they don't clash)
2305     GTimeVal cu;
2306     g_get_current_time (&cu);
2307     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2309     // Create the filename
2310     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2311     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2312     // digits, and a few other chars, with "_"
2313     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2314     // Build the complete path by adding document->base if set
2315     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2317     //g_print ("%s\n", filepath);
2319     // Remember parent and z-order of the topmost one
2320     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2321     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2322     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2324     // Calculate resolution
2325     double res;
2326     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2327     if (0 < prefs_res) {
2328         // If it's given explicitly in prefs, take it
2329         res = prefs_res;
2330     } else {
2331         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2332         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2333         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2334     }
2336     // The width and height of the bitmap in pixels
2337     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2338     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2340     // Find out if we have to run a filter
2341     const gchar *run = NULL;
2342     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2343     if (filter) {
2344         // filter command is given;
2345         // see if we have a parameter to pass to it
2346         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2347         if (param1) {
2348             if (param1[strlen(param1) - 1] == '%') {
2349                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2350                 gchar p1[256];
2351                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2352                 // the first param is always the image filename, the second is param1
2353                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2354             } else {
2355                 // otherwise pass the param1 unchanged
2356                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2357             }
2358         } else {
2359             // run without extra parameter
2360             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2361         }
2362     }
2364     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2365     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2366     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2368     // Do the export
2369     sp_export_png_file(document, filepath,
2370                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2371                    width, height, res, res,
2372                    (guint32) 0xffffff00,
2373                    NULL, NULL,
2374                    true,  /*bool force_overwrite,*/
2375                    items);
2377     g_slist_free (items);
2379     // Run filter, if any
2380     if (run) {
2381         g_print ("Running external filter: %s\n", run);
2382         system (run);
2383     }
2385     // Import the image back
2386     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2387     if (pb) {
2388         // Create the repr for the image
2389         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2390         repr->setAttribute("xlink:href", filename);
2391         repr->setAttribute("sodipodi:absref", filepath);
2392         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2393         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2395         // Write transform
2396         gchar c[256];
2397         if (sp_svg_transform_write(c, 256, t)) {
2398             repr->setAttribute("transform", c);
2399         }
2401         // add the new repr to the parent
2402         parent->appendChild(repr);
2404         // move to the saved position
2405         repr->setPosition(pos > 0 ? pos + 1 : 1);
2407         // Set selection to the new image
2408         selection->clear();
2409         selection->add(repr);
2411         // Clean up
2412         Inkscape::GC::release(repr);
2413         gdk_pixbuf_unref (pb);
2415         // Complete undoable transaction
2416         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2417                           _("Create bitmap"));
2418     }
2420     g_free (filename);
2421     g_free (filepath);
2424 /**
2425  * \brief sp_selection_set_mask
2426  *
2427  * This function creates a mask or clipPath from selection
2428  * Two different modes:
2429  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2430  *       and is applied to current layer
2431  *  otherwise, topmost object is used as mask for other objects
2432  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2433  * 
2434  */
2435 void
2436 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2438     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2439     if (desktop == NULL)
2440         return;
2442     SPDocument *document = sp_desktop_document(desktop);
2443     
2444     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2446     // check if something is selected
2447     bool is_empty = selection->isEmpty();
2448     if ( apply_to_layer && is_empty) {
2449         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2450         return;
2451     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2452         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2453         return;
2454     }
2455     
2456     sp_document_ensure_up_to_date(document);
2458     GSList *items = g_slist_copy((GSList *) selection->itemList());
2459     
2460     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2462     // create a list of duplicates
2463     GSList *mask_items = NULL;
2464     GSList *apply_to_items = NULL;
2465     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2466     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2467     
2468     if (apply_to_layer) {
2469         // all selected items are used for mask, which is applied to a layer
2470         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2472         for (GSList *i = items; i != NULL; i = i->next) {
2473             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2474             mask_items = g_slist_prepend (mask_items, dup);
2476             if (remove_original) {
2477                 SPObject *item = SP_OBJECT (i->data);
2478                 item->deleteObject (false);
2479             }
2480         }
2481     } else if (!topmost) {
2482         // topmost item is used as a mask, which is applied to other items in a selection
2483         GSList *i = items;
2484         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2485         mask_items = g_slist_prepend (mask_items, dup);
2487         if (remove_original) {
2488             SPObject *item = SP_OBJECT (i->data);
2489             item->deleteObject (false);
2490         }
2491         
2492         for (i = i->next; i != NULL; i = i->next) {
2493             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2494         }
2495     } else {
2496         GSList *i = NULL;
2497         for (i = items; NULL != i->next; i = i->next) {
2498             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2499         }
2501         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2502         mask_items = g_slist_prepend (mask_items, dup);
2504         if (remove_original) {
2505             SPObject *item = SP_OBJECT (i->data);
2506             item->deleteObject (false);
2507         }
2508     }
2509     
2510     g_slist_free (items);
2511     items = NULL;
2512             
2513     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2514     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2515         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2516         // inverted object transform should be applied to a mask object,
2517         // as mask is calculated in user space (after applying transform)
2518         NR::Matrix maskTransform (item->transform.inverse());
2520         GSList *mask_items_dup = NULL;
2521         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2522             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2523             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2524         }
2526         const gchar *mask_id = NULL;
2527         if (apply_clip_path) {
2528             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2529         } else {
2530             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2531         }
2533         g_slist_free (mask_items_dup);
2534         mask_items_dup = NULL;
2536         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2537     }
2539     g_slist_free (mask_items);
2540     g_slist_free (apply_to_items);
2542     if (apply_clip_path) 
2543         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2544     else 
2545         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2548 void sp_selection_unset_mask(bool apply_clip_path) {
2549     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2550     if (desktop == NULL)
2551         return;
2552     
2553     SPDocument *document = sp_desktop_document(desktop);    
2554     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2556     // check if something is selected
2557     if (selection->isEmpty()) {
2558         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2559         return;
2560     }
2561     
2562     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2563     sp_document_ensure_up_to_date(document);
2565     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2566     std::map<SPObject*,SPItem*> referenced_objects;
2567     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2568         if (remove_original) {
2569             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2570             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2571             Inkscape::URIReference *uri_ref = NULL;
2572         
2573             if (apply_clip_path) {
2574                 uri_ref = item->clip_ref;
2575             } else {
2576                 uri_ref = item->mask_ref;
2577             }
2579             // collect distinct mask object (and associate with item to apply transform)
2580             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2581                 referenced_objects[uri_ref->getObject()] = item;
2582             }
2583         }
2585         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2586     }
2588     // restore mask objects into a document
2589     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2590         SPObject *obj = (*it).first;
2591         GSList *items_to_move = NULL;
2592         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2593             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2594             items_to_move = g_slist_prepend (items_to_move, copy);
2595         }
2597         if (!obj->isReferenced()) {
2598             // delete from defs if no other object references this mask
2599             obj->deleteObject(false);
2600         }
2602         // remember parent and position of the item to which the clippath/mask was applied
2603         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2604         gint pos = SP_OBJECT_REPR((*it).second)->position();
2606         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2607             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2609             // insert into parent, restore pos
2610             parent->appendChild(repr);
2611             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2613             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2614             selection->add(repr);
2616             // transform mask, so it is moved the same spot where mask was applied
2617             NR::Matrix transform (mask_item->transform);
2618             transform *= (*it).second->transform;
2619             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2620         }
2622         g_slist_free (items_to_move);
2623     }
2625     if (apply_clip_path) 
2626         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2627     else 
2628         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2631 void fit_canvas_to_selection(SPDesktop *desktop) {
2632     g_return_if_fail(desktop != NULL);
2633     SPDocument *doc = sp_desktop_document(desktop);
2635     g_return_if_fail(doc != NULL);
2636     g_return_if_fail(desktop->selection != NULL);
2637     g_return_if_fail(!desktop->selection->isEmpty());
2638     NRRect bbox = {0,0,0,0};
2640     desktop->selection->bounds(&bbox);
2641     if (!empty(bbox)) {
2642         doc->fitToRect(bbox);
2643     }
2644 };
2646 void fit_canvas_to_drawing(SPDocument *doc) {
2647     g_return_if_fail(doc != NULL);
2648     NRRect bbox = {0,0,0,0};
2650     sp_document_ensure_up_to_date (doc);
2651     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2653     if (!empty(bbox)) {
2654         doc->fitToRect(bbox);
2655     }
2656 };
2658 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2659     g_return_if_fail(desktop != NULL);
2660     SPDocument *doc = sp_desktop_document(desktop);
2662     g_return_if_fail(doc != NULL);
2663     g_return_if_fail(desktop->selection != NULL);
2665     if (desktop->selection->isEmpty()) {
2666         fit_canvas_to_drawing(doc);
2667     } else {
2668         fit_canvas_to_selection(desktop);
2669     }
2671     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2672                      _("Fit page to selection"));
2673 };
2675 /*
2676   Local Variables:
2677   mode:c++
2678   c-file-style:"stroustrup"
2679   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2680   indent-tabs-mode:nil
2681   fill-column:99
2682   End:
2683 */
2684 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :