Code

enable copy/paste of objects with filters
[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 "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include "helper/units.h"
73 #include "sp-item.h"
74 using NR::X;
75 using NR::Y;
77 #include "selection-chemistry.h"
79 /* fixme: find a better place */
80 GSList *clipboard = NULL;
81 GSList *defs_clipboard = NULL;
82 SPCSSAttr *style_clipboard = NULL;
83 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
85 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
87 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
88 {
89     Inkscape::XML::Node *copy = repr->duplicate();
91     // copy complete inherited style
92     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
93     sp_repr_css_set(copy, css, "style");
94     sp_repr_css_attr_unref(css);
96     // write the complete accummulated transform passed to us
97     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
98     gchar affinestr[80];
99     if (sp_svg_transform_write(affinestr, 79, full_t)) {
100         copy->setAttribute("transform", affinestr);
101     } else {
102         copy->setAttribute("transform", NULL);
103     }
105     *clip = g_slist_prepend(*clip, copy);
108 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
111     // Copy stuff referenced by all items to defs_clip:
112     if (defs_clip) {
113         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
114             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
115         }
116         *defs_clip = g_slist_reverse(*defs_clip);
117     }
119     // Store style:
120     if (style_clip) {
121         SPItem *item = SP_ITEM (items->data); // take from the first selected item
122         *style_clip = take_style_from_item (item);
123     }
125     if (clip) {
126         // Sort items:
127         GSList *sorted_items = g_slist_copy ((GSList *) items);
128         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
130         // Copy item reprs:
131         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
132             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
133         }
135         *clip = g_slist_reverse(*clip);
136         g_slist_free ((GSList *) sorted_items);
137     }
140 /**
141 Add gradients/patterns/markers referenced by copied objects to defs
142 */
143 void
144 paste_defs (GSList **defs_clip, SPDocument *doc)
146     if (!defs_clip)
147         return;
149     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
150         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
151         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
152         gchar const *id = repr->attribute("id");
153         if (!id || !doc->getObjectById(id)) {
154             Inkscape::XML::Node *copy = repr->duplicate();
155             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
156             Inkscape::GC::release(copy);
157         }
158     }
161 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
163     paste_defs (defs_clip, document);
165     GSList *copied = NULL;
166     // add objects to document
167     for (GSList *l = *clip; l != NULL; l = l->next) {
168         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
169         Inkscape::XML::Node *copy = repr->duplicate();
171         // premultiply the item transform by the accumulated parent transform in the paste layer
172         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
173         if (!local.test_identity()) {
174             gchar const *t_str = copy->attribute("transform");
175             NR::Matrix item_t (NR::identity());
176             if (t_str)
177                 sp_svg_transform_read(t_str, &item_t);
178             item_t *= local.inverse();
179             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
180             gchar affinestr[80];
181             if (sp_svg_transform_write(affinestr, 79, item_t)) {
182                 copy->setAttribute("transform", affinestr);
183             } else {
184                 copy->setAttribute("transform", NULL);
185             }
186         }
188         parent->appendChildRepr(copy);
189         copied = g_slist_prepend(copied, copy);
190         Inkscape::GC::release(copy);
191     }
192     return copied;
195 void sp_selection_delete_impl(const GSList *items)
197     for (const GSList *i = items ; i ; i = i->next ) {
198         sp_object_ref((SPObject *)i->data, NULL);
199     }
200     for (const GSList *i = items; i != NULL; i = i->next) {
201         SPItem *item = (SPItem *) i->data;
202         SP_OBJECT(item)->deleteObject();
203         sp_object_unref((SPObject *)item, NULL);
204     }
208 void sp_selection_delete()
210     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
211     if (desktop == NULL) {
212         return;
213     }
215     if (tools_isactive (desktop, TOOLS_TEXT))
216         if (sp_text_delete_selection(desktop->event_context)) {
217             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
218                              _("Delete text"));
219             return;
220         }
222     Inkscape::Selection *selection = sp_desktop_selection(desktop);
224     // check if something is selected
225     if (selection->isEmpty()) {
226         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
227         return;
228     }
230     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
231     selection->clear();
232     sp_selection_delete_impl (selected);
233     g_slist_free ((GSList *) selected);
235     /* a tool may have set up private information in it's selection context
236      * that depends on desktop items.  I think the only sane way to deal with
237      * this currently is to reset the current tool, which will reset it's
238      * associated selection context.  For example: deleting an object
239      * while moving it around the canvas.
240      */
241     tools_switch ( desktop, tools_active ( desktop ) );
243     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
244                      _("Delete"));
247 /* fixme: sequencing */
248 void sp_selection_duplicate()
250     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
251     if (desktop == NULL)
252         return;
254     Inkscape::Selection *selection = sp_desktop_selection(desktop);
256     // check if something is selected
257     if (selection->isEmpty()) {
258         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
259         return;
260     }
262     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
264     selection->clear();
266     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
267     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
269     GSList *newsel = NULL;
271     while (reprs) {
272         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
273         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
275         parent->appendChild(copy);
277         newsel = g_slist_prepend(newsel, copy);
278         reprs = g_slist_remove(reprs, reprs->data);
279         Inkscape::GC::release(copy);
280     }
282     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
283                      _("Duplicate"));
285     selection->setReprList(newsel);
287     g_slist_free(newsel);
290 void sp_edit_clear_all()
292     SPDesktop *dt = SP_ACTIVE_DESKTOP;
293     if (!dt)
294         return;
296     SPDocument *doc = sp_desktop_document(dt);
297     sp_desktop_selection(dt)->clear();
299     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
300     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
302     while (items) {
303         SP_OBJECT (items->data)->deleteObject();
304         items = g_slist_remove(items, items->data);
305     }
307     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
308                      _("Delete all"));
311 GSList *
312 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
314     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
315         if (SP_IS_ITEM(child) &&
316             !desktop->isLayer(SP_ITEM(child)) &&
317             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
318             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
319             (!exclude || !g_slist_find ((GSList *) exclude, child))
320             )
321         {
322             list = g_slist_prepend (list, SP_ITEM(child));
323         }
325         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
326             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
327         }
328     }
330     return list;
333 void sp_edit_select_all_full (bool force_all_layers, bool invert)
335     SPDesktop *dt = SP_ACTIVE_DESKTOP;
336     if (!dt)
337         return;
339     Inkscape::Selection *selection = sp_desktop_selection(dt);
341     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
343     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
344     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
345     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
347     GSList *items = NULL;
349     const GSList *exclude = NULL;
350     if (invert) {
351         exclude = selection->itemList();
352     }
354     if (force_all_layers)
355         inlayer = PREFS_SELECTION_ALL;
357     switch (inlayer) {
358         case PREFS_SELECTION_LAYER: {
359         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
360              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
361         return;
363         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
365         for (GSList *i = all_items; i; i = i->next) {
366             SPItem *item = SP_ITEM (i->data);
368             if (item && (!onlysensitive || !item->isLocked())) {
369                 if (!onlyvisible || !dt->itemIsHidden(item)) {
370                     if (!dt->isLayer(item)) {
371                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
372                             items = g_slist_prepend (items, item); // leave it in the list
373                         }
374                     }
375                 }
376             }
377         }
379         g_slist_free (all_items);
380             break;
381         }
382         case PREFS_SELECTION_LAYER_RECURSIVE: {
383             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
384             break;
385         }
386         default: {
387         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
388             break;
389     }
390     }
392     selection->setList (items);
394     if (items) {
395         g_slist_free (items);
396     }
399 void sp_edit_select_all ()
401     sp_edit_select_all_full (false, false);
404 void sp_edit_select_all_in_all_layers ()
406     sp_edit_select_all_full (true, false);
409 void sp_edit_invert ()
411     sp_edit_select_all_full (false, true);
414 void sp_edit_invert_in_all_layers ()
416     sp_edit_select_all_full (true, true);
419 void sp_selection_group()
421     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
422     if (desktop == NULL)
423         return;
425     SPDocument *document = sp_desktop_document (desktop);
427     Inkscape::Selection *selection = sp_desktop_selection(desktop);
429     // Check if something is selected.
430     if (selection->isEmpty()) {
431         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
432         return;
433     }
435     GSList const *l = (GSList *) selection->reprList();
437     // Check if at least two objects are selected.
438     if (l->next == NULL) {
439         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
440         return;
441     }
443     GSList *p = g_slist_copy((GSList *) l);
445     selection->clear();
447     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
449     // Remember the position and parent of the topmost object.
450     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
451     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
453     Inkscape::XML::Node *group = sp_repr_new("svg:g");
455     while (p) {
456         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
458         if (current->parent() == topmost_parent) {
459             Inkscape::XML::Node *spnew = current->duplicate();
460             sp_repr_unparent(current);
461             group->appendChild(spnew);
462             Inkscape::GC::release(spnew);
463             topmost --; // only reduce count for those items deleted from topmost_parent
464         } else { // move it to topmost_parent first
465                 GSList *temp_clip = NULL;
467                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
468                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
469                 gchar const *t_str = current->attribute("transform");
470                 NR::Matrix item_t (NR::identity());
471                 if (t_str)
472                     sp_svg_transform_read(t_str, &item_t);
473                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
474                 //FIXME: when moving both clone and original from a transformed group (either by
475                 //grouping into another parent, or by cut/paste) the transform from the original's
476                 //parent becomes embedded into original itself, and this affects its clones. Fix
477                 //this by remembering the transform diffs we write to each item into an array and
478                 //then, if this is clone, looking up its original in that array and pre-multiplying
479                 //it by the inverse of that original's transform diff.
481                 sp_selection_copy_one (current, item_t, &temp_clip);
482                 sp_repr_unparent(current);
484                 // paste into topmost_parent (temporarily)
485                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
486                 if (temp_clip) g_slist_free (temp_clip);
487                 if (copied) { // if success,
488                     // take pasted object (now in topmost_parent)
489                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
490                     // make a copy
491                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
492                     // remove pasted
493                     sp_repr_unparent(in_topmost);
494                     // put its copy into group
495                     group->appendChild(spnew);
496                     Inkscape::GC::release(spnew);
497                     g_slist_free (copied);
498                 }
499         }
500         p = g_slist_remove(p, current);
501     }
503     // Add the new group to the topmost members' parent
504     topmost_parent->appendChild(group);
506     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
507     group->setPosition(topmost + 1);
509     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
510                      _("Group"));
512     selection->set(group);
513     Inkscape::GC::release(group);
516 void sp_selection_ungroup()
518     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
519     if (desktop == NULL)
520         return;
522     Inkscape::Selection *selection = sp_desktop_selection(desktop);
524     if (selection->isEmpty()) {
525         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
526         return;
527     }
529     GSList *items = g_slist_copy((GSList *) selection->itemList());
530     selection->clear();
532     // Get a copy of current selection.
533     GSList *new_select = NULL;
534     bool ungrouped = false;
535     for (GSList *i = items;
536          i != NULL;
537          i = i->next)
538     {
539         SPItem *group = (SPItem *) i->data;
541         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
542         if (!SP_IS_OBJECT(group)) {
543             continue;
544         }
546         /* We do not allow ungrouping <svg> etc. (lauris) */
547         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
548             // keep the non-group item in the new selection
549             selection->add(group);
550             continue;
551         }
553         GSList *children = NULL;
554         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
555         sp_item_group_ungroup(SP_GROUP(group), &children, false);
556         ungrouped = true;
557         // Add ungrouped items to the new selection.
558         new_select = g_slist_concat(new_select, children);
559     }
561     if (new_select) { // Set new selection.
562         selection->addList(new_select);
563         g_slist_free(new_select);
564     }
565     if (!ungrouped) {
566         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
567     }
569     g_slist_free(items);
571     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
572                      _("Ungroup"));
575 static SPGroup *
576 sp_item_list_common_parent_group(const GSList *items)
578     if (!items) {
579         return NULL;
580     }
581     SPObject *parent = SP_OBJECT_PARENT(items->data);
582     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
583     if (!SP_IS_GROUP(parent)) {
584         return NULL;
585     }
586     for (items = items->next; items; items = items->next) {
587         if (SP_OBJECT_PARENT(items->data) != parent) {
588             return NULL;
589         }
590     }
592     return SP_GROUP(parent);
595 /** Finds out the minimum common bbox of the selected items
596  */
597 NR::Rect
598 enclose_items(const GSList *items)
600     g_assert(items != NULL);
602     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
604     for (GSList *i = items->next; i; i = i->next) {
605         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
606     }
608     return r;
611 SPObject *
612 prev_sibling(SPObject *child)
614     SPObject *parent = SP_OBJECT_PARENT(child);
615     if (!SP_IS_GROUP(parent)) {
616         return NULL;
617     }
618     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
619         if (i->next == child)
620             return i;
621     }
622     return NULL;
625 void
626 sp_selection_raise()
628     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
629     if (!desktop)
630         return;
632     Inkscape::Selection *selection = sp_desktop_selection(desktop);
634     GSList const *items = (GSList *) selection->itemList();
635     if (!items) {
636         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
637         return;
638     }
640     SPGroup const *group = sp_item_list_common_parent_group(items);
641     if (!group) {
642         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
643         return;
644     }
646     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
648     /* construct reverse-ordered list of selected children */
649     GSList *rev = g_slist_copy((GSList *) items);
650     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
652     // find out the common bbox of the selected items
653     NR::Rect selected = enclose_items(items);
655     // for all objects in the selection (starting from top)
656     while (rev) {
657         SPObject *child = SP_OBJECT(rev->data);
658         // for each selected object, find the next sibling
659         for (SPObject *newref = child->next; newref; newref = newref->next) {
660             // if the sibling is an item AND overlaps our selection,
661             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
662                 // AND if it's not one of our selected objects,
663                 if (!g_slist_find((GSList *) items, newref)) {
664                     // move the selected object after that sibling
665                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
666                 }
667                 break;
668             }
669         }
670         rev = g_slist_remove(rev, child);
671     }
673     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
674                      _("Raise"));
677 void sp_selection_raise_to_top()
679     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
680     if (desktop == NULL)
681         return;
683     SPDocument *document = sp_desktop_document(desktop);
684     Inkscape::Selection *selection = sp_desktop_selection(desktop);
686     if (selection->isEmpty()) {
687         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
688         return;
689     }
691     GSList const *items = (GSList *) selection->itemList();
693     SPGroup const *group = sp_item_list_common_parent_group(items);
694     if (!group) {
695         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
696         return;
697     }
699     GSList *rl = g_slist_copy((GSList *) selection->reprList());
700     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
702     for (GSList *l = rl; l != NULL; l = l->next) {
703         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
704         repr->setPosition(-1);
705     }
707     g_slist_free(rl);
709     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
710                      _("Raise to top"));
713 void
714 sp_selection_lower()
716     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
717     if (desktop == NULL)
718         return;
720     Inkscape::Selection *selection = sp_desktop_selection(desktop);
722     GSList const *items = (GSList *) selection->itemList();
723     if (!items) {
724         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
725         return;
726     }
728     SPGroup const *group = sp_item_list_common_parent_group(items);
729     if (!group) {
730         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
731         return;
732     }
734     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
736     // find out the common bbox of the selected items
737     NR::Rect selected = enclose_items(items);
739     /* construct direct-ordered list of selected children */
740     GSList *rev = g_slist_copy((GSList *) items);
741     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
742     rev = g_slist_reverse(rev);
744     // for all objects in the selection (starting from top)
745     while (rev) {
746         SPObject *child = SP_OBJECT(rev->data);
747         // for each selected object, find the prev sibling
748         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
749             // if the sibling is an item AND overlaps our selection,
750             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
751                 // AND if it's not one of our selected objects,
752                 if (!g_slist_find((GSList *) items, newref)) {
753                     // move the selected object before that sibling
754                     SPObject *put_after = prev_sibling(newref);
755                     if (put_after)
756                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
757                     else
758                         SP_OBJECT_REPR(child)->setPosition(0);
759                 }
760                 break;
761             }
762         }
763         rev = g_slist_remove(rev, child);
764     }
766     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
767                      _("Lower"));
771 void sp_selection_lower_to_bottom()
773     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
774     if (desktop == NULL)
775         return;
777     SPDocument *document = sp_desktop_document(desktop);
778     Inkscape::Selection *selection = sp_desktop_selection(desktop);
780     if (selection->isEmpty()) {
781         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
782         return;
783     }
785     GSList const *items = (GSList *) selection->itemList();
787     SPGroup const *group = sp_item_list_common_parent_group(items);
788     if (!group) {
789         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
790         return;
791     }
793     GSList *rl;
794     rl = g_slist_copy((GSList *) selection->reprList());
795     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
796     rl = g_slist_reverse(rl);
798     for (GSList *l = rl; l != NULL; l = l->next) {
799         gint minpos;
800         SPObject *pp, *pc;
801         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
802         pp = document->getObjectByRepr(sp_repr_parent(repr));
803         minpos = 0;
804         g_assert(SP_IS_GROUP(pp));
805         pc = sp_object_first_child(pp);
806         while (!SP_IS_ITEM(pc)) {
807             minpos += 1;
808             pc = pc->next;
809         }
810         repr->setPosition(minpos);
811     }
813     g_slist_free(rl);
815     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
816                      _("Lower to bottom"));
819 void
820 sp_undo(SPDesktop *desktop, SPDocument *)
822         if (!sp_document_undo(sp_desktop_document(desktop)))
823             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
826 void
827 sp_redo(SPDesktop *desktop, SPDocument *)
829         if (!sp_document_redo(sp_desktop_document(desktop)))
830             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
833 void sp_selection_cut()
835     sp_selection_copy();
836     sp_selection_delete();
839 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
841     SPGradient *ref = gradient;
843     while (ref) {
844         // climb up the refs, copying each one in the chain
845         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
846         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
848         ref = ref->ref->getObject();
849     }
852 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
854     SPPattern *ref = pattern;
856     while (ref) {
857         // climb up the refs, copying each one in the chain
858         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
859         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
861         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
862         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
863             if (!SP_IS_ITEM (child))
864                 continue;
865             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
866         }
868         ref = ref->ref->getObject();
869     }
872 void sp_copy_single (GSList **defs_clip, SPObject *thing)
874     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
875     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
879 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
881     SPItem *path = sp_textpath_get_path_item (tp);
882     if (!path)
883         return;
884     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
885         return;
886     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
887     *defs_clip = g_slist_prepend (*defs_clip, repr);
890 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
892     SPStyle *style = SP_OBJECT_STYLE (item);
894     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
895         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
896         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
897             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
898         if (SP_IS_PATTERN (server))
899             sp_copy_pattern (defs_clip, SP_PATTERN(server));
900     }
902     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
903         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
904         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
905             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
906         if (SP_IS_PATTERN (server))
907             sp_copy_pattern (defs_clip, SP_PATTERN(server));
908     }
910     if (SP_IS_SHAPE (item)) {
911         SPShape *shape = SP_SHAPE (item);
912         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
913             if (shape->marker[i]) {
914                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
915             }
916         }
917     }
919     if (SP_IS_TEXT_TEXTPATH (item)) {
920         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
921     }
923     if (item->clip_ref->getObject()) {
924         sp_copy_single (defs_clip, item->clip_ref->getObject());
925     }
927     if (item->mask_ref->getObject()) {
928         SPObject *mask = item->mask_ref->getObject();
929         sp_copy_single (defs_clip, mask);
930         // recurse into the mask for its gradients etc.
931         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
932             if (SP_IS_ITEM(o))
933                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
934         }
935     }
937     if (style->filter.filter) {
938         SPObject *filter = style->filter.filter;
939         if (SP_IS_FILTER(filter)) {
940             sp_copy_single (defs_clip, filter);
941         }
942     }
944     // recurse
945     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
946         if (SP_IS_ITEM(o))
947             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
948     }
951 /**
952  * \pre item != NULL
953  */
954 SPCSSAttr *
955 take_style_from_item (SPItem *item)
957     // write the complete cascaded style, context-free
958     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
959     if (css == NULL)
960         return NULL;
962     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
963         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
964         // if this is a text with exactly one tspan child, merge the style of that tspan as well
965         // If this is a group, merge the style of its topmost (last) child with style
966         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
967             if (SP_OBJECT_STYLE (last_element) != NULL) {
968                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
969                 if (temp) {
970                     sp_repr_css_merge (css, temp);
971                     sp_repr_css_attr_unref (temp);
972                 }
973                 break;
974             }
975         }
976     }
977     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
978         // do not copy text properties from non-text objects, it's confusing
979         css = sp_css_attr_unset_text (css);
980     }
982     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
983     double ex = NR::expansion(sp_item_i2doc_affine(item));
984     if (ex != 1.0) {
985         css = sp_css_attr_scale (css, ex);
986     }
988     return css;
992 void sp_selection_copy()
994     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
995     if (desktop == NULL)
996         return;
998     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1000     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1001         sp_dropper_context_copy(desktop->event_context);
1002         return; // copied color under cursor, nothing else to do
1003     }
1005     // check if something is selected
1006     if (selection->isEmpty()) {
1007         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1008         return;
1009     }
1011     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1013     // 0. Copy text to system clipboard
1014     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1015     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1016     Glib::ustring text;
1017     if (tools_isactive (desktop, TOOLS_TEXT)) {
1018         text = sp_text_get_selected_text(desktop->event_context);
1019     }
1021     if (text.empty()) {
1022         guint texts = 0;
1023         for (GSList *i = (GSList *) items; i; i = i->next) {
1024             SPItem *item = SP_ITEM (i->data);
1025             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1026                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1027                     text += " ";
1028                 gchar *this_text = sp_te_get_string_multiline (item);
1029                 if (this_text) {
1030                     text += this_text;
1031                     g_free(this_text);
1032                 }
1033                 texts++;
1034             }
1035         }
1036     }
1037     if (!text.empty()) {
1038         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1039         refClipboard->set_text(text);
1040     }
1042     // clear old defs clipboard
1043     while (defs_clipboard) {
1044         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1045         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1046     }
1048     // clear style clipboard
1049     if (style_clipboard) {
1050         sp_repr_css_attr_unref (style_clipboard);
1051         style_clipboard = NULL;
1052     }
1054     //clear main clipboard
1055     while (clipboard) {
1056         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1057         clipboard = g_slist_remove(clipboard, clipboard->data);
1058     }
1060     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1062     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1063         SPStyle *const query = sp_style_new();
1064         if (sp_desktop_query_style_all (desktop, query)) {
1065             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1066             if (css != NULL) {
1067                 // clear style clipboard
1068                 if (style_clipboard) {
1069                     sp_repr_css_attr_unref (style_clipboard);
1070                     style_clipboard = NULL;
1071                 }
1072                 //sp_repr_css_print (css);
1073                 style_clipboard = css;
1074             }
1075         }
1076         g_free (query);
1077     }
1079     size_clipboard = selection->bounds();
1081     g_slist_free ((GSList *) items);
1084 void sp_selection_paste(bool in_place)
1086     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1088     if (desktop == NULL) {
1089         return;
1090     }
1092     SPDocument *document = sp_desktop_document(desktop);
1094     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1095         return;
1096     }
1098     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1100     if (tools_isactive (desktop, TOOLS_TEXT)) {
1101         if (sp_text_paste_inline(desktop->event_context))
1102             return; // pasted from system clipboard into text, nothing else to do
1103     }
1105     // check if something is in the clipboard
1106     if (clipboard == NULL) {
1107         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1108         return;
1109     }
1111     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1112     // add pasted objects to selection
1113     selection->setReprList((GSList const *) copied);
1114     g_slist_free (copied);
1116     if (!in_place) {
1117         sp_document_ensure_up_to_date(document);
1119         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1121         /* Snap the offset of the new item(s) to the grid */
1122         /* FIXME: this gridsnap fiddling is a hack. */
1123         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1124         gdouble const curr_gridsnap = s.getDistance();
1125         s.setDistance(NR_HUGE);
1126         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1127         s.setDistance(curr_gridsnap);
1128         sp_selection_move_relative(selection, m);
1129     }
1131     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1132                      _("Paste"));
1135 void sp_selection_paste_style()
1137     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1138     if (desktop == NULL) return;
1140     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1142     // check if something is in the clipboard
1143     if (clipboard == NULL) {
1144         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1145         return;
1146     }
1148     // check if something is selected
1149     if (selection->isEmpty()) {
1150         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1151         return;
1152     }
1154     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1156     sp_desktop_set_style (desktop, style_clipboard);
1158     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1159                      _("Paste style"));
1162 void sp_selection_paste_size (bool apply_x, bool apply_y)
1164     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1165     if (desktop == NULL) return;
1167     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1169     // check if something is in the clipboard
1170     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1171         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1172         return;
1173     }
1175     // check if something is selected
1176     if (selection->isEmpty()) {
1177         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1178         return;
1179     }
1181     NR::Rect current = selection->bounds();
1182     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1183         return;
1184     }
1186     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1187     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1189     sp_selection_scale_relative (selection, current.midpoint(), 
1190                                  NR::scale(
1191                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1192                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1194     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1195                      _("Paste size"));
1198 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1200     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1201     if (desktop == NULL) return;
1203     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1205     // check if something is in the clipboard
1206     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1207         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1208         return;
1209     }
1211     // check if something is selected
1212     if (selection->isEmpty()) {
1213         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1214         return;
1215     }
1217     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1218         SPItem *item = SP_ITEM(l->data);
1220         NR::Rect current = sp_item_bbox_desktop(item);
1221         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1222             continue;
1223         }
1225         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1226         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1228         sp_item_scale_rel (item,
1229                                  NR::scale(
1230                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1231                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1233     }
1235     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1236                      _("Paste size separately"));
1239 void sp_selection_to_next_layer ()
1241     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1243     Inkscape::Selection *selection = sp_desktop_selection(dt);
1245     // check if something is selected
1246     if (selection->isEmpty()) {
1247         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1248         return;
1249     }
1251     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1253     bool no_more = false; // Set to true, if no more layers above
1254     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1255     if (next) {
1256         GSList *temp_clip = NULL;
1257         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1258         sp_selection_delete_impl (items);
1259         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1260         GSList *copied;
1261         if(next) {
1262             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1263         } else {
1264             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1265             no_more = true;
1266         }
1267         selection->setReprList((GSList const *) copied);
1268         g_slist_free (copied);
1269         if (temp_clip) g_slist_free (temp_clip);
1270         if (next) dt->setCurrentLayer(next);
1271         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1272                          _("Raise to next layer"));
1273     } else {
1274         no_more = true;
1275     }
1277     if (no_more) {
1278         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1279     }
1281     g_slist_free ((GSList *) items);
1284 void sp_selection_to_prev_layer ()
1286     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1288     Inkscape::Selection *selection = sp_desktop_selection(dt);
1290     // check if something is selected
1291     if (selection->isEmpty()) {
1292         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1293         return;
1294     }
1296     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1298     bool no_more = false; // Set to true, if no more layers below
1299     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1300     if (next) {
1301         GSList *temp_clip = NULL;
1302         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1303         sp_selection_delete_impl (items);
1304         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1305         GSList *copied;
1306         if(next) {
1307             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1308         } else {
1309             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1310             no_more = true;
1311         }
1312         selection->setReprList((GSList const *) copied);
1313         g_slist_free (copied);
1314         if (temp_clip) g_slist_free (temp_clip);
1315         if (next) dt->setCurrentLayer(next);
1316         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1317                          _("Lower to previous layer"));
1318     } else {
1319         no_more = true;
1320     }
1322     if (no_more) {
1323         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1324     }
1326     g_slist_free ((GSList *) items);
1329 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1330 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1331 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1332 that case, items are already in the new position, but the repr is in the old, and this function
1333 then simply updates the repr from item->transform.
1334  */
1335 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1337     if (selection->isEmpty())
1338         return;
1340     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1341         SPItem *item = SP_ITEM(l->data);
1343         NR::Point old_center(0,0);
1344         if (set_i2d && item->isCenterSet())
1345             old_center = item->getCenter();
1347 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1348          At the time of writing, this is the only place to re-enable. */
1349         sp_item_update_cns(*item, selection->desktop());
1350 #endif
1352         // we're moving both a clone and its original
1353         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1354         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)))) ));
1355         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1356         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1357        
1358         // If we're moving a connector, we want to detach it
1359         // from shapes that aren't part of the selection, but
1360         // leave it attached if they are
1361         if (cc_item_is_connector(item)) {
1362             SPItem *attItem[2];
1363             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1364             
1365             for (int n = 0; n < 2; ++n) {
1366                 if (!selection->includes(attItem[n])) {
1367                     sp_conn_end_detach(item, n);
1368                 }
1369             }
1370         }
1371         
1372         // "clones are unmoved when original is moved" preference
1373         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1374         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1375         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1377         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1378         // transform of its original and respond to it itself. Without this, a clone is doubly
1379         // transformed, very unintuitive.
1380       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1381       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1382       // Same for linked offset if we are also moving its source: do not move it.
1383         if (transform_textpath_with_path || transform_offset_with_source) {
1384                 // restore item->transform field from the repr, in case it was changed by seltrans
1385             sp_object_read_attr (SP_OBJECT (item), "transform");
1387         } else if (transform_flowtext_with_frame) {
1388             // apply the inverse of the region's transform to the <use> so that the flow remains
1389             // the same (even though the output itself gets transformed)
1390             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1391                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1392                     continue;
1393                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1394                     if (!SP_IS_USE(use)) continue;
1395                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1396                 }
1397             }
1398         } else if (transform_clone_with_original) {
1399             // We are transforming a clone along with its original. The below matrix juggling is
1400             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1401             // transform and its move compensation are both cancelled out.
1403             // restore item->transform field from the repr, in case it was changed by seltrans
1404             sp_object_read_attr (SP_OBJECT (item), "transform");
1406             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1407             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1408             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1409             NR::Matrix result = t_inv * item->transform * t;
1411             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1412                 // we need to cancel out the move compensation, too
1414                 // find out the clone move, same as in sp_use_move_compensate
1415                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1416                 NR::Matrix clone_move = parent.inverse() * t * parent;
1418                 if (prefs_parallel) {
1419                     NR::Matrix move = result * clone_move * t_inv;
1420                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1422                 } else if (prefs_unmoved) {
1423                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1424                         clone_move = NR::identity();
1425                     NR::Matrix move = result * clone_move;
1426                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1427                 }
1429             } else {
1430                 // just apply the result
1431                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1432             }
1434         } else {
1435             if (set_i2d) {
1436                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1437             }
1438             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1439         }
1441         // if we're moving the actual object, not just updating the repr, we can transform the
1442         // center by the same matrix (only necessary for non-translations)
1443         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1444             item->setCenter(old_center * affine);
1445             SP_OBJECT(item)->updateRepr();
1446         }
1447     }
1450 void sp_selection_remove_transform()
1452     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1453     if (desktop == NULL)
1454         return;
1456     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1458     GSList const *l = (GSList *) selection->reprList();
1459     while (l != NULL) {
1460         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1461         l = l->next;
1462     }
1464     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1465                      _("Remove transform"));
1468 void
1469 sp_selection_scale_absolute(Inkscape::Selection *selection,
1470                             double const x0, double const x1,
1471                             double const y0, double const y1)
1473     if (selection->isEmpty())
1474         return;
1476     NR::Rect const bbox(selection->bounds());
1477     if (bbox.isEmpty()) {
1478         return;
1479     }
1481     NR::translate const p2o(-bbox.min());
1483     NR::scale const newSize(x1 - x0,
1484                             y1 - y0);
1485     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1486     NR::translate const o2n(x0, y0);
1487     NR::Matrix const final( p2o * scale * o2n );
1489     sp_selection_apply_affine(selection, final);
1493 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1495     if (selection->isEmpty())
1496         return;
1498     NR::Rect const bbox(selection->bounds());
1500     if (bbox.isEmpty()) {
1501         return;
1502     }
1504     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1505     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1506          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1507     {
1508         return;
1509     }
1511     NR::translate const n2d(-align);
1512     NR::translate const d2n(align);
1513     NR::Matrix const final( n2d * scale * d2n );
1514     sp_selection_apply_affine(selection, final);
1517 void
1518 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1520     NR::translate const d2n(center);
1521     NR::translate const n2d(-center);
1522     NR::rotate const rotate(rotate_degrees(angle_degrees));
1523     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1524     sp_selection_apply_affine(selection, final);
1527 void
1528 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1530     NR::translate const d2n(align);
1531     NR::translate const n2d(-align);
1532     NR::Matrix const skew(1, dy,
1533                           dx, 1,
1534                           0, 0);
1535     NR::Matrix const final( n2d * skew * d2n );
1536     sp_selection_apply_affine(selection, final);
1539 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1541     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1544 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1546     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1550 /**
1551  * \brief sp_selection_rotate_90
1552  *
1553  * This function rotates selected objects 90 degrees clockwise.
1554  *
1555  */
1557 void sp_selection_rotate_90_cw()
1559     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1561     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1563     if (selection->isEmpty())
1564         return;
1566     GSList const *l = selection->itemList();
1567     NR::rotate const rot_neg_90(NR::Point(0, -1));
1568     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1569         SPItem *item = SP_ITEM(l2->data);
1570         sp_item_rotate_rel(item, rot_neg_90);
1571     }
1573     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1574                      _("Rotate 90&#176; CW"));
1578 /**
1579  * \brief sp_selection_rotate_90_ccw
1580  *
1581  * This function rotates selected objects 90 degrees counter-clockwise.
1582  *
1583  */
1585 void sp_selection_rotate_90_ccw()
1587     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1589     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1591     if (selection->isEmpty())
1592         return;
1594     GSList const *l = selection->itemList();
1595     NR::rotate const rot_neg_90(NR::Point(0, 1));
1596     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1597         SPItem *item = SP_ITEM(l2->data);
1598         sp_item_rotate_rel(item, rot_neg_90);
1599     }
1601     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1602                      _("Rotate 90&#176; CCW"));
1605 void
1606 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1608     if (selection->isEmpty())
1609         return;
1611     NR::Point center = selection->center();
1613     sp_selection_rotate_relative(selection, center, angle_degrees);
1615     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1616                            ( ( angle_degrees > 0 )
1617                              ? "selector:rotate:ccw"
1618                              : "selector:rotate:cw" ), 
1619                            SP_VERB_CONTEXT_SELECT, 
1620                            _("Rotate"));
1623 /**
1624 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1625 */
1626 void
1627 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1629     if (selection->isEmpty())
1630         return;
1632     NR::Rect const bbox(selection->bounds());
1634     NR::Point center = selection->center();
1636     gdouble const zoom = selection->desktop()->current_zoom();
1637     gdouble const zmove = angle / zoom;
1638     gdouble const r = NR::L2(bbox.max() - center);
1640     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1642     sp_selection_rotate_relative(selection, center, zangle);
1644     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1645                            ( (angle > 0)
1646                              ? "selector:rotate:ccw"
1647                              : "selector:rotate:cw" ),
1648                            SP_VERB_CONTEXT_SELECT, 
1649                            _("Rotate by pixels"));
1652 void
1653 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1655     if (selection->isEmpty())
1656         return;
1658     NR::Rect const bbox(selection->bounds());
1659     NR::Point const center(bbox.midpoint());
1660     double const max_len = bbox.maxExtent();
1662     // you can't scale "do nizhe pola" (below zero)
1663     if ( max_len + grow <= 1e-3 ) {
1664         return;
1665     }
1667     double const times = 1.0 + grow / max_len;
1668     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1670     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1671                            ( (grow > 0)
1672                              ? "selector:scale:larger"
1673                              : "selector:scale:smaller" ),
1674                            SP_VERB_CONTEXT_SELECT,
1675                            _("Scale"));
1678 void
1679 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1681     sp_selection_scale(selection,
1682                        grow_pixels / selection->desktop()->current_zoom());
1685 void
1686 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1688     if (selection->isEmpty())
1689         return;
1691     NR::Point const center(selection->bounds().midpoint());
1692     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1693     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1694                      _("Scale by whole factor"));
1697 void
1698 sp_selection_move(gdouble dx, gdouble dy)
1700     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1701     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1702     if (selection->isEmpty()) {
1703         return;
1704     }
1706     sp_selection_move_relative(selection, dx, dy);
1708     if (dx == 0) {
1709         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1710                                _("Move vertically"));
1711     } else if (dy == 0) {
1712         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1713                                _("Move horizontally"));
1714     } else {
1715         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1716                          _("Move"));
1717     }
1720 void
1721 sp_selection_move_screen(gdouble dx, gdouble dy)
1723     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1725     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1726     if (selection->isEmpty()) {
1727         return;
1728     }
1730     // same as sp_selection_move but divide deltas by zoom factor
1731     gdouble const zoom = desktop->current_zoom();
1732     gdouble const zdx = dx / zoom;
1733     gdouble const zdy = dy / zoom;
1734     sp_selection_move_relative(selection, zdx, zdy);
1736     if (dx == 0) {
1737         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1738                                _("Nudge vertically by pixels"));
1739     } else if (dy == 0) {
1740         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1741                                _("Nudge horizontally by pixels"));
1742     } else {
1743         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1744                          _("Move"));
1745     }
1748 namespace {
1750 template <typename D>
1751 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1752                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1754 template <typename D>
1755 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1756                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1758 struct Forward {
1759     typedef SPObject *Iterator;
1761     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1762     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1763     static void dispose(Iterator i) {}
1765     static SPObject *object(Iterator i) { return i; }
1766     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1767 };
1769 struct Reverse {
1770     typedef GSList *Iterator;
1772     static Iterator children(SPObject *o) {
1773         return make_list(o->firstChild(), NULL);
1774     }
1775     static Iterator siblings_after(SPObject *o) {
1776         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1777     }
1778     static void dispose(Iterator i) {
1779         g_slist_free(i);
1780     }
1782     static SPObject *object(Iterator i) {
1783         return reinterpret_cast<SPObject *>(i->data);
1784     }
1785     static Iterator next(Iterator i) { return i->next; }
1787 private:
1788     static GSList *make_list(SPObject *object, SPObject *limit) {
1789         GSList *list=NULL;
1790         while ( object != limit ) {
1791             list = g_slist_prepend(list, object);
1792             object = SP_OBJECT_NEXT(object);
1793         }
1794         return list;
1795     }
1796 };
1800 void
1801 sp_selection_item_next(void)
1803     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1804     g_return_if_fail(desktop != NULL);
1805     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1807     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1808     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1809     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1811     SPObject *root;
1812     if (PREFS_SELECTION_ALL != inlayer) {
1813         root = selection->activeContext();
1814     } else {
1815         root = desktop->currentRoot();
1816     }
1818     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1820     if (item) {
1821         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1822         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1823             scroll_to_show_item(desktop, item);
1824         }
1825     }
1828 void
1829 sp_selection_item_prev(void)
1831     SPDocument *document = SP_ACTIVE_DOCUMENT;
1832     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1833     g_return_if_fail(document != NULL);
1834     g_return_if_fail(desktop != NULL);
1835     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1837     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1838     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1839     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1841     SPObject *root;
1842     if (PREFS_SELECTION_ALL != inlayer) {
1843         root = selection->activeContext();
1844     } else {
1845         root = desktop->currentRoot();
1846     }
1848     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1850     if (item) {
1851         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1852         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1853             scroll_to_show_item(desktop, item);
1854         }
1855     }
1858 namespace {
1860 template <typename D>
1861 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1862                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1864     SPObject *current=root;
1865     while (items) {
1866         SPItem *item=SP_ITEM(items->data);
1867         if ( root->isAncestorOf(item) &&
1868              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1869         {
1870             current = item;
1871             break;
1872         }
1873         items = items->next;
1874     }
1876     GSList *path=NULL;
1877     while ( current != root ) {
1878         path = g_slist_prepend(path, current);
1879         current = SP_OBJECT_PARENT(current);
1880     }
1882     SPItem *next;
1883     // first, try from the current object
1884     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1885     g_slist_free(path);
1887     if (!next) { // if we ran out of objects, start over at the root
1888         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1889     }
1891     return next;
1894 template <typename D>
1895 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1896                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1898     typename D::Iterator children;
1899     typename D::Iterator iter;
1901     SPItem *found=NULL;
1903     if (path) {
1904         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1905         g_assert(SP_OBJECT_PARENT(object) == root);
1906         if (desktop->isLayer(object)) {
1907             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1908         }
1909         iter = children = D::siblings_after(object);
1910     } else {
1911         iter = children = D::children(root);
1912     }
1914     while ( iter && !found ) {
1915         SPObject *object=D::object(iter);
1916         if (desktop->isLayer(object)) {
1917             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1918                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1919             }
1920         } else if ( SP_IS_ITEM(object) &&
1921                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1922                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1923                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1924                     !desktop->isLayer(SP_ITEM(object)) )
1925         {
1926             found = SP_ITEM(object);
1927         }
1928         iter = D::next(iter);
1929     }
1931     D::dispose(children);
1933     return found;
1938 /**
1939  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1940  * \a item.
1941  */
1942 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1944     NR::Rect dbox = desktop->get_display_area();
1945     NR::Rect sbox = sp_item_bbox_desktop(item);
1947     if (dbox.contains(sbox) == false) {
1948         NR::Point const s_dt = sbox.midpoint();
1949         NR::Point const s_w = desktop->d2w(s_dt);
1950         NR::Point const d_dt = dbox.midpoint();
1951         NR::Point const d_w = desktop->d2w(d_dt);
1952         NR::Point const moved_w( d_w - s_w );
1953         gint const dx = (gint) moved_w[X];
1954         gint const dy = (gint) moved_w[Y];
1955         desktop->scroll_world(dx, dy);
1956     }
1960 void
1961 sp_selection_clone()
1963     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1964     if (desktop == NULL)
1965         return;
1967     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1969     // check if something is selected
1970     if (selection->isEmpty()) {
1971         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1972         return;
1973     }
1975     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1976   
1977     selection->clear();
1978   
1979     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1980     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1982     GSList *newsel = NULL;
1983  
1984     while (reprs) {
1985         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1986         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1988         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1989         sp_repr_set_attr(clone, "x", "0");
1990         sp_repr_set_attr(clone, "y", "0");
1991         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1993         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1994         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1995         
1996         // add the new clone to the top of the original's parent
1997         parent->appendChild(clone);
1999         newsel = g_slist_prepend(newsel, clone);
2000         reprs = g_slist_remove(reprs, sel_repr);
2001         Inkscape::GC::release(clone);
2002     }
2003     
2004     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2005                      _("Clone"));
2007     selection->setReprList(newsel);
2008  
2009     g_slist_free(newsel);
2012 void
2013 sp_selection_unlink()
2015     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2016     if (!desktop)
2017         return;
2019     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2021     if (selection->isEmpty()) {
2022         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2023         return;
2024     }
2026     // Get a copy of current selection.
2027     GSList *new_select = NULL;
2028     bool unlinked = false;
2029     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2030          items != NULL;
2031          items = items->next)
2032     {
2033         SPItem *use = (SPItem *) items->data;
2035         if (!SP_IS_USE(use)) {
2036             // keep the non-yse item in the new selection
2037             new_select = g_slist_prepend(new_select, use);
2038             continue;
2039         }
2041         SPItem *unlink = sp_use_unlink(SP_USE(use));
2042         unlinked = true;
2043         // Add ungrouped items to the new selection.
2044         new_select = g_slist_prepend(new_select, unlink);
2045     }
2047     if (new_select) { // set new selection
2048         selection->clear();
2049         selection->setList(new_select);
2050         g_slist_free(new_select);
2051     }
2052     if (!unlinked) {
2053         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2054     }
2056     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2057                      _("Unlink clone"));
2060 void
2061 sp_select_clone_original()
2063     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2064     if (desktop == NULL)
2065         return;
2067     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2069     SPItem *item = selection->singleItem();
2071     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.");
2073     // Check if other than two objects are selected
2074     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2075         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2076         return;
2077     }
2079     SPItem *original = NULL;
2080     if (SP_IS_USE(item)) {
2081         original = sp_use_get_original (SP_USE(item));
2082     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2083         original = sp_offset_get_source (SP_OFFSET(item));
2084     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2085         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2086     } else if (SP_IS_FLOWTEXT(item)) {
2087         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2088     } else { // it's an object that we don't know what to do with
2089         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2090         return;
2091     }
2093     if (!original) {
2094         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2095         return;
2096     }
2098     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2099         if (SP_IS_DEFS (o)) {
2100             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2101             return;
2102         }
2103     }
2105     if (original) {
2106         selection->clear();
2107         selection->set(original);
2108         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2109             scroll_to_show_item(desktop, original);
2110         }
2111     }
2114 void
2115 sp_selection_tile(bool apply)
2117     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2118     if (desktop == NULL)
2119         return;
2121     SPDocument *document = sp_desktop_document(desktop);
2123     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2125     // check if something is selected
2126     if (selection->isEmpty()) {
2127         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2128         return;
2129     }
2131     sp_document_ensure_up_to_date(document);
2132     NR::Rect r = selection->bounds();
2133     if (r.isEmpty()) {
2134         return;
2135     }
2137     // calculate the transform to be applied to objects to move them to 0,0
2138     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2139     move_p[NR::Y] = -move_p[NR::Y];
2140     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2142     GSList *items = g_slist_copy((GSList *) selection->itemList());
2144     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2146     // bottommost object, after sorting
2147     SPObject *parent = SP_OBJECT_PARENT (items->data);
2149     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2151     // remember the position of the first item
2152     gint pos = SP_OBJECT_REPR (items->data)->position();
2154     // create a list of duplicates
2155     GSList *repr_copies = NULL;
2156     for (GSList *i = items; i != NULL; i = i->next) {
2157         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2158         repr_copies = g_slist_prepend (repr_copies, dup);
2159     }
2161     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2163     if (apply) {
2164         // delete objects so that their clones don't get alerted; this object will be restored shortly
2165         for (GSList *i = items; i != NULL; i = i->next) {
2166             SPObject *item = SP_OBJECT (i->data);
2167             item->deleteObject (false);
2168         }
2169     }
2171     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2172     // without disturbing clones.
2173     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2174     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2175     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2177     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2178                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2180     // restore compensation setting
2181     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2183     if (apply) {
2184         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2185         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2187         NR::Point min = bounds.min() * parent_transform.inverse();
2188         NR::Point max = bounds.max() * parent_transform.inverse();
2190         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2191         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2192         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2193         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2195         // restore parent and position
2196         SP_OBJECT_REPR (parent)->appendChild(rect);
2197         rect->setPosition(pos > 0 ? pos : 0);
2198         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2200         Inkscape::GC::release(rect);
2202         selection->clear();
2203         selection->set(rectangle);
2204     }
2206     g_slist_free (items);
2208     sp_document_done (document, SP_VERB_EDIT_TILE, 
2209                       _("Objects to pattern"));
2212 void
2213 sp_selection_untile()
2215     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2216     if (desktop == NULL)
2217         return;
2219     SPDocument *document = sp_desktop_document(desktop);
2221     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2223     // check if something is selected
2224     if (selection->isEmpty()) {
2225         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2226         return;
2227     }
2229     GSList *new_select = NULL;
2231     bool did = false;
2233     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2234          items != NULL;
2235          items = items->next) {
2237         SPItem *item = (SPItem *) items->data;
2239         SPStyle *style = SP_OBJECT_STYLE (item);
2241         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2242             continue;
2244         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2246         if (!SP_IS_PATTERN(server))
2247             continue;
2249         did = true;
2251         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2253         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2254         pat_transform *= item->transform;
2256         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2257             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2258             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2260            // FIXME: relink clones to the new canvas objects
2261            // use SPObject::setid when mental finishes it to steal ids of
2263             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2264             sp_document_ensure_up_to_date (document);
2266             NR::Matrix transform( i->transform * pat_transform );
2267             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2269             new_select = g_slist_prepend(new_select, i);
2270         }
2272         SPCSSAttr *css = sp_repr_css_attr_new ();
2273         sp_repr_css_set_property (css, "fill", "none");
2274         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2275     }
2277     if (!did) {
2278         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2279     } else {
2280         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2281                          _("Pattern to objects"));
2282         selection->setList(new_select);
2283     }
2286 void
2287 sp_selection_create_bitmap_copy ()
2289     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2290     if (desktop == NULL)
2291         return;
2293     SPDocument *document = sp_desktop_document(desktop);
2295     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2297     // check if something is selected
2298     if (selection->isEmpty()) {
2299         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2300         return;
2301     }
2303     // Get the bounding box of the selection
2304     NRRect bbox;
2305     sp_document_ensure_up_to_date (document);
2306     selection->bounds(&bbox);
2307     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2308         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2309     }
2311     // List of the items to show; all others will be hidden
2312     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2314     // Sort items so that the topmost comes last
2315     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2317     // Generate a random value from the current time (you may create bitmap from the same object(s)
2318     // multiple times, and this is done so that they don't clash)
2319     GTimeVal cu;
2320     g_get_current_time (&cu);
2321     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2323     // Create the filename
2324     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2325     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2326     // digits, and a few other chars, with "_"
2327     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2328     // Build the complete path by adding document->base if set
2329     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2331     //g_print ("%s\n", filepath);
2333     // Remember parent and z-order of the topmost one
2334     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2335     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2336     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2338     // Calculate resolution
2339     double res;
2340     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2341     if (0 < prefs_res) {
2342         // If it's given explicitly in prefs, take it
2343         res = prefs_res;
2344     } else {
2345         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2346         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2347         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2348     }
2350     // The width and height of the bitmap in pixels
2351     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2352     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2354     // Find out if we have to run a filter
2355     const gchar *run = NULL;
2356     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2357     if (filter) {
2358         // filter command is given;
2359         // see if we have a parameter to pass to it
2360         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2361         if (param1) {
2362             if (param1[strlen(param1) - 1] == '%') {
2363                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2364                 gchar p1[256];
2365                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2366                 // the first param is always the image filename, the second is param1
2367                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2368             } else {
2369                 // otherwise pass the param1 unchanged
2370                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2371             }
2372         } else {
2373             // run without extra parameter
2374             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2375         }
2376     }
2378     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2379     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2380     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2382     // Do the export
2383     sp_export_png_file(document, filepath,
2384                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2385                    width, height, res, res,
2386                    (guint32) 0xffffff00,
2387                    NULL, NULL,
2388                    true,  /*bool force_overwrite,*/
2389                    items);
2391     g_slist_free (items);
2393     // Run filter, if any
2394     if (run) {
2395         g_print ("Running external filter: %s\n", run);
2396         system (run);
2397     }
2399     // Import the image back
2400     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2401     if (pb) {
2402         // Create the repr for the image
2403         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2404         repr->setAttribute("xlink:href", filename);
2405         repr->setAttribute("sodipodi:absref", filepath);
2406         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2407         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2409         // Write transform
2410         gchar c[256];
2411         if (sp_svg_transform_write(c, 256, t)) {
2412             repr->setAttribute("transform", c);
2413         }
2415         // add the new repr to the parent
2416         parent->appendChild(repr);
2418         // move to the saved position
2419         repr->setPosition(pos > 0 ? pos + 1 : 1);
2421         // Set selection to the new image
2422         selection->clear();
2423         selection->add(repr);
2425         // Clean up
2426         Inkscape::GC::release(repr);
2427         gdk_pixbuf_unref (pb);
2429         // Complete undoable transaction
2430         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2431                           _("Create bitmap"));
2432     }
2434     g_free (filename);
2435     g_free (filepath);
2438 /**
2439  * \brief sp_selection_set_mask
2440  *
2441  * This function creates a mask or clipPath from selection
2442  * Two different modes:
2443  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2444  *       and is applied to current layer
2445  *  otherwise, topmost object is used as mask for other objects
2446  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2447  * 
2448  */
2449 void
2450 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2452     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2453     if (desktop == NULL)
2454         return;
2456     SPDocument *document = sp_desktop_document(desktop);
2457     
2458     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2460     // check if something is selected
2461     bool is_empty = selection->isEmpty();
2462     if ( apply_to_layer && is_empty) {
2463         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2464         return;
2465     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2466         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2467         return;
2468     }
2469     
2470     sp_document_ensure_up_to_date(document);
2472     GSList *items = g_slist_copy((GSList *) selection->itemList());
2473     
2474     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2476     // create a list of duplicates
2477     GSList *mask_items = NULL;
2478     GSList *apply_to_items = NULL;
2479     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2480     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2481     
2482     if (apply_to_layer) {
2483         // all selected items are used for mask, which is applied to a layer
2484         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2486         for (GSList *i = items; i != NULL; i = i->next) {
2487             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2488             mask_items = g_slist_prepend (mask_items, dup);
2490             if (remove_original) {
2491                 SPObject *item = SP_OBJECT (i->data);
2492                 item->deleteObject (false);
2493             }
2494         }
2495     } else if (!topmost) {
2496         // topmost item is used as a mask, which is applied to other items in a selection
2497         GSList *i = items;
2498         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2499         mask_items = g_slist_prepend (mask_items, dup);
2501         if (remove_original) {
2502             SPObject *item = SP_OBJECT (i->data);
2503             item->deleteObject (false);
2504         }
2505         
2506         for (i = i->next; i != NULL; i = i->next) {
2507             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2508         }
2509     } else {
2510         GSList *i = NULL;
2511         for (i = items; NULL != i->next; i = i->next) {
2512             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2513         }
2515         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2516         mask_items = g_slist_prepend (mask_items, dup);
2518         if (remove_original) {
2519             SPObject *item = SP_OBJECT (i->data);
2520             item->deleteObject (false);
2521         }
2522     }
2523     
2524     g_slist_free (items);
2525     items = NULL;
2526             
2527     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2528     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2529         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2530         // inverted object transform should be applied to a mask object,
2531         // as mask is calculated in user space (after applying transform)
2532         NR::Matrix maskTransform (item->transform.inverse());
2534         GSList *mask_items_dup = NULL;
2535         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2536             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2537             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2538         }
2540         const gchar *mask_id = NULL;
2541         if (apply_clip_path) {
2542             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2543         } else {
2544             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2545         }
2547         g_slist_free (mask_items_dup);
2548         mask_items_dup = NULL;
2550         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2551     }
2553     g_slist_free (mask_items);
2554     g_slist_free (apply_to_items);
2556     if (apply_clip_path) 
2557         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2558     else 
2559         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2562 void sp_selection_unset_mask(bool apply_clip_path) {
2563     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2564     if (desktop == NULL)
2565         return;
2566     
2567     SPDocument *document = sp_desktop_document(desktop);    
2568     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2570     // check if something is selected
2571     if (selection->isEmpty()) {
2572         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2573         return;
2574     }
2575     
2576     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2577     sp_document_ensure_up_to_date(document);
2579     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2580     std::map<SPObject*,SPItem*> referenced_objects;
2581     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2582         if (remove_original) {
2583             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2584             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2585             Inkscape::URIReference *uri_ref = NULL;
2586         
2587             if (apply_clip_path) {
2588                 uri_ref = item->clip_ref;
2589             } else {
2590                 uri_ref = item->mask_ref;
2591             }
2593             // collect distinct mask object (and associate with item to apply transform)
2594             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2595                 referenced_objects[uri_ref->getObject()] = item;
2596             }
2597         }
2599         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2600     }
2602     // restore mask objects into a document
2603     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2604         SPObject *obj = (*it).first;
2605         GSList *items_to_move = NULL;
2606         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2607             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2608             items_to_move = g_slist_prepend (items_to_move, copy);
2609         }
2611         if (!obj->isReferenced()) {
2612             // delete from defs if no other object references this mask
2613             obj->deleteObject(false);
2614         }
2616         // remember parent and position of the item to which the clippath/mask was applied
2617         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2618         gint pos = SP_OBJECT_REPR((*it).second)->position();
2620         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2621             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2623             // insert into parent, restore pos
2624             parent->appendChild(repr);
2625             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2627             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2628             selection->add(repr);
2630             // transform mask, so it is moved the same spot where mask was applied
2631             NR::Matrix transform (mask_item->transform);
2632             transform *= (*it).second->transform;
2633             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2634         }
2636         g_slist_free (items_to_move);
2637     }
2639     if (apply_clip_path) 
2640         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2641     else 
2642         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2645 void fit_canvas_to_selection(SPDesktop *desktop) {
2646     g_return_if_fail(desktop != NULL);
2647     SPDocument *doc = sp_desktop_document(desktop);
2649     g_return_if_fail(doc != NULL);
2650     g_return_if_fail(desktop->selection != NULL);
2651     g_return_if_fail(!desktop->selection->isEmpty());
2652     NRRect bbox = {0,0,0,0};
2654     desktop->selection->bounds(&bbox);
2655     if (!empty(bbox)) {
2656         doc->fitToRect(bbox);
2657     }
2658 };
2660 void fit_canvas_to_drawing(SPDocument *doc) {
2661     g_return_if_fail(doc != NULL);
2662     NRRect bbox = {0,0,0,0};
2664     sp_document_ensure_up_to_date (doc);
2665     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2667     if (!empty(bbox)) {
2668         doc->fitToRect(bbox);
2669     }
2670 };
2672 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2673     g_return_if_fail(desktop != NULL);
2674     SPDocument *doc = sp_desktop_document(desktop);
2676     g_return_if_fail(doc != NULL);
2677     g_return_if_fail(desktop->selection != NULL);
2679     if (desktop->selection->isEmpty()) {
2680         fit_canvas_to_drawing(doc);
2681     } else {
2682         fit_canvas_to_selection(desktop);
2683     }
2685     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2686                      _("Fit page to selection"));
2687 };
2689 /*
2690   Local Variables:
2691   mode:c++
2692   c-file-style:"stroustrup"
2693   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2694   indent-tabs-mode:nil
2695   fill-column:99
2696   End:
2697 */
2698 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :