Code

Ensure that rubberbanding has been initialized before manipulating rubberband
[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     // recurse
938     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
939         if (SP_IS_ITEM(o))
940             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
941     }
944 /**
945  * \pre item != NULL
946  */
947 SPCSSAttr *
948 take_style_from_item (SPItem *item)
950     // write the complete cascaded style, context-free
951     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
952     if (css == NULL)
953         return NULL;
955     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
956         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
957         // if this is a text with exactly one tspan child, merge the style of that tspan as well
958         // If this is a group, merge the style of its topmost (last) child with style
959         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
960             if (SP_OBJECT_STYLE (last_element) != NULL) {
961                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
962                 if (temp) {
963                     sp_repr_css_merge (css, temp);
964                     sp_repr_css_attr_unref (temp);
965                 }
966                 break;
967             }
968         }
969     }
970     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
971         // do not copy text properties from non-text objects, it's confusing
972         css = sp_css_attr_unset_text (css);
973     }
975     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
976     double ex = NR::expansion(sp_item_i2doc_affine(item));
977     if (ex != 1.0) {
978         css = sp_css_attr_scale (css, ex);
979     }
981     return css;
985 void sp_selection_copy()
987     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
988     if (desktop == NULL)
989         return;
991     Inkscape::Selection *selection = sp_desktop_selection(desktop);
993     if (tools_isactive (desktop, TOOLS_DROPPER)) {
994         sp_dropper_context_copy(desktop->event_context);
995         return; // copied color under cursor, nothing else to do
996     }
998     // check if something is selected
999     if (selection->isEmpty()) {
1000         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1001         return;
1002     }
1004     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1006     // 0. Copy text to system clipboard
1007     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1008     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1009     Glib::ustring text;
1010     if (tools_isactive (desktop, TOOLS_TEXT)) {
1011         text = sp_text_get_selected_text(desktop->event_context);
1012     }
1014     if (text.empty()) {
1015         guint texts = 0;
1016         for (GSList *i = (GSList *) items; i; i = i->next) {
1017             SPItem *item = SP_ITEM (i->data);
1018             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1019                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1020                     text += " ";
1021                 gchar *this_text = sp_te_get_string_multiline (item);
1022                 if (this_text) {
1023                     text += this_text;
1024                     g_free(this_text);
1025                 }
1026                 texts++;
1027             }
1028         }
1029     }
1030     if (!text.empty()) {
1031         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1032         refClipboard->set_text(text);
1033     }
1035     // clear old defs clipboard
1036     while (defs_clipboard) {
1037         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1038         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1039     }
1041     // clear style clipboard
1042     if (style_clipboard) {
1043         sp_repr_css_attr_unref (style_clipboard);
1044         style_clipboard = NULL;
1045     }
1047     //clear main clipboard
1048     while (clipboard) {
1049         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1050         clipboard = g_slist_remove(clipboard, clipboard->data);
1051     }
1053     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1055     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1056         SPStyle *const query = sp_style_new();
1057         if (sp_desktop_query_style_all (desktop, query)) {
1058             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1059             if (css != NULL) {
1060                 // clear style clipboard
1061                 if (style_clipboard) {
1062                     sp_repr_css_attr_unref (style_clipboard);
1063                     style_clipboard = NULL;
1064                 }
1065                 //sp_repr_css_print (css);
1066                 style_clipboard = css;
1067             }
1068         }
1069         g_free (query);
1070     }
1072     size_clipboard = selection->bounds();
1074     g_slist_free ((GSList *) items);
1077 void sp_selection_paste(bool in_place)
1079     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1081     if (desktop == NULL) {
1082         return;
1083     }
1085     SPDocument *document = sp_desktop_document(desktop);
1087     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1088         return;
1089     }
1091     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1093     if (tools_isactive (desktop, TOOLS_TEXT)) {
1094         if (sp_text_paste_inline(desktop->event_context))
1095             return; // pasted from system clipboard into text, nothing else to do
1096     }
1098     // check if something is in the clipboard
1099     if (clipboard == NULL) {
1100         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1101         return;
1102     }
1104     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1105     // add pasted objects to selection
1106     selection->setReprList((GSList const *) copied);
1107     g_slist_free (copied);
1109     if (!in_place) {
1110         sp_document_ensure_up_to_date(document);
1112         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1114         /* Snap the offset of the new item(s) to the grid */
1115         /* FIXME: this gridsnap fiddling is a hack. */
1116         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1117         gdouble const curr_gridsnap = s.getDistance();
1118         s.setDistance(NR_HUGE);
1119         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1120         s.setDistance(curr_gridsnap);
1121         sp_selection_move_relative(selection, m);
1122     }
1124     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1125                      _("Paste"));
1128 void sp_selection_paste_style()
1130     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1131     if (desktop == NULL) return;
1133     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1135     // check if something is in the clipboard
1136     if (clipboard == NULL) {
1137         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1138         return;
1139     }
1141     // check if something is selected
1142     if (selection->isEmpty()) {
1143         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1144         return;
1145     }
1147     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1149     sp_desktop_set_style (desktop, style_clipboard);
1151     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1152                      _("Paste style"));
1155 void sp_selection_paste_size (bool apply_x, bool apply_y)
1157     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1158     if (desktop == NULL) return;
1160     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1162     // check if something is in the clipboard
1163     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1164         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1165         return;
1166     }
1168     // check if something is selected
1169     if (selection->isEmpty()) {
1170         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1171         return;
1172     }
1174     NR::Rect current = selection->bounds();
1175     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1176         return;
1177     }
1179     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1180     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1182     sp_selection_scale_relative (selection, current.midpoint(), 
1183                                  NR::scale(
1184                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1185                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1187     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1188                      _("Paste size"));
1191 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1193     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1194     if (desktop == NULL) return;
1196     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1198     // check if something is in the clipboard
1199     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1200         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1201         return;
1202     }
1204     // check if something is selected
1205     if (selection->isEmpty()) {
1206         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1207         return;
1208     }
1210     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1211         SPItem *item = SP_ITEM(l->data);
1213         NR::Rect current = sp_item_bbox_desktop(item);
1214         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1215             continue;
1216         }
1218         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1219         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1221         sp_item_scale_rel (item,
1222                                  NR::scale(
1223                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1224                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1226     }
1228     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1229                      _("Paste size separately"));
1232 void sp_selection_to_next_layer ()
1234     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1236     Inkscape::Selection *selection = sp_desktop_selection(dt);
1238     // check if something is selected
1239     if (selection->isEmpty()) {
1240         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1241         return;
1242     }
1244     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1246     bool no_more = false; // Set to true, if no more layers above
1247     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1248     if (next) {
1249         GSList *temp_clip = NULL;
1250         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1251         sp_selection_delete_impl (items);
1252         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1253         GSList *copied;
1254         if(next) {
1255             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1256         } else {
1257             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1258             no_more = true;
1259         }
1260         selection->setReprList((GSList const *) copied);
1261         g_slist_free (copied);
1262         if (temp_clip) g_slist_free (temp_clip);
1263         if (next) dt->setCurrentLayer(next);
1264         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1265                          _("Raise to next layer"));
1266     } else {
1267         no_more = true;
1268     }
1270     if (no_more) {
1271         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1272     }
1274     g_slist_free ((GSList *) items);
1277 void sp_selection_to_prev_layer ()
1279     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1281     Inkscape::Selection *selection = sp_desktop_selection(dt);
1283     // check if something is selected
1284     if (selection->isEmpty()) {
1285         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1286         return;
1287     }
1289     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1291     bool no_more = false; // Set to true, if no more layers below
1292     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1293     if (next) {
1294         GSList *temp_clip = NULL;
1295         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1296         sp_selection_delete_impl (items);
1297         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1298         GSList *copied;
1299         if(next) {
1300             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1301         } else {
1302             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1303             no_more = true;
1304         }
1305         selection->setReprList((GSList const *) copied);
1306         g_slist_free (copied);
1307         if (temp_clip) g_slist_free (temp_clip);
1308         if (next) dt->setCurrentLayer(next);
1309         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1310                          _("Lower to previous layer"));
1311     } else {
1312         no_more = true;
1313     }
1315     if (no_more) {
1316         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1317     }
1319     g_slist_free ((GSList *) items);
1322 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1323 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1324 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1325 that case, items are already in the new position, but the repr is in the old, and this function
1326 then simply updates the repr from item->transform.
1327  */
1328 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1330     if (selection->isEmpty())
1331         return;
1333     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1334         SPItem *item = SP_ITEM(l->data);
1336         NR::Point old_center(0,0);
1337         if (set_i2d && item->isCenterSet())
1338             old_center = item->getCenter();
1340 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1341          At the time of writing, this is the only place to re-enable. */
1342         sp_item_update_cns(*item, selection->desktop());
1343 #endif
1345         // we're moving both a clone and its original
1346         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1347         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)))) ));
1348         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1349         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1350        
1351         // If we're moving a connector, we want to detach it
1352         // from shapes that aren't part of the selection, but
1353         // leave it attached if they are
1354         if (cc_item_is_connector(item)) {
1355             SPItem *attItem[2];
1356             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1357             
1358             for (int n = 0; n < 2; ++n) {
1359                 if (!selection->includes(attItem[n])) {
1360                     sp_conn_end_detach(item, n);
1361                 }
1362             }
1363         }
1364         
1365         // "clones are unmoved when original is moved" preference
1366         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1367         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1368         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1370         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1371         // transform of its original and respond to it itself. Without this, a clone is doubly
1372         // transformed, very unintuitive.
1373       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1374       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1375       // Same for linked offset if we are also moving its source: do not move it.
1376         if (transform_textpath_with_path || transform_offset_with_source) {
1377                 // restore item->transform field from the repr, in case it was changed by seltrans
1378             sp_object_read_attr (SP_OBJECT (item), "transform");
1380         } else if (transform_flowtext_with_frame) {
1381             // apply the inverse of the region's transform to the <use> so that the flow remains
1382             // the same (even though the output itself gets transformed)
1383             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1384                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1385                     continue;
1386                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1387                     if (!SP_IS_USE(use)) continue;
1388                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1389                 }
1390             }
1391         } else if (transform_clone_with_original) {
1392             // We are transforming a clone along with its original. The below matrix juggling is
1393             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1394             // transform and its move compensation are both cancelled out.
1396             // restore item->transform field from the repr, in case it was changed by seltrans
1397             sp_object_read_attr (SP_OBJECT (item), "transform");
1399             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1400             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1401             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1402             NR::Matrix result = t_inv * item->transform * t;
1404             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1405                 // we need to cancel out the move compensation, too
1407                 // find out the clone move, same as in sp_use_move_compensate
1408                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1409                 NR::Matrix clone_move = parent.inverse() * t * parent;
1411                 if (prefs_parallel) {
1412                     NR::Matrix move = result * clone_move * t_inv;
1413                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1415                 } else if (prefs_unmoved) {
1416                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1417                         clone_move = NR::identity();
1418                     NR::Matrix move = result * clone_move;
1419                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1420                 }
1422             } else {
1423                 // just apply the result
1424                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1425             }
1427         } else {
1428             if (set_i2d) {
1429                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1430             }
1431             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1432         }
1434         // if we're moving the actual object, not just updating the repr, we can transform the
1435         // center by the same matrix (only necessary for non-translations)
1436         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1437             item->setCenter(old_center * affine);
1438             SP_OBJECT(item)->updateRepr();
1439         }
1440     }
1443 void sp_selection_remove_transform()
1445     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1446     if (desktop == NULL)
1447         return;
1449     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1451     GSList const *l = (GSList *) selection->reprList();
1452     while (l != NULL) {
1453         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1454         l = l->next;
1455     }
1457     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1458                      _("Remove transform"));
1461 void
1462 sp_selection_scale_absolute(Inkscape::Selection *selection,
1463                             double const x0, double const x1,
1464                             double const y0, double const y1)
1466     if (selection->isEmpty())
1467         return;
1469     NR::Rect const bbox(selection->bounds());
1470     if (bbox.isEmpty()) {
1471         return;
1472     }
1474     NR::translate const p2o(-bbox.min());
1476     NR::scale const newSize(x1 - x0,
1477                             y1 - y0);
1478     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1479     NR::translate const o2n(x0, y0);
1480     NR::Matrix const final( p2o * scale * o2n );
1482     sp_selection_apply_affine(selection, final);
1486 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1488     if (selection->isEmpty())
1489         return;
1491     NR::Rect const bbox(selection->bounds());
1493     if (bbox.isEmpty()) {
1494         return;
1495     }
1497     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1498     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1499          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1500     {
1501         return;
1502     }
1504     NR::translate const n2d(-align);
1505     NR::translate const d2n(align);
1506     NR::Matrix const final( n2d * scale * d2n );
1507     sp_selection_apply_affine(selection, final);
1510 void
1511 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1513     NR::translate const d2n(center);
1514     NR::translate const n2d(-center);
1515     NR::rotate const rotate(rotate_degrees(angle_degrees));
1516     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1517     sp_selection_apply_affine(selection, final);
1520 void
1521 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1523     NR::translate const d2n(align);
1524     NR::translate const n2d(-align);
1525     NR::Matrix const skew(1, dy,
1526                           dx, 1,
1527                           0, 0);
1528     NR::Matrix const final( n2d * skew * d2n );
1529     sp_selection_apply_affine(selection, final);
1532 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1534     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1537 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1539     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1543 /**
1544  * \brief sp_selection_rotate_90
1545  *
1546  * This function rotates selected objects 90 degrees clockwise.
1547  *
1548  */
1550 void sp_selection_rotate_90_cw()
1552     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1554     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1556     if (selection->isEmpty())
1557         return;
1559     GSList const *l = selection->itemList();
1560     NR::rotate const rot_neg_90(NR::Point(0, -1));
1561     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1562         SPItem *item = SP_ITEM(l2->data);
1563         sp_item_rotate_rel(item, rot_neg_90);
1564     }
1566     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1567                      _("Rotate 90&#176; CW"));
1571 /**
1572  * \brief sp_selection_rotate_90_ccw
1573  *
1574  * This function rotates selected objects 90 degrees counter-clockwise.
1575  *
1576  */
1578 void sp_selection_rotate_90_ccw()
1580     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1582     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1584     if (selection->isEmpty())
1585         return;
1587     GSList const *l = selection->itemList();
1588     NR::rotate const rot_neg_90(NR::Point(0, 1));
1589     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1590         SPItem *item = SP_ITEM(l2->data);
1591         sp_item_rotate_rel(item, rot_neg_90);
1592     }
1594     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1595                      _("Rotate 90&#176; CCW"));
1598 void
1599 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1601     if (selection->isEmpty())
1602         return;
1604     NR::Point center = selection->center();
1606     sp_selection_rotate_relative(selection, center, angle_degrees);
1608     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1609                            ( ( angle_degrees > 0 )
1610                              ? "selector:rotate:ccw"
1611                              : "selector:rotate:cw" ), 
1612                            SP_VERB_CONTEXT_SELECT, 
1613                            _("Rotate"));
1616 /**
1617 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1618 */
1619 void
1620 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1622     if (selection->isEmpty())
1623         return;
1625     NR::Rect const bbox(selection->bounds());
1627     NR::Point center = selection->center();
1629     gdouble const zoom = selection->desktop()->current_zoom();
1630     gdouble const zmove = angle / zoom;
1631     gdouble const r = NR::L2(bbox.max() - center);
1633     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1635     sp_selection_rotate_relative(selection, center, zangle);
1637     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1638                            ( (angle > 0)
1639                              ? "selector:rotate:ccw"
1640                              : "selector:rotate:cw" ),
1641                            SP_VERB_CONTEXT_SELECT, 
1642                            _("Rotate by pixels"));
1645 void
1646 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1648     if (selection->isEmpty())
1649         return;
1651     NR::Rect const bbox(selection->bounds());
1652     NR::Point const center(bbox.midpoint());
1653     double const max_len = bbox.maxExtent();
1655     // you can't scale "do nizhe pola" (below zero)
1656     if ( max_len + grow <= 1e-3 ) {
1657         return;
1658     }
1660     double const times = 1.0 + grow / max_len;
1661     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1663     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1664                            ( (grow > 0)
1665                              ? "selector:scale:larger"
1666                              : "selector:scale:smaller" ),
1667                            SP_VERB_CONTEXT_SELECT,
1668                            _("Scale"));
1671 void
1672 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1674     sp_selection_scale(selection,
1675                        grow_pixels / selection->desktop()->current_zoom());
1678 void
1679 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1681     if (selection->isEmpty())
1682         return;
1684     NR::Point const center(selection->bounds().midpoint());
1685     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1686     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1687                      _("Scale by whole factor"));
1690 void
1691 sp_selection_move(gdouble dx, gdouble dy)
1693     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1694     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1695     if (selection->isEmpty()) {
1696         return;
1697     }
1699     sp_selection_move_relative(selection, dx, dy);
1701     if (dx == 0) {
1702         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1703                                _("Move vertically"));
1704     } else if (dy == 0) {
1705         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1706                                _("Move horizontally"));
1707     } else {
1708         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1709                          _("Move"));
1710     }
1713 void
1714 sp_selection_move_screen(gdouble dx, gdouble dy)
1716     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1718     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1719     if (selection->isEmpty()) {
1720         return;
1721     }
1723     // same as sp_selection_move but divide deltas by zoom factor
1724     gdouble const zoom = desktop->current_zoom();
1725     gdouble const zdx = dx / zoom;
1726     gdouble const zdy = dy / zoom;
1727     sp_selection_move_relative(selection, zdx, zdy);
1729     if (dx == 0) {
1730         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1731                                _("Nudge vertically by pixels"));
1732     } else if (dy == 0) {
1733         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1734                                _("Nudge horizontally by pixels"));
1735     } else {
1736         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1737                          _("Move"));
1738     }
1741 namespace {
1743 template <typename D>
1744 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1745                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1747 template <typename D>
1748 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1749                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1751 struct Forward {
1752     typedef SPObject *Iterator;
1754     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1755     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1756     static void dispose(Iterator i) {}
1758     static SPObject *object(Iterator i) { return i; }
1759     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1760 };
1762 struct Reverse {
1763     typedef GSList *Iterator;
1765     static Iterator children(SPObject *o) {
1766         return make_list(o->firstChild(), NULL);
1767     }
1768     static Iterator siblings_after(SPObject *o) {
1769         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1770     }
1771     static void dispose(Iterator i) {
1772         g_slist_free(i);
1773     }
1775     static SPObject *object(Iterator i) {
1776         return reinterpret_cast<SPObject *>(i->data);
1777     }
1778     static Iterator next(Iterator i) { return i->next; }
1780 private:
1781     static GSList *make_list(SPObject *object, SPObject *limit) {
1782         GSList *list=NULL;
1783         while ( object != limit ) {
1784             list = g_slist_prepend(list, object);
1785             object = SP_OBJECT_NEXT(object);
1786         }
1787         return list;
1788     }
1789 };
1793 void
1794 sp_selection_item_next(void)
1796     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1797     g_return_if_fail(desktop != NULL);
1798     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1800     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1801     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1802     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1804     SPObject *root;
1805     if (PREFS_SELECTION_ALL != inlayer) {
1806         root = selection->activeContext();
1807     } else {
1808         root = desktop->currentRoot();
1809     }
1811     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1813     if (item) {
1814         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1815         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1816             scroll_to_show_item(desktop, item);
1817         }
1818     }
1821 void
1822 sp_selection_item_prev(void)
1824     SPDocument *document = SP_ACTIVE_DOCUMENT;
1825     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1826     g_return_if_fail(document != NULL);
1827     g_return_if_fail(desktop != NULL);
1828     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1830     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1831     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1832     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1834     SPObject *root;
1835     if (PREFS_SELECTION_ALL != inlayer) {
1836         root = selection->activeContext();
1837     } else {
1838         root = desktop->currentRoot();
1839     }
1841     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1843     if (item) {
1844         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1845         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1846             scroll_to_show_item(desktop, item);
1847         }
1848     }
1851 namespace {
1853 template <typename D>
1854 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1855                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1857     SPObject *current=root;
1858     while (items) {
1859         SPItem *item=SP_ITEM(items->data);
1860         if ( root->isAncestorOf(item) &&
1861              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1862         {
1863             current = item;
1864             break;
1865         }
1866         items = items->next;
1867     }
1869     GSList *path=NULL;
1870     while ( current != root ) {
1871         path = g_slist_prepend(path, current);
1872         current = SP_OBJECT_PARENT(current);
1873     }
1875     SPItem *next;
1876     // first, try from the current object
1877     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1878     g_slist_free(path);
1880     if (!next) { // if we ran out of objects, start over at the root
1881         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1882     }
1884     return next;
1887 template <typename D>
1888 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1889                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1891     typename D::Iterator children;
1892     typename D::Iterator iter;
1894     SPItem *found=NULL;
1896     if (path) {
1897         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1898         g_assert(SP_OBJECT_PARENT(object) == root);
1899         if (desktop->isLayer(object)) {
1900             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1901         }
1902         iter = children = D::siblings_after(object);
1903     } else {
1904         iter = children = D::children(root);
1905     }
1907     while ( iter && !found ) {
1908         SPObject *object=D::object(iter);
1909         if (desktop->isLayer(object)) {
1910             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1911                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1912             }
1913         } else if ( SP_IS_ITEM(object) &&
1914                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1915                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1916                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1917                     !desktop->isLayer(SP_ITEM(object)) )
1918         {
1919             found = SP_ITEM(object);
1920         }
1921         iter = D::next(iter);
1922     }
1924     D::dispose(children);
1926     return found;
1931 /**
1932  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1933  * \a item.
1934  */
1935 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1937     NR::Rect dbox = desktop->get_display_area();
1938     NR::Rect sbox = sp_item_bbox_desktop(item);
1940     if (dbox.contains(sbox) == false) {
1941         NR::Point const s_dt = sbox.midpoint();
1942         NR::Point const s_w = desktop->d2w(s_dt);
1943         NR::Point const d_dt = dbox.midpoint();
1944         NR::Point const d_w = desktop->d2w(d_dt);
1945         NR::Point const moved_w( d_w - s_w );
1946         gint const dx = (gint) moved_w[X];
1947         gint const dy = (gint) moved_w[Y];
1948         desktop->scroll_world(dx, dy);
1949     }
1953 void
1954 sp_selection_clone()
1956     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1957     if (desktop == NULL)
1958         return;
1960     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1962     // check if something is selected
1963     if (selection->isEmpty()) {
1964         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1965         return;
1966     }
1968     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1969   
1970     selection->clear();
1971   
1972     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1973     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1975     GSList *newsel = NULL;
1976  
1977     while (reprs) {
1978         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1979         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1981         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1982         sp_repr_set_attr(clone, "x", "0");
1983         sp_repr_set_attr(clone, "y", "0");
1984         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1986         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1987         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1988         
1989         // add the new clone to the top of the original's parent
1990         parent->appendChild(clone);
1992         newsel = g_slist_prepend(newsel, clone);
1993         reprs = g_slist_remove(reprs, sel_repr);
1994         Inkscape::GC::release(clone);
1995     }
1996     
1997     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
1998                      _("Clone"));
2000     selection->setReprList(newsel);
2001  
2002     g_slist_free(newsel);
2005 void
2006 sp_selection_unlink()
2008     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2009     if (!desktop)
2010         return;
2012     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2014     if (selection->isEmpty()) {
2015         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2016         return;
2017     }
2019     // Get a copy of current selection.
2020     GSList *new_select = NULL;
2021     bool unlinked = false;
2022     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2023          items != NULL;
2024          items = items->next)
2025     {
2026         SPItem *use = (SPItem *) items->data;
2028         if (!SP_IS_USE(use)) {
2029             // keep the non-yse item in the new selection
2030             new_select = g_slist_prepend(new_select, use);
2031             continue;
2032         }
2034         SPItem *unlink = sp_use_unlink(SP_USE(use));
2035         unlinked = true;
2036         // Add ungrouped items to the new selection.
2037         new_select = g_slist_prepend(new_select, unlink);
2038     }
2040     if (new_select) { // set new selection
2041         selection->clear();
2042         selection->setList(new_select);
2043         g_slist_free(new_select);
2044     }
2045     if (!unlinked) {
2046         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2047     }
2049     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2050                      _("Unlink clone"));
2053 void
2054 sp_select_clone_original()
2056     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2057     if (desktop == NULL)
2058         return;
2060     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2062     SPItem *item = selection->singleItem();
2064     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.");
2066     // Check if other than two objects are selected
2067     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2068         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2069         return;
2070     }
2072     SPItem *original = NULL;
2073     if (SP_IS_USE(item)) {
2074         original = sp_use_get_original (SP_USE(item));
2075     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2076         original = sp_offset_get_source (SP_OFFSET(item));
2077     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2078         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2079     } else if (SP_IS_FLOWTEXT(item)) {
2080         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2081     } else { // it's an object that we don't know what to do with
2082         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2083         return;
2084     }
2086     if (!original) {
2087         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2088         return;
2089     }
2091     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2092         if (SP_IS_DEFS (o)) {
2093             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2094             return;
2095         }
2096     }
2098     if (original) {
2099         selection->clear();
2100         selection->set(original);
2101         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2102             scroll_to_show_item(desktop, original);
2103         }
2104     }
2107 void
2108 sp_selection_tile(bool apply)
2110     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2111     if (desktop == NULL)
2112         return;
2114     SPDocument *document = sp_desktop_document(desktop);
2116     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2118     // check if something is selected
2119     if (selection->isEmpty()) {
2120         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2121         return;
2122     }
2124     sp_document_ensure_up_to_date(document);
2125     NR::Rect r = selection->bounds();
2126     if (r.isEmpty()) {
2127         return;
2128     }
2130     // calculate the transform to be applied to objects to move them to 0,0
2131     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2132     move_p[NR::Y] = -move_p[NR::Y];
2133     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2135     GSList *items = g_slist_copy((GSList *) selection->itemList());
2137     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2139     // bottommost object, after sorting
2140     SPObject *parent = SP_OBJECT_PARENT (items->data);
2142     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2144     // remember the position of the first item
2145     gint pos = SP_OBJECT_REPR (items->data)->position();
2147     // create a list of duplicates
2148     GSList *repr_copies = NULL;
2149     for (GSList *i = items; i != NULL; i = i->next) {
2150         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2151         repr_copies = g_slist_prepend (repr_copies, dup);
2152     }
2154     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2156     if (apply) {
2157         // delete objects so that their clones don't get alerted; this object will be restored shortly
2158         for (GSList *i = items; i != NULL; i = i->next) {
2159             SPObject *item = SP_OBJECT (i->data);
2160             item->deleteObject (false);
2161         }
2162     }
2164     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2165     // without disturbing clones.
2166     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2167     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2168     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2170     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2171                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2173     // restore compensation setting
2174     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2176     if (apply) {
2177         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2178         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2180         NR::Point min = bounds.min() * parent_transform.inverse();
2181         NR::Point max = bounds.max() * parent_transform.inverse();
2183         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2184         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2185         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2186         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2188         // restore parent and position
2189         SP_OBJECT_REPR (parent)->appendChild(rect);
2190         rect->setPosition(pos > 0 ? pos : 0);
2191         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2193         Inkscape::GC::release(rect);
2195         selection->clear();
2196         selection->set(rectangle);
2197     }
2199     g_slist_free (items);
2201     sp_document_done (document, SP_VERB_EDIT_TILE, 
2202                       _("Objects to pattern"));
2205 void
2206 sp_selection_untile()
2208     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2209     if (desktop == NULL)
2210         return;
2212     SPDocument *document = sp_desktop_document(desktop);
2214     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2216     // check if something is selected
2217     if (selection->isEmpty()) {
2218         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2219         return;
2220     }
2222     GSList *new_select = NULL;
2224     bool did = false;
2226     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2227          items != NULL;
2228          items = items->next) {
2230         SPItem *item = (SPItem *) items->data;
2232         SPStyle *style = SP_OBJECT_STYLE (item);
2234         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2235             continue;
2237         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2239         if (!SP_IS_PATTERN(server))
2240             continue;
2242         did = true;
2244         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2246         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2247         pat_transform *= item->transform;
2249         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2250             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2251             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2253            // FIXME: relink clones to the new canvas objects
2254            // use SPObject::setid when mental finishes it to steal ids of
2256             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2257             sp_document_ensure_up_to_date (document);
2259             NR::Matrix transform( i->transform * pat_transform );
2260             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2262             new_select = g_slist_prepend(new_select, i);
2263         }
2265         SPCSSAttr *css = sp_repr_css_attr_new ();
2266         sp_repr_css_set_property (css, "fill", "none");
2267         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2268     }
2270     if (!did) {
2271         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2272     } else {
2273         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2274                          _("Pattern to objects"));
2275         selection->setList(new_select);
2276     }
2279 void
2280 sp_selection_create_bitmap_copy ()
2282     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2283     if (desktop == NULL)
2284         return;
2286     SPDocument *document = sp_desktop_document(desktop);
2288     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2290     // check if something is selected
2291     if (selection->isEmpty()) {
2292         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2293         return;
2294     }
2296     // Get the bounding box of the selection
2297     NRRect bbox;
2298     sp_document_ensure_up_to_date (document);
2299     selection->bounds(&bbox);
2300     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2301         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2302     }
2304     // List of the items to show; all others will be hidden
2305     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2307     // Sort items so that the topmost comes last
2308     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2310     // Generate a random value from the current time (you may create bitmap from the same object(s)
2311     // multiple times, and this is done so that they don't clash)
2312     GTimeVal cu;
2313     g_get_current_time (&cu);
2314     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2316     // Create the filename
2317     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2318     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2319     // digits, and a few other chars, with "_"
2320     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2321     // Build the complete path by adding document->base if set
2322     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2324     //g_print ("%s\n", filepath);
2326     // Remember parent and z-order of the topmost one
2327     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2328     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2329     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2331     // Calculate resolution
2332     double res;
2333     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2334     if (0 < prefs_res) {
2335         // If it's given explicitly in prefs, take it
2336         res = prefs_res;
2337     } else {
2338         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2339         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2340         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2341     }
2343     // The width and height of the bitmap in pixels
2344     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2345     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2347     // Find out if we have to run a filter
2348     const gchar *run = NULL;
2349     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2350     if (filter) {
2351         // filter command is given;
2352         // see if we have a parameter to pass to it
2353         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2354         if (param1) {
2355             if (param1[strlen(param1) - 1] == '%') {
2356                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2357                 gchar p1[256];
2358                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2359                 // the first param is always the image filename, the second is param1
2360                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2361             } else {
2362                 // otherwise pass the param1 unchanged
2363                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2364             }
2365         } else {
2366             // run without extra parameter
2367             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2368         }
2369     }
2371     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2372     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2373     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2375     // Do the export
2376     sp_export_png_file(document, filepath,
2377                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2378                    width, height, res, res,
2379                    (guint32) 0xffffff00,
2380                    NULL, NULL,
2381                    true,  /*bool force_overwrite,*/
2382                    items);
2384     g_slist_free (items);
2386     // Run filter, if any
2387     if (run) {
2388         g_print ("Running external filter: %s\n", run);
2389         system (run);
2390     }
2392     // Import the image back
2393     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2394     if (pb) {
2395         // Create the repr for the image
2396         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2397         repr->setAttribute("xlink:href", filename);
2398         repr->setAttribute("sodipodi:absref", filepath);
2399         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2400         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2402         // Write transform
2403         gchar c[256];
2404         if (sp_svg_transform_write(c, 256, t)) {
2405             repr->setAttribute("transform", c);
2406         }
2408         // add the new repr to the parent
2409         parent->appendChild(repr);
2411         // move to the saved position
2412         repr->setPosition(pos > 0 ? pos + 1 : 1);
2414         // Set selection to the new image
2415         selection->clear();
2416         selection->add(repr);
2418         // Clean up
2419         Inkscape::GC::release(repr);
2420         gdk_pixbuf_unref (pb);
2422         // Complete undoable transaction
2423         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2424                           _("Create bitmap"));
2425     }
2427     g_free (filename);
2428     g_free (filepath);
2431 /**
2432  * \brief sp_selection_set_mask
2433  *
2434  * This function creates a mask or clipPath from selection
2435  * Two different modes:
2436  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2437  *       and is applied to current layer
2438  *  otherwise, topmost object is used as mask for other objects
2439  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2440  * 
2441  */
2442 void
2443 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2445     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2446     if (desktop == NULL)
2447         return;
2449     SPDocument *document = sp_desktop_document(desktop);
2450     
2451     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2453     // check if something is selected
2454     bool is_empty = selection->isEmpty();
2455     if ( apply_to_layer && is_empty) {
2456         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2457         return;
2458     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2459         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2460         return;
2461     }
2462     
2463     sp_document_ensure_up_to_date(document);
2465     GSList *items = g_slist_copy((GSList *) selection->itemList());
2466     
2467     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2469     // create a list of duplicates
2470     GSList *mask_items = NULL;
2471     GSList *apply_to_items = NULL;
2472     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2473     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2474     
2475     if (apply_to_layer) {
2476         // all selected items are used for mask, which is applied to a layer
2477         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2479         for (GSList *i = items; i != NULL; i = i->next) {
2480             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2481             mask_items = g_slist_prepend (mask_items, dup);
2483             if (remove_original) {
2484                 SPObject *item = SP_OBJECT (i->data);
2485                 item->deleteObject (false);
2486             }
2487         }
2488     } else if (!topmost) {
2489         // topmost item is used as a mask, which is applied to other items in a selection
2490         GSList *i = items;
2491         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2492         mask_items = g_slist_prepend (mask_items, dup);
2494         if (remove_original) {
2495             SPObject *item = SP_OBJECT (i->data);
2496             item->deleteObject (false);
2497         }
2498         
2499         for (i = i->next; i != NULL; i = i->next) {
2500             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2501         }
2502     } else {
2503         GSList *i = NULL;
2504         for (i = items; NULL != i->next; i = i->next) {
2505             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2506         }
2508         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2509         mask_items = g_slist_prepend (mask_items, dup);
2511         if (remove_original) {
2512             SPObject *item = SP_OBJECT (i->data);
2513             item->deleteObject (false);
2514         }
2515     }
2516     
2517     g_slist_free (items);
2518     items = NULL;
2519             
2520     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2521     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2522         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2523         // inverted object transform should be applied to a mask object,
2524         // as mask is calculated in user space (after applying transform)
2525         NR::Matrix maskTransform (item->transform.inverse());
2527         GSList *mask_items_dup = NULL;
2528         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2529             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2530             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2531         }
2533         const gchar *mask_id = NULL;
2534         if (apply_clip_path) {
2535             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2536         } else {
2537             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2538         }
2540         g_slist_free (mask_items_dup);
2541         mask_items_dup = NULL;
2543         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2544     }
2546     g_slist_free (mask_items);
2547     g_slist_free (apply_to_items);
2549     if (apply_clip_path) 
2550         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2551     else 
2552         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2555 void sp_selection_unset_mask(bool apply_clip_path) {
2556     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2557     if (desktop == NULL)
2558         return;
2559     
2560     SPDocument *document = sp_desktop_document(desktop);    
2561     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2563     // check if something is selected
2564     if (selection->isEmpty()) {
2565         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2566         return;
2567     }
2568     
2569     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2570     sp_document_ensure_up_to_date(document);
2572     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2573     std::map<SPObject*,SPItem*> referenced_objects;
2574     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2575         if (remove_original) {
2576             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2577             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2578             Inkscape::URIReference *uri_ref = NULL;
2579         
2580             if (apply_clip_path) {
2581                 uri_ref = item->clip_ref;
2582             } else {
2583                 uri_ref = item->mask_ref;
2584             }
2586             // collect distinct mask object (and associate with item to apply transform)
2587             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2588                 referenced_objects[uri_ref->getObject()] = item;
2589             }
2590         }
2592         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2593     }
2595     // restore mask objects into a document
2596     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2597         SPObject *obj = (*it).first;
2598         GSList *items_to_move = NULL;
2599         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2600             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2601             items_to_move = g_slist_prepend (items_to_move, copy);
2602         }
2604         if (!obj->isReferenced()) {
2605             // delete from defs if no other object references this mask
2606             obj->deleteObject(false);
2607         }
2609         // remember parent and position of the item to which the clippath/mask was applied
2610         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2611         gint pos = SP_OBJECT_REPR((*it).second)->position();
2613         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2614             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2616             // insert into parent, restore pos
2617             parent->appendChild(repr);
2618             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2620             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2621             selection->add(repr);
2623             // transform mask, so it is moved the same spot where mask was applied
2624             NR::Matrix transform (mask_item->transform);
2625             transform *= (*it).second->transform;
2626             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2627         }
2629         g_slist_free (items_to_move);
2630     }
2632     if (apply_clip_path) 
2633         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2634     else 
2635         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2638 void fit_canvas_to_selection(SPDesktop *desktop) {
2639     g_return_if_fail(desktop != NULL);
2640     SPDocument *doc = sp_desktop_document(desktop);
2642     g_return_if_fail(doc != NULL);
2643     g_return_if_fail(desktop->selection != NULL);
2644     g_return_if_fail(!desktop->selection->isEmpty());
2645     NRRect bbox = {0,0,0,0};
2647     desktop->selection->bounds(&bbox);
2648     if (!empty(bbox)) {
2649         doc->fitToRect(bbox);
2650     }
2651 };
2653 void fit_canvas_to_drawing(SPDocument *doc) {
2654     g_return_if_fail(doc != NULL);
2655     NRRect bbox = {0,0,0,0};
2657     sp_document_ensure_up_to_date (doc);
2658     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2660     if (!empty(bbox)) {
2661         doc->fitToRect(bbox);
2662     }
2663 };
2665 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2666     g_return_if_fail(desktop != NULL);
2667     SPDocument *doc = sp_desktop_document(desktop);
2669     g_return_if_fail(doc != NULL);
2670     g_return_if_fail(desktop->selection != NULL);
2672     if (desktop->selection->isEmpty()) {
2673         fit_canvas_to_drawing(doc);
2674     } else {
2675         fit_canvas_to_selection(desktop);
2676     }
2678     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2679                      _("Fit page to selection"));
2680 };
2682 /*
2683   Local Variables:
2684   mode:c++
2685   c-file-style:"stroustrup"
2686   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2687   indent-tabs-mode:nil
2688   fill-column:99
2689   End:
2690 */
2691 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :