Code

factor out retrieving export hints from selection and document; use that for create_b...
[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 #include "unit-constants.h"
75 using NR::X;
76 using NR::Y;
78 #include "selection-chemistry.h"
80 /* fixme: find a better place */
81 GSList *clipboard = NULL;
82 GSList *defs_clipboard = NULL;
83 SPCSSAttr *style_clipboard = NULL;
84 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
86 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
88 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
89 {
90     Inkscape::XML::Node *copy = repr->duplicate();
92     // copy complete inherited style
93     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
94     sp_repr_css_set(copy, css, "style");
95     sp_repr_css_attr_unref(css);
97     // write the complete accummulated transform passed to us
98     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
99     gchar affinestr[80];
100     if (sp_svg_transform_write(affinestr, 79, full_t)) {
101         copy->setAttribute("transform", affinestr);
102     } else {
103         copy->setAttribute("transform", NULL);
104     }
106     *clip = g_slist_prepend(*clip, copy);
109 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
112     // Copy stuff referenced by all items to defs_clip:
113     if (defs_clip) {
114         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
115             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
116         }
117         *defs_clip = g_slist_reverse(*defs_clip);
118     }
120     // Store style:
121     if (style_clip) {
122         SPItem *item = SP_ITEM (items->data); // take from the first selected item
123         *style_clip = take_style_from_item (item);
124     }
126     if (clip) {
127         // Sort items:
128         GSList *sorted_items = g_slist_copy ((GSList *) items);
129         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
131         // Copy item reprs:
132         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
133             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
134         }
136         *clip = g_slist_reverse(*clip);
137         g_slist_free ((GSList *) sorted_items);
138     }
141 /**
142 Add gradients/patterns/markers referenced by copied objects to defs
143 */
144 void
145 paste_defs (GSList **defs_clip, SPDocument *doc)
147     if (!defs_clip)
148         return;
150     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
151         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
152         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
153         gchar const *id = repr->attribute("id");
154         if (!id || !doc->getObjectById(id)) {
155             Inkscape::XML::Node *copy = repr->duplicate();
156             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
157             Inkscape::GC::release(copy);
158         }
159     }
162 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
164     paste_defs (defs_clip, document);
166     GSList *copied = NULL;
167     // add objects to document
168     for (GSList *l = *clip; l != NULL; l = l->next) {
169         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
170         Inkscape::XML::Node *copy = repr->duplicate();
172         // premultiply the item transform by the accumulated parent transform in the paste layer
173         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
174         if (!local.test_identity()) {
175             gchar const *t_str = copy->attribute("transform");
176             NR::Matrix item_t (NR::identity());
177             if (t_str)
178                 sp_svg_transform_read(t_str, &item_t);
179             item_t *= local.inverse();
180             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
181             gchar affinestr[80];
182             if (sp_svg_transform_write(affinestr, 79, item_t)) {
183                 copy->setAttribute("transform", affinestr);
184             } else {
185                 copy->setAttribute("transform", NULL);
186             }
187         }
189         parent->appendChildRepr(copy);
190         copied = g_slist_prepend(copied, copy);
191         Inkscape::GC::release(copy);
192     }
193     return copied;
196 void sp_selection_delete_impl(const GSList *items)
198     for (const GSList *i = items ; i ; i = i->next ) {
199         sp_object_ref((SPObject *)i->data, NULL);
200     }
201     for (const GSList *i = items; i != NULL; i = i->next) {
202         SPItem *item = (SPItem *) i->data;
203         SP_OBJECT(item)->deleteObject();
204         sp_object_unref((SPObject *)item, NULL);
205     }
209 void sp_selection_delete()
211     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
212     if (desktop == NULL) {
213         return;
214     }
216     if (tools_isactive (desktop, TOOLS_TEXT))
217         if (sp_text_delete_selection(desktop->event_context)) {
218             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
219                              _("Delete text"));
220             return;
221         }
223     Inkscape::Selection *selection = sp_desktop_selection(desktop);
225     // check if something is selected
226     if (selection->isEmpty()) {
227         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
228         return;
229     }
231     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
232     selection->clear();
233     sp_selection_delete_impl (selected);
234     g_slist_free ((GSList *) selected);
236     /* a tool may have set up private information in it's selection context
237      * that depends on desktop items.  I think the only sane way to deal with
238      * this currently is to reset the current tool, which will reset it's
239      * associated selection context.  For example: deleting an object
240      * while moving it around the canvas.
241      */
242     tools_switch ( desktop, tools_active ( desktop ) );
244     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
245                      _("Delete"));
248 /* fixme: sequencing */
249 void sp_selection_duplicate()
251     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
252     if (desktop == NULL)
253         return;
255     Inkscape::Selection *selection = sp_desktop_selection(desktop);
257     // check if something is selected
258     if (selection->isEmpty()) {
259         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
260         return;
261     }
263     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
265     selection->clear();
267     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
268     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
270     GSList *newsel = NULL;
272     while (reprs) {
273         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
274         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
276         parent->appendChild(copy);
278         newsel = g_slist_prepend(newsel, copy);
279         reprs = g_slist_remove(reprs, reprs->data);
280         Inkscape::GC::release(copy);
281     }
283     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
284                      _("Duplicate"));
286     selection->setReprList(newsel);
288     g_slist_free(newsel);
291 void sp_edit_clear_all()
293     SPDesktop *dt = SP_ACTIVE_DESKTOP;
294     if (!dt)
295         return;
297     SPDocument *doc = sp_desktop_document(dt);
298     sp_desktop_selection(dt)->clear();
300     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
301     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
303     while (items) {
304         SP_OBJECT (items->data)->deleteObject();
305         items = g_slist_remove(items, items->data);
306     }
308     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
309                      _("Delete all"));
312 GSList *
313 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
315     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
316         if (SP_IS_ITEM(child) &&
317             !desktop->isLayer(SP_ITEM(child)) &&
318             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
319             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
320             (!exclude || !g_slist_find ((GSList *) exclude, child))
321             )
322         {
323             list = g_slist_prepend (list, SP_ITEM(child));
324         }
326         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
327             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
328         }
329     }
331     return list;
334 void sp_edit_select_all_full (bool force_all_layers, bool invert)
336     SPDesktop *dt = SP_ACTIVE_DESKTOP;
337     if (!dt)
338         return;
340     Inkscape::Selection *selection = sp_desktop_selection(dt);
342     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
344     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
345     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
346     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
348     GSList *items = NULL;
350     const GSList *exclude = NULL;
351     if (invert) {
352         exclude = selection->itemList();
353     }
355     if (force_all_layers)
356         inlayer = PREFS_SELECTION_ALL;
358     switch (inlayer) {
359         case PREFS_SELECTION_LAYER: {
360         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
361              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
362         return;
364         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
366         for (GSList *i = all_items; i; i = i->next) {
367             SPItem *item = SP_ITEM (i->data);
369             if (item && (!onlysensitive || !item->isLocked())) {
370                 if (!onlyvisible || !dt->itemIsHidden(item)) {
371                     if (!dt->isLayer(item)) {
372                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
373                             items = g_slist_prepend (items, item); // leave it in the list
374                         }
375                     }
376                 }
377             }
378         }
380         g_slist_free (all_items);
381             break;
382         }
383         case PREFS_SELECTION_LAYER_RECURSIVE: {
384             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
385             break;
386         }
387         default: {
388         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
389             break;
390     }
391     }
393     selection->setList (items);
395     if (items) {
396         g_slist_free (items);
397     }
400 void sp_edit_select_all ()
402     sp_edit_select_all_full (false, false);
405 void sp_edit_select_all_in_all_layers ()
407     sp_edit_select_all_full (true, false);
410 void sp_edit_invert ()
412     sp_edit_select_all_full (false, true);
415 void sp_edit_invert_in_all_layers ()
417     sp_edit_select_all_full (true, true);
420 void sp_selection_group()
422     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
423     if (desktop == NULL)
424         return;
426     SPDocument *document = sp_desktop_document (desktop);
428     Inkscape::Selection *selection = sp_desktop_selection(desktop);
430     // Check if something is selected.
431     if (selection->isEmpty()) {
432         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
433         return;
434     }
436     GSList const *l = (GSList *) selection->reprList();
438     // Check if at least two objects are selected.
439     if (l->next == NULL) {
440         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
441         return;
442     }
444     GSList *p = g_slist_copy((GSList *) l);
446     selection->clear();
448     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
450     // Remember the position and parent of the topmost object.
451     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
452     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
454     Inkscape::XML::Node *group = sp_repr_new("svg:g");
456     while (p) {
457         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
459         if (current->parent() == topmost_parent) {
460             Inkscape::XML::Node *spnew = current->duplicate();
461             sp_repr_unparent(current);
462             group->appendChild(spnew);
463             Inkscape::GC::release(spnew);
464             topmost --; // only reduce count for those items deleted from topmost_parent
465         } else { // move it to topmost_parent first
466                 GSList *temp_clip = NULL;
468                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
469                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
470                 gchar const *t_str = current->attribute("transform");
471                 NR::Matrix item_t (NR::identity());
472                 if (t_str)
473                     sp_svg_transform_read(t_str, &item_t);
474                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
475                 //FIXME: when moving both clone and original from a transformed group (either by
476                 //grouping into another parent, or by cut/paste) the transform from the original's
477                 //parent becomes embedded into original itself, and this affects its clones. Fix
478                 //this by remembering the transform diffs we write to each item into an array and
479                 //then, if this is clone, looking up its original in that array and pre-multiplying
480                 //it by the inverse of that original's transform diff.
482                 sp_selection_copy_one (current, item_t, &temp_clip);
483                 sp_repr_unparent(current);
485                 // paste into topmost_parent (temporarily)
486                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
487                 if (temp_clip) g_slist_free (temp_clip);
488                 if (copied) { // if success,
489                     // take pasted object (now in topmost_parent)
490                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
491                     // make a copy
492                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
493                     // remove pasted
494                     sp_repr_unparent(in_topmost);
495                     // put its copy into group
496                     group->appendChild(spnew);
497                     Inkscape::GC::release(spnew);
498                     g_slist_free (copied);
499                 }
500         }
501         p = g_slist_remove(p, current);
502     }
504     // Add the new group to the topmost members' parent
505     topmost_parent->appendChild(group);
507     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
508     group->setPosition(topmost + 1);
510     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
511                      _("Group"));
513     selection->set(group);
514     Inkscape::GC::release(group);
517 void sp_selection_ungroup()
519     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
520     if (desktop == NULL)
521         return;
523     Inkscape::Selection *selection = sp_desktop_selection(desktop);
525     if (selection->isEmpty()) {
526         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
527         return;
528     }
530     GSList *items = g_slist_copy((GSList *) selection->itemList());
531     selection->clear();
533     // Get a copy of current selection.
534     GSList *new_select = NULL;
535     bool ungrouped = false;
536     for (GSList *i = items;
537          i != NULL;
538          i = i->next)
539     {
540         SPItem *group = (SPItem *) i->data;
542         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
543         if (!SP_IS_OBJECT(group)) {
544             continue;
545         }
547         /* We do not allow ungrouping <svg> etc. (lauris) */
548         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
549             // keep the non-group item in the new selection
550             selection->add(group);
551             continue;
552         }
554         GSList *children = NULL;
555         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
556         sp_item_group_ungroup(SP_GROUP(group), &children, false);
557         ungrouped = true;
558         // Add ungrouped items to the new selection.
559         new_select = g_slist_concat(new_select, children);
560     }
562     if (new_select) { // Set new selection.
563         selection->addList(new_select);
564         g_slist_free(new_select);
565     }
566     if (!ungrouped) {
567         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
568     }
570     g_slist_free(items);
572     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
573                      _("Ungroup"));
576 static SPGroup *
577 sp_item_list_common_parent_group(const GSList *items)
579     if (!items) {
580         return NULL;
581     }
582     SPObject *parent = SP_OBJECT_PARENT(items->data);
583     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
584     if (!SP_IS_GROUP(parent)) {
585         return NULL;
586     }
587     for (items = items->next; items; items = items->next) {
588         if (SP_OBJECT_PARENT(items->data) != parent) {
589             return NULL;
590         }
591     }
593     return SP_GROUP(parent);
596 /** Finds out the minimum common bbox of the selected items
597  */
598 NR::Rect
599 enclose_items(const GSList *items)
601     g_assert(items != NULL);
603     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
605     for (GSList *i = items->next; i; i = i->next) {
606         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
607     }
609     return r;
612 SPObject *
613 prev_sibling(SPObject *child)
615     SPObject *parent = SP_OBJECT_PARENT(child);
616     if (!SP_IS_GROUP(parent)) {
617         return NULL;
618     }
619     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
620         if (i->next == child)
621             return i;
622     }
623     return NULL;
626 void
627 sp_selection_raise()
629     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
630     if (!desktop)
631         return;
633     Inkscape::Selection *selection = sp_desktop_selection(desktop);
635     GSList const *items = (GSList *) selection->itemList();
636     if (!items) {
637         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
638         return;
639     }
641     SPGroup const *group = sp_item_list_common_parent_group(items);
642     if (!group) {
643         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
644         return;
645     }
647     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
649     /* construct reverse-ordered list of selected children */
650     GSList *rev = g_slist_copy((GSList *) items);
651     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
653     // find out the common bbox of the selected items
654     NR::Rect selected = enclose_items(items);
656     // for all objects in the selection (starting from top)
657     while (rev) {
658         SPObject *child = SP_OBJECT(rev->data);
659         // for each selected object, find the next sibling
660         for (SPObject *newref = child->next; newref; newref = newref->next) {
661             // if the sibling is an item AND overlaps our selection,
662             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
663                 // AND if it's not one of our selected objects,
664                 if (!g_slist_find((GSList *) items, newref)) {
665                     // move the selected object after that sibling
666                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
667                 }
668                 break;
669             }
670         }
671         rev = g_slist_remove(rev, child);
672     }
674     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
675                      _("Raise"));
678 void sp_selection_raise_to_top()
680     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
681     if (desktop == NULL)
682         return;
684     SPDocument *document = sp_desktop_document(desktop);
685     Inkscape::Selection *selection = sp_desktop_selection(desktop);
687     if (selection->isEmpty()) {
688         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
689         return;
690     }
692     GSList const *items = (GSList *) selection->itemList();
694     SPGroup const *group = sp_item_list_common_parent_group(items);
695     if (!group) {
696         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
697         return;
698     }
700     GSList *rl = g_slist_copy((GSList *) selection->reprList());
701     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
703     for (GSList *l = rl; l != NULL; l = l->next) {
704         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
705         repr->setPosition(-1);
706     }
708     g_slist_free(rl);
710     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
711                      _("Raise to top"));
714 void
715 sp_selection_lower()
717     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
718     if (desktop == NULL)
719         return;
721     Inkscape::Selection *selection = sp_desktop_selection(desktop);
723     GSList const *items = (GSList *) selection->itemList();
724     if (!items) {
725         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
726         return;
727     }
729     SPGroup const *group = sp_item_list_common_parent_group(items);
730     if (!group) {
731         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
732         return;
733     }
735     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
737     // find out the common bbox of the selected items
738     NR::Rect selected = enclose_items(items);
740     /* construct direct-ordered list of selected children */
741     GSList *rev = g_slist_copy((GSList *) items);
742     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
743     rev = g_slist_reverse(rev);
745     // for all objects in the selection (starting from top)
746     while (rev) {
747         SPObject *child = SP_OBJECT(rev->data);
748         // for each selected object, find the prev sibling
749         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
750             // if the sibling is an item AND overlaps our selection,
751             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
752                 // AND if it's not one of our selected objects,
753                 if (!g_slist_find((GSList *) items, newref)) {
754                     // move the selected object before that sibling
755                     SPObject *put_after = prev_sibling(newref);
756                     if (put_after)
757                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
758                     else
759                         SP_OBJECT_REPR(child)->setPosition(0);
760                 }
761                 break;
762             }
763         }
764         rev = g_slist_remove(rev, child);
765     }
767     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
768                      _("Lower"));
772 void sp_selection_lower_to_bottom()
774     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
775     if (desktop == NULL)
776         return;
778     SPDocument *document = sp_desktop_document(desktop);
779     Inkscape::Selection *selection = sp_desktop_selection(desktop);
781     if (selection->isEmpty()) {
782         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
783         return;
784     }
786     GSList const *items = (GSList *) selection->itemList();
788     SPGroup const *group = sp_item_list_common_parent_group(items);
789     if (!group) {
790         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
791         return;
792     }
794     GSList *rl;
795     rl = g_slist_copy((GSList *) selection->reprList());
796     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
797     rl = g_slist_reverse(rl);
799     for (GSList *l = rl; l != NULL; l = l->next) {
800         gint minpos;
801         SPObject *pp, *pc;
802         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
803         pp = document->getObjectByRepr(sp_repr_parent(repr));
804         minpos = 0;
805         g_assert(SP_IS_GROUP(pp));
806         pc = sp_object_first_child(pp);
807         while (!SP_IS_ITEM(pc)) {
808             minpos += 1;
809             pc = pc->next;
810         }
811         repr->setPosition(minpos);
812     }
814     g_slist_free(rl);
816     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
817                      _("Lower to bottom"));
820 void
821 sp_undo(SPDesktop *desktop, SPDocument *)
823         if (!sp_document_undo(sp_desktop_document(desktop)))
824             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
827 void
828 sp_redo(SPDesktop *desktop, SPDocument *)
830         if (!sp_document_redo(sp_desktop_document(desktop)))
831             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
834 void sp_selection_cut()
836     sp_selection_copy();
837     sp_selection_delete();
840 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
842     SPGradient *ref = gradient;
844     while (ref) {
845         // climb up the refs, copying each one in the chain
846         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
847         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
849         ref = ref->ref->getObject();
850     }
853 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
855     SPPattern *ref = pattern;
857     while (ref) {
858         // climb up the refs, copying each one in the chain
859         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
860         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
862         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
863         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
864             if (!SP_IS_ITEM (child))
865                 continue;
866             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
867         }
869         ref = ref->ref->getObject();
870     }
873 void sp_copy_single (GSList **defs_clip, SPObject *thing)
875     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
876     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
880 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
882     SPItem *path = sp_textpath_get_path_item (tp);
883     if (!path)
884         return;
885     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
886         return;
887     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
888     *defs_clip = g_slist_prepend (*defs_clip, repr);
891 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
893     SPStyle *style = SP_OBJECT_STYLE (item);
895     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
896         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
897         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
898             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
899         if (SP_IS_PATTERN (server))
900             sp_copy_pattern (defs_clip, SP_PATTERN(server));
901     }
903     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
904         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
905         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
906             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
907         if (SP_IS_PATTERN (server))
908             sp_copy_pattern (defs_clip, SP_PATTERN(server));
909     }
911     if (SP_IS_SHAPE (item)) {
912         SPShape *shape = SP_SHAPE (item);
913         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
914             if (shape->marker[i]) {
915                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
916             }
917         }
918     }
920     if (SP_IS_TEXT_TEXTPATH (item)) {
921         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
922     }
924     if (item->clip_ref->getObject()) {
925         sp_copy_single (defs_clip, item->clip_ref->getObject());
926     }
928     if (item->mask_ref->getObject()) {
929         SPObject *mask = item->mask_ref->getObject();
930         sp_copy_single (defs_clip, mask);
931         // recurse into the mask for its gradients etc.
932         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
933             if (SP_IS_ITEM(o))
934                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
935         }
936     }
938     if (style->filter.filter) {
939         SPObject *filter = style->filter.filter;
940         if (SP_IS_FILTER(filter)) {
941             sp_copy_single (defs_clip, filter);
942         }
943     }
945     // recurse
946     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
947         if (SP_IS_ITEM(o))
948             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
949     }
952 /**
953  * \pre item != NULL
954  */
955 SPCSSAttr *
956 take_style_from_item (SPItem *item)
958     // write the complete cascaded style, context-free
959     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
960     if (css == NULL)
961         return NULL;
963     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
964         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
965         // if this is a text with exactly one tspan child, merge the style of that tspan as well
966         // If this is a group, merge the style of its topmost (last) child with style
967         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
968             if (SP_OBJECT_STYLE (last_element) != NULL) {
969                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
970                 if (temp) {
971                     sp_repr_css_merge (css, temp);
972                     sp_repr_css_attr_unref (temp);
973                 }
974                 break;
975             }
976         }
977     }
978     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
979         // do not copy text properties from non-text objects, it's confusing
980         css = sp_css_attr_unset_text (css);
981     }
983     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
984     double ex = NR::expansion(sp_item_i2doc_affine(item));
985     if (ex != 1.0) {
986         css = sp_css_attr_scale (css, ex);
987     }
989     return css;
993 void sp_selection_copy()
995     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
996     if (desktop == NULL)
997         return;
999     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1001     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1002         sp_dropper_context_copy(desktop->event_context);
1003         return; // copied color under cursor, nothing else to do
1004     }
1006     // check if something is selected
1007     if (selection->isEmpty()) {
1008         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1009         return;
1010     }
1012     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1014     // 0. Copy text to system clipboard
1015     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1016     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1017     Glib::ustring text;
1018     if (tools_isactive (desktop, TOOLS_TEXT)) {
1019         text = sp_text_get_selected_text(desktop->event_context);
1020     }
1022     if (text.empty()) {
1023         guint texts = 0;
1024         for (GSList *i = (GSList *) items; i; i = i->next) {
1025             SPItem *item = SP_ITEM (i->data);
1026             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1027                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1028                     text += " ";
1029                 gchar *this_text = sp_te_get_string_multiline (item);
1030                 if (this_text) {
1031                     text += this_text;
1032                     g_free(this_text);
1033                 }
1034                 texts++;
1035             }
1036         }
1037     }
1038     if (!text.empty()) {
1039         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1040         refClipboard->set_text(text);
1041     }
1043     // clear old defs clipboard
1044     while (defs_clipboard) {
1045         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1046         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1047     }
1049     // clear style clipboard
1050     if (style_clipboard) {
1051         sp_repr_css_attr_unref (style_clipboard);
1052         style_clipboard = NULL;
1053     }
1055     //clear main clipboard
1056     while (clipboard) {
1057         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1058         clipboard = g_slist_remove(clipboard, clipboard->data);
1059     }
1061     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1063     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1064         SPStyle *const query = sp_style_new();
1065         if (sp_desktop_query_style_all (desktop, query)) {
1066             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1067             if (css != NULL) {
1068                 // clear style clipboard
1069                 if (style_clipboard) {
1070                     sp_repr_css_attr_unref (style_clipboard);
1071                     style_clipboard = NULL;
1072                 }
1073                 //sp_repr_css_print (css);
1074                 style_clipboard = css;
1075             }
1076         }
1077         g_free (query);
1078     }
1080     size_clipboard = selection->bounds();
1082     g_slist_free ((GSList *) items);
1085 void sp_selection_paste(bool in_place)
1087     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1089     if (desktop == NULL) {
1090         return;
1091     }
1093     SPDocument *document = sp_desktop_document(desktop);
1095     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1096         return;
1097     }
1099     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1101     if (tools_isactive (desktop, TOOLS_TEXT)) {
1102         if (sp_text_paste_inline(desktop->event_context))
1103             return; // pasted from system clipboard into text, nothing else to do
1104     }
1106     // check if something is in the clipboard
1107     if (clipboard == NULL) {
1108         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1109         return;
1110     }
1112     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1113     // add pasted objects to selection
1114     selection->setReprList((GSList const *) copied);
1115     g_slist_free (copied);
1117     if (!in_place) {
1118         sp_document_ensure_up_to_date(document);
1120         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1122         /* Snap the offset of the new item(s) to the grid */
1123         /* FIXME: this gridsnap fiddling is a hack. */
1124         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1125         gdouble const curr_gridsnap = s.getDistance();
1126         s.setDistance(NR_HUGE);
1127         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1128         s.setDistance(curr_gridsnap);
1129         sp_selection_move_relative(selection, m);
1130     }
1132     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1133                      _("Paste"));
1136 void sp_selection_paste_style()
1138     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1139     if (desktop == NULL) return;
1141     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1143     // check if something is in the clipboard
1144     if (clipboard == NULL) {
1145         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1146         return;
1147     }
1149     // check if something is selected
1150     if (selection->isEmpty()) {
1151         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1152         return;
1153     }
1155     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1157     sp_desktop_set_style (desktop, style_clipboard);
1159     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1160                      _("Paste style"));
1163 void sp_selection_paste_size (bool apply_x, bool apply_y)
1165     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1166     if (desktop == NULL) return;
1168     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1170     // check if something is in the clipboard
1171     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1172         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1173         return;
1174     }
1176     // check if something is selected
1177     if (selection->isEmpty()) {
1178         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1179         return;
1180     }
1182     NR::Rect current = selection->bounds();
1183     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1184         return;
1185     }
1187     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1188     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1190     sp_selection_scale_relative (selection, current.midpoint(), 
1191                                  NR::scale(
1192                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1193                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1195     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1196                      _("Paste size"));
1199 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1201     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1202     if (desktop == NULL) return;
1204     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1206     // check if something is in the clipboard
1207     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1208         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1209         return;
1210     }
1212     // check if something is selected
1213     if (selection->isEmpty()) {
1214         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1215         return;
1216     }
1218     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1219         SPItem *item = SP_ITEM(l->data);
1221         NR::Rect current = sp_item_bbox_desktop(item);
1222         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1223             continue;
1224         }
1226         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1227         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1229         sp_item_scale_rel (item,
1230                                  NR::scale(
1231                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1232                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1234     }
1236     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1237                      _("Paste size separately"));
1240 void sp_selection_to_next_layer ()
1242     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1244     Inkscape::Selection *selection = sp_desktop_selection(dt);
1246     // check if something is selected
1247     if (selection->isEmpty()) {
1248         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1249         return;
1250     }
1252     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1254     bool no_more = false; // Set to true, if no more layers above
1255     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1256     if (next) {
1257         GSList *temp_clip = NULL;
1258         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1259         sp_selection_delete_impl (items);
1260         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1261         GSList *copied;
1262         if(next) {
1263             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1264         } else {
1265             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1266             no_more = true;
1267         }
1268         selection->setReprList((GSList const *) copied);
1269         g_slist_free (copied);
1270         if (temp_clip) g_slist_free (temp_clip);
1271         if (next) dt->setCurrentLayer(next);
1272         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1273                          _("Raise to next layer"));
1274     } else {
1275         no_more = true;
1276     }
1278     if (no_more) {
1279         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1280     }
1282     g_slist_free ((GSList *) items);
1285 void sp_selection_to_prev_layer ()
1287     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1289     Inkscape::Selection *selection = sp_desktop_selection(dt);
1291     // check if something is selected
1292     if (selection->isEmpty()) {
1293         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1294         return;
1295     }
1297     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1299     bool no_more = false; // Set to true, if no more layers below
1300     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1301     if (next) {
1302         GSList *temp_clip = NULL;
1303         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1304         sp_selection_delete_impl (items);
1305         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1306         GSList *copied;
1307         if(next) {
1308             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1309         } else {
1310             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1311             no_more = true;
1312         }
1313         selection->setReprList((GSList const *) copied);
1314         g_slist_free (copied);
1315         if (temp_clip) g_slist_free (temp_clip);
1316         if (next) dt->setCurrentLayer(next);
1317         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1318                          _("Lower to previous layer"));
1319     } else {
1320         no_more = true;
1321     }
1323     if (no_more) {
1324         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1325     }
1327     g_slist_free ((GSList *) items);
1330 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1331 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1332 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1333 that case, items are already in the new position, but the repr is in the old, and this function
1334 then simply updates the repr from item->transform.
1335  */
1336 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1338     if (selection->isEmpty())
1339         return;
1341     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1342         SPItem *item = SP_ITEM(l->data);
1344         NR::Point old_center(0,0);
1345         if (set_i2d && item->isCenterSet())
1346             old_center = item->getCenter();
1348 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1349          At the time of writing, this is the only place to re-enable. */
1350         sp_item_update_cns(*item, selection->desktop());
1351 #endif
1353         // we're moving both a clone and its original
1354         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1355         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)))) ));
1356         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1357         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1358        
1359         // If we're moving a connector, we want to detach it
1360         // from shapes that aren't part of the selection, but
1361         // leave it attached if they are
1362         if (cc_item_is_connector(item)) {
1363             SPItem *attItem[2];
1364             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1365             
1366             for (int n = 0; n < 2; ++n) {
1367                 if (!selection->includes(attItem[n])) {
1368                     sp_conn_end_detach(item, n);
1369                 }
1370             }
1371         }
1372         
1373         // "clones are unmoved when original is moved" preference
1374         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1375         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1376         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1378         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1379         // transform of its original and respond to it itself. Without this, a clone is doubly
1380         // transformed, very unintuitive.
1381       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1382       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1383       // Same for linked offset if we are also moving its source: do not move it.
1384         if (transform_textpath_with_path || transform_offset_with_source) {
1385                 // restore item->transform field from the repr, in case it was changed by seltrans
1386             sp_object_read_attr (SP_OBJECT (item), "transform");
1388         } else if (transform_flowtext_with_frame) {
1389             // apply the inverse of the region's transform to the <use> so that the flow remains
1390             // the same (even though the output itself gets transformed)
1391             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1392                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1393                     continue;
1394                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1395                     if (!SP_IS_USE(use)) continue;
1396                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1397                 }
1398             }
1399         } else if (transform_clone_with_original) {
1400             // We are transforming a clone along with its original. The below matrix juggling is
1401             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1402             // transform and its move compensation are both cancelled out.
1404             // restore item->transform field from the repr, in case it was changed by seltrans
1405             sp_object_read_attr (SP_OBJECT (item), "transform");
1407             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1408             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1409             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1410             NR::Matrix result = t_inv * item->transform * t;
1412             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1413                 // we need to cancel out the move compensation, too
1415                 // find out the clone move, same as in sp_use_move_compensate
1416                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1417                 NR::Matrix clone_move = parent.inverse() * t * parent;
1419                 if (prefs_parallel) {
1420                     NR::Matrix move = result * clone_move * t_inv;
1421                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1423                 } else if (prefs_unmoved) {
1424                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1425                         clone_move = NR::identity();
1426                     NR::Matrix move = result * clone_move;
1427                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1428                 }
1430             } else {
1431                 // just apply the result
1432                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1433             }
1435         } else {
1436             if (set_i2d) {
1437                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1438             }
1439             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1440         }
1442         // if we're moving the actual object, not just updating the repr, we can transform the
1443         // center by the same matrix (only necessary for non-translations)
1444         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1445             item->setCenter(old_center * affine);
1446             SP_OBJECT(item)->updateRepr();
1447         }
1448     }
1451 void sp_selection_remove_transform()
1453     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1454     if (desktop == NULL)
1455         return;
1457     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1459     GSList const *l = (GSList *) selection->reprList();
1460     while (l != NULL) {
1461         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1462         l = l->next;
1463     }
1465     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1466                      _("Remove transform"));
1469 void
1470 sp_selection_scale_absolute(Inkscape::Selection *selection,
1471                             double const x0, double const x1,
1472                             double const y0, double const y1)
1474     if (selection->isEmpty())
1475         return;
1477     NR::Rect const bbox(selection->bounds());
1478     if (bbox.isEmpty()) {
1479         return;
1480     }
1482     NR::translate const p2o(-bbox.min());
1484     NR::scale const newSize(x1 - x0,
1485                             y1 - y0);
1486     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1487     NR::translate const o2n(x0, y0);
1488     NR::Matrix const final( p2o * scale * o2n );
1490     sp_selection_apply_affine(selection, final);
1494 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1496     if (selection->isEmpty())
1497         return;
1499     NR::Rect const bbox(selection->bounds());
1501     if (bbox.isEmpty()) {
1502         return;
1503     }
1505     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1506     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1507          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1508     {
1509         return;
1510     }
1512     NR::translate const n2d(-align);
1513     NR::translate const d2n(align);
1514     NR::Matrix const final( n2d * scale * d2n );
1515     sp_selection_apply_affine(selection, final);
1518 void
1519 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1521     NR::translate const d2n(center);
1522     NR::translate const n2d(-center);
1523     NR::rotate const rotate(rotate_degrees(angle_degrees));
1524     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1525     sp_selection_apply_affine(selection, final);
1528 void
1529 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1531     NR::translate const d2n(align);
1532     NR::translate const n2d(-align);
1533     NR::Matrix const skew(1, dy,
1534                           dx, 1,
1535                           0, 0);
1536     NR::Matrix const final( n2d * skew * d2n );
1537     sp_selection_apply_affine(selection, final);
1540 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1542     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1545 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1547     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1551 /**
1552  * \brief sp_selection_rotate_90
1553  *
1554  * This function rotates selected objects 90 degrees clockwise.
1555  *
1556  */
1558 void sp_selection_rotate_90_cw()
1560     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1562     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1564     if (selection->isEmpty())
1565         return;
1567     GSList const *l = selection->itemList();
1568     NR::rotate const rot_neg_90(NR::Point(0, -1));
1569     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1570         SPItem *item = SP_ITEM(l2->data);
1571         sp_item_rotate_rel(item, rot_neg_90);
1572     }
1574     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1575                      _("Rotate 90&#176; CW"));
1579 /**
1580  * \brief sp_selection_rotate_90_ccw
1581  *
1582  * This function rotates selected objects 90 degrees counter-clockwise.
1583  *
1584  */
1586 void sp_selection_rotate_90_ccw()
1588     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1590     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1592     if (selection->isEmpty())
1593         return;
1595     GSList const *l = selection->itemList();
1596     NR::rotate const rot_neg_90(NR::Point(0, 1));
1597     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1598         SPItem *item = SP_ITEM(l2->data);
1599         sp_item_rotate_rel(item, rot_neg_90);
1600     }
1602     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1603                      _("Rotate 90&#176; CCW"));
1606 void
1607 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1609     if (selection->isEmpty())
1610         return;
1612     NR::Point center = selection->center();
1614     sp_selection_rotate_relative(selection, center, angle_degrees);
1616     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1617                            ( ( angle_degrees > 0 )
1618                              ? "selector:rotate:ccw"
1619                              : "selector:rotate:cw" ), 
1620                            SP_VERB_CONTEXT_SELECT, 
1621                            _("Rotate"));
1624 /**
1625 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1626 */
1627 void
1628 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1630     if (selection->isEmpty())
1631         return;
1633     NR::Rect const bbox(selection->bounds());
1635     NR::Point center = selection->center();
1637     gdouble const zoom = selection->desktop()->current_zoom();
1638     gdouble const zmove = angle / zoom;
1639     gdouble const r = NR::L2(bbox.max() - center);
1641     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1643     sp_selection_rotate_relative(selection, center, zangle);
1645     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1646                            ( (angle > 0)
1647                              ? "selector:rotate:ccw"
1648                              : "selector:rotate:cw" ),
1649                            SP_VERB_CONTEXT_SELECT, 
1650                            _("Rotate by pixels"));
1653 void
1654 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1656     if (selection->isEmpty())
1657         return;
1659     NR::Rect const bbox(selection->bounds());
1660     NR::Point const center(bbox.midpoint());
1661     double const max_len = bbox.maxExtent();
1663     // you can't scale "do nizhe pola" (below zero)
1664     if ( max_len + grow <= 1e-3 ) {
1665         return;
1666     }
1668     double const times = 1.0 + grow / max_len;
1669     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1671     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1672                            ( (grow > 0)
1673                              ? "selector:scale:larger"
1674                              : "selector:scale:smaller" ),
1675                            SP_VERB_CONTEXT_SELECT,
1676                            _("Scale"));
1679 void
1680 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1682     sp_selection_scale(selection,
1683                        grow_pixels / selection->desktop()->current_zoom());
1686 void
1687 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1689     if (selection->isEmpty())
1690         return;
1692     NR::Point const center(selection->bounds().midpoint());
1693     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1694     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1695                      _("Scale by whole factor"));
1698 void
1699 sp_selection_move(gdouble dx, gdouble dy)
1701     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1702     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1703     if (selection->isEmpty()) {
1704         return;
1705     }
1707     sp_selection_move_relative(selection, dx, dy);
1709     if (dx == 0) {
1710         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1711                                _("Move vertically"));
1712     } else if (dy == 0) {
1713         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1714                                _("Move horizontally"));
1715     } else {
1716         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1717                          _("Move"));
1718     }
1721 void
1722 sp_selection_move_screen(gdouble dx, gdouble dy)
1724     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1726     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1727     if (selection->isEmpty()) {
1728         return;
1729     }
1731     // same as sp_selection_move but divide deltas by zoom factor
1732     gdouble const zoom = desktop->current_zoom();
1733     gdouble const zdx = dx / zoom;
1734     gdouble const zdy = dy / zoom;
1735     sp_selection_move_relative(selection, zdx, zdy);
1737     if (dx == 0) {
1738         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1739                                _("Nudge vertically by pixels"));
1740     } else if (dy == 0) {
1741         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1742                                _("Nudge horizontally by pixels"));
1743     } else {
1744         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1745                          _("Move"));
1746     }
1749 namespace {
1751 template <typename D>
1752 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1753                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1755 template <typename D>
1756 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1757                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1759 struct Forward {
1760     typedef SPObject *Iterator;
1762     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1763     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1764     static void dispose(Iterator i) {}
1766     static SPObject *object(Iterator i) { return i; }
1767     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1768 };
1770 struct Reverse {
1771     typedef GSList *Iterator;
1773     static Iterator children(SPObject *o) {
1774         return make_list(o->firstChild(), NULL);
1775     }
1776     static Iterator siblings_after(SPObject *o) {
1777         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1778     }
1779     static void dispose(Iterator i) {
1780         g_slist_free(i);
1781     }
1783     static SPObject *object(Iterator i) {
1784         return reinterpret_cast<SPObject *>(i->data);
1785     }
1786     static Iterator next(Iterator i) { return i->next; }
1788 private:
1789     static GSList *make_list(SPObject *object, SPObject *limit) {
1790         GSList *list=NULL;
1791         while ( object != limit ) {
1792             list = g_slist_prepend(list, object);
1793             object = SP_OBJECT_NEXT(object);
1794         }
1795         return list;
1796     }
1797 };
1801 void
1802 sp_selection_item_next(void)
1804     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1805     g_return_if_fail(desktop != NULL);
1806     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1808     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1809     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1810     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1812     SPObject *root;
1813     if (PREFS_SELECTION_ALL != inlayer) {
1814         root = selection->activeContext();
1815     } else {
1816         root = desktop->currentRoot();
1817     }
1819     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1821     if (item) {
1822         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1823         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1824             scroll_to_show_item(desktop, item);
1825         }
1826     }
1829 void
1830 sp_selection_item_prev(void)
1832     SPDocument *document = SP_ACTIVE_DOCUMENT;
1833     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1834     g_return_if_fail(document != NULL);
1835     g_return_if_fail(desktop != NULL);
1836     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1838     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1839     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1840     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1842     SPObject *root;
1843     if (PREFS_SELECTION_ALL != inlayer) {
1844         root = selection->activeContext();
1845     } else {
1846         root = desktop->currentRoot();
1847     }
1849     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1851     if (item) {
1852         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1853         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1854             scroll_to_show_item(desktop, item);
1855         }
1856     }
1859 namespace {
1861 template <typename D>
1862 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1863                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1865     SPObject *current=root;
1866     while (items) {
1867         SPItem *item=SP_ITEM(items->data);
1868         if ( root->isAncestorOf(item) &&
1869              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1870         {
1871             current = item;
1872             break;
1873         }
1874         items = items->next;
1875     }
1877     GSList *path=NULL;
1878     while ( current != root ) {
1879         path = g_slist_prepend(path, current);
1880         current = SP_OBJECT_PARENT(current);
1881     }
1883     SPItem *next;
1884     // first, try from the current object
1885     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1886     g_slist_free(path);
1888     if (!next) { // if we ran out of objects, start over at the root
1889         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1890     }
1892     return next;
1895 template <typename D>
1896 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1897                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1899     typename D::Iterator children;
1900     typename D::Iterator iter;
1902     SPItem *found=NULL;
1904     if (path) {
1905         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1906         g_assert(SP_OBJECT_PARENT(object) == root);
1907         if (desktop->isLayer(object)) {
1908             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1909         }
1910         iter = children = D::siblings_after(object);
1911     } else {
1912         iter = children = D::children(root);
1913     }
1915     while ( iter && !found ) {
1916         SPObject *object=D::object(iter);
1917         if (desktop->isLayer(object)) {
1918             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1919                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1920             }
1921         } else if ( SP_IS_ITEM(object) &&
1922                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1923                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1924                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1925                     !desktop->isLayer(SP_ITEM(object)) )
1926         {
1927             found = SP_ITEM(object);
1928         }
1929         iter = D::next(iter);
1930     }
1932     D::dispose(children);
1934     return found;
1939 /**
1940  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1941  * \a item.
1942  */
1943 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1945     NR::Rect dbox = desktop->get_display_area();
1946     NR::Rect sbox = sp_item_bbox_desktop(item);
1948     if (dbox.contains(sbox) == false) {
1949         NR::Point const s_dt = sbox.midpoint();
1950         NR::Point const s_w = desktop->d2w(s_dt);
1951         NR::Point const d_dt = dbox.midpoint();
1952         NR::Point const d_w = desktop->d2w(d_dt);
1953         NR::Point const moved_w( d_w - s_w );
1954         gint const dx = (gint) moved_w[X];
1955         gint const dy = (gint) moved_w[Y];
1956         desktop->scroll_world(dx, dy);
1957     }
1961 void
1962 sp_selection_clone()
1964     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1965     if (desktop == NULL)
1966         return;
1968     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1970     // check if something is selected
1971     if (selection->isEmpty()) {
1972         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1973         return;
1974     }
1976     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1977   
1978     selection->clear();
1979   
1980     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1981     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1983     GSList *newsel = NULL;
1984  
1985     while (reprs) {
1986         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1987         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1989         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1990         sp_repr_set_attr(clone, "x", "0");
1991         sp_repr_set_attr(clone, "y", "0");
1992         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1994         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1995         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1996         
1997         // add the new clone to the top of the original's parent
1998         parent->appendChild(clone);
2000         newsel = g_slist_prepend(newsel, clone);
2001         reprs = g_slist_remove(reprs, sel_repr);
2002         Inkscape::GC::release(clone);
2003     }
2004     
2005     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2006                      _("Clone"));
2008     selection->setReprList(newsel);
2009  
2010     g_slist_free(newsel);
2013 void
2014 sp_selection_unlink()
2016     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2017     if (!desktop)
2018         return;
2020     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2022     if (selection->isEmpty()) {
2023         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2024         return;
2025     }
2027     // Get a copy of current selection.
2028     GSList *new_select = NULL;
2029     bool unlinked = false;
2030     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2031          items != NULL;
2032          items = items->next)
2033     {
2034         SPItem *use = (SPItem *) items->data;
2036         if (!SP_IS_USE(use)) {
2037             // keep the non-yse item in the new selection
2038             new_select = g_slist_prepend(new_select, use);
2039             continue;
2040         }
2042         SPItem *unlink = sp_use_unlink(SP_USE(use));
2043         unlinked = true;
2044         // Add ungrouped items to the new selection.
2045         new_select = g_slist_prepend(new_select, unlink);
2046     }
2048     if (new_select) { // set new selection
2049         selection->clear();
2050         selection->setList(new_select);
2051         g_slist_free(new_select);
2052     }
2053     if (!unlinked) {
2054         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2055     }
2057     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2058                      _("Unlink clone"));
2061 void
2062 sp_select_clone_original()
2064     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2065     if (desktop == NULL)
2066         return;
2068     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2070     SPItem *item = selection->singleItem();
2072     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.");
2074     // Check if other than two objects are selected
2075     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2076         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2077         return;
2078     }
2080     SPItem *original = NULL;
2081     if (SP_IS_USE(item)) {
2082         original = sp_use_get_original (SP_USE(item));
2083     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2084         original = sp_offset_get_source (SP_OFFSET(item));
2085     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2086         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2087     } else if (SP_IS_FLOWTEXT(item)) {
2088         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2089     } else { // it's an object that we don't know what to do with
2090         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2091         return;
2092     }
2094     if (!original) {
2095         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2096         return;
2097     }
2099     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2100         if (SP_IS_DEFS (o)) {
2101             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2102             return;
2103         }
2104     }
2106     if (original) {
2107         selection->clear();
2108         selection->set(original);
2109         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2110             scroll_to_show_item(desktop, original);
2111         }
2112     }
2115 void
2116 sp_selection_tile(bool apply)
2118     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2119     if (desktop == NULL)
2120         return;
2122     SPDocument *document = sp_desktop_document(desktop);
2124     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2126     // check if something is selected
2127     if (selection->isEmpty()) {
2128         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2129         return;
2130     }
2132     sp_document_ensure_up_to_date(document);
2133     NR::Rect r = selection->bounds();
2134     if (r.isEmpty()) {
2135         return;
2136     }
2138     // calculate the transform to be applied to objects to move them to 0,0
2139     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2140     move_p[NR::Y] = -move_p[NR::Y];
2141     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2143     GSList *items = g_slist_copy((GSList *) selection->itemList());
2145     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2147     // bottommost object, after sorting
2148     SPObject *parent = SP_OBJECT_PARENT (items->data);
2150     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2152     // remember the position of the first item
2153     gint pos = SP_OBJECT_REPR (items->data)->position();
2155     // create a list of duplicates
2156     GSList *repr_copies = NULL;
2157     for (GSList *i = items; i != NULL; i = i->next) {
2158         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2159         repr_copies = g_slist_prepend (repr_copies, dup);
2160     }
2162     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2164     if (apply) {
2165         // delete objects so that their clones don't get alerted; this object will be restored shortly
2166         for (GSList *i = items; i != NULL; i = i->next) {
2167             SPObject *item = SP_OBJECT (i->data);
2168             item->deleteObject (false);
2169         }
2170     }
2172     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2173     // without disturbing clones.
2174     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2175     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2176     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2178     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2179                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2181     // restore compensation setting
2182     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2184     if (apply) {
2185         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2186         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2188         NR::Point min = bounds.min() * parent_transform.inverse();
2189         NR::Point max = bounds.max() * parent_transform.inverse();
2191         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2192         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2193         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2194         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2196         // restore parent and position
2197         SP_OBJECT_REPR (parent)->appendChild(rect);
2198         rect->setPosition(pos > 0 ? pos : 0);
2199         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2201         Inkscape::GC::release(rect);
2203         selection->clear();
2204         selection->set(rectangle);
2205     }
2207     g_slist_free (items);
2209     sp_document_done (document, SP_VERB_EDIT_TILE, 
2210                       _("Objects to pattern"));
2213 void
2214 sp_selection_untile()
2216     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2217     if (desktop == NULL)
2218         return;
2220     SPDocument *document = sp_desktop_document(desktop);
2222     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2224     // check if something is selected
2225     if (selection->isEmpty()) {
2226         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2227         return;
2228     }
2230     GSList *new_select = NULL;
2232     bool did = false;
2234     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2235          items != NULL;
2236          items = items->next) {
2238         SPItem *item = (SPItem *) items->data;
2240         SPStyle *style = SP_OBJECT_STYLE (item);
2242         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2243             continue;
2245         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2247         if (!SP_IS_PATTERN(server))
2248             continue;
2250         did = true;
2252         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2254         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2255         pat_transform *= item->transform;
2257         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2258             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2259             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2261            // FIXME: relink clones to the new canvas objects
2262            // use SPObject::setid when mental finishes it to steal ids of
2264             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2265             sp_document_ensure_up_to_date (document);
2267             NR::Matrix transform( i->transform * pat_transform );
2268             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2270             new_select = g_slist_prepend(new_select, i);
2271         }
2273         SPCSSAttr *css = sp_repr_css_attr_new ();
2274         sp_repr_css_set_property (css, "fill", "none");
2275         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2276     }
2278     if (!did) {
2279         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2280     } else {
2281         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2282                          _("Pattern to objects"));
2283         selection->setList(new_select);
2284     }
2287 void
2288 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2290     if (selection->isEmpty()) {
2291         return;
2292     }
2294     const GSList * reprlst = selection->reprList();
2295     bool filename_search = TRUE;
2296     bool xdpi_search = TRUE;
2297     bool ydpi_search = TRUE;
2299     for(; reprlst != NULL &&
2300             filename_search &&
2301             xdpi_search &&
2302             ydpi_search;
2303         reprlst = reprlst->next) {
2304         const gchar * dpi_string;
2305         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2307         if (filename_search) {
2308             *filename = repr->attribute("inkscape:export-filename");
2309             if (*filename != NULL)
2310                 filename_search = FALSE;
2311         }
2313         if (xdpi_search) {
2314             dpi_string = NULL;
2315             dpi_string = repr->attribute("inkscape:export-xdpi");
2316             if (dpi_string != NULL) {
2317                 *xdpi = atof(dpi_string);
2318                 xdpi_search = FALSE;
2319             }
2320         }
2322         if (ydpi_search) {
2323             dpi_string = NULL;
2324             dpi_string = repr->attribute("inkscape:export-ydpi");
2325             if (dpi_string != NULL) {
2326                 *ydpi = atof(dpi_string);
2327                 ydpi_search = FALSE;
2328             }
2329         }
2330     }
2333 void
2334 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2336     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2337     const gchar * dpi_string;
2339     *filename = repr->attribute("inkscape:export-filename");
2341     dpi_string = NULL;
2342     dpi_string = repr->attribute("inkscape:export-xdpi");
2343     if (dpi_string != NULL) {
2344         *xdpi = atof(dpi_string);
2345     }
2347     dpi_string = NULL;
2348     dpi_string = repr->attribute("inkscape:export-ydpi");
2349     if (dpi_string != NULL) {
2350         *ydpi = atof(dpi_string);
2351     }
2354 void
2355 sp_selection_create_bitmap_copy ()
2357     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2358     if (desktop == NULL)
2359         return;
2361     SPDocument *document = sp_desktop_document(desktop);
2363     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2365     // check if something is selected
2366     if (selection->isEmpty()) {
2367         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2368         return;
2369     }
2371     // Get the bounding box of the selection
2372     NRRect bbox;
2373     sp_document_ensure_up_to_date (document);
2374     selection->bounds(&bbox);
2375     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2376         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2377     }
2379     // List of the items to show; all others will be hidden
2380     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2382     // Sort items so that the topmost comes last
2383     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2385     // Generate a random value from the current time (you may create bitmap from the same object(s)
2386     // multiple times, and this is done so that they don't clash)
2387     GTimeVal cu;
2388     g_get_current_time (&cu);
2389     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2391     // Create the filename
2392     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2393     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2394     // digits, and a few other chars, with "_"
2395     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2396     // Build the complete path by adding document->base if set
2397     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2399     //g_print ("%s\n", filepath);
2401     // Remember parent and z-order of the topmost one
2402     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2403     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2404     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2406     // Calculate resolution
2407     double res;
2408     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2409     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2410     if (0 < prefs_res) {
2411         // If it's given explicitly in prefs, take it
2412         res = prefs_res;
2413     } else if (0 < prefs_min) {
2414         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2415         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2416     } else {
2417         float hint_xdpi = 0, hint_ydpi = 0;
2418         const char *hint_filename;
2419         // take resolution hint from the selected objects
2420         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2421         if (hint_xdpi != 0) {
2422             res = hint_xdpi;
2423         } else {
2424             // take resolution hint from the document
2425             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2426             if (hint_xdpi != 0) {
2427                 res = hint_xdpi;
2428             } else {
2429                 // if all else fails, take the default 90 dpi
2430                 res = PX_PER_IN;
2431             }
2432         }
2433     }
2435     // The width and height of the bitmap in pixels
2436     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2437     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2439     // Find out if we have to run a filter
2440     const gchar *run = NULL;
2441     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2442     if (filter) {
2443         // filter command is given;
2444         // see if we have a parameter to pass to it
2445         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2446         if (param1) {
2447             if (param1[strlen(param1) - 1] == '%') {
2448                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2449                 gchar p1[256];
2450                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2451                 // the first param is always the image filename, the second is param1
2452                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2453             } else {
2454                 // otherwise pass the param1 unchanged
2455                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2456             }
2457         } else {
2458             // run without extra parameter
2459             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2460         }
2461     }
2463     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2464     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2465     NR::Matrix t;
2466     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2467         t = NR::scale (1, -1) * NR::translate ((unsigned) (bbox.x0 + 0.5), (unsigned) (bbox.y1 + 0.5)) * eek.inverse();
2468     } else {
2469         t = NR::scale (1, -1) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2470     }
2472     // Do the export
2473     sp_export_png_file(document, filepath,
2474                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2475                    width, height, res, res,
2476                    (guint32) 0xffffff00,
2477                    NULL, NULL,
2478                    true,  /*bool force_overwrite,*/
2479                    items);
2481     g_slist_free (items);
2483     // Run filter, if any
2484     if (run) {
2485         g_print ("Running external filter: %s\n", run);
2486         system (run);
2487     }
2489     // Import the image back
2490     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2491     if (pb) {
2492         // Create the repr for the image
2493         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2494         repr->setAttribute("xlink:href", filename);
2495         repr->setAttribute("sodipodi:absref", filepath);
2496         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2497             sp_repr_set_svg_double(repr, "width", width);
2498             sp_repr_set_svg_double(repr, "height", height);
2499         } else {
2500             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2501             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2502         }
2504         // Write transform
2505         gchar c[256];
2506         if (sp_svg_transform_write(c, 256, t)) {
2507             repr->setAttribute("transform", c);
2508         }
2510         // add the new repr to the parent
2511         parent->appendChild(repr);
2513         // move to the saved position
2514         repr->setPosition(pos > 0 ? pos + 1 : 1);
2516         // Set selection to the new image
2517         selection->clear();
2518         selection->add(repr);
2520         // Clean up
2521         Inkscape::GC::release(repr);
2522         gdk_pixbuf_unref (pb);
2524         // Complete undoable transaction
2525         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2526                           _("Create bitmap"));
2527     }
2529     g_free (filename);
2530     g_free (filepath);
2533 /**
2534  * \brief sp_selection_set_mask
2535  *
2536  * This function creates a mask or clipPath from selection
2537  * Two different modes:
2538  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2539  *       and is applied to current layer
2540  *  otherwise, topmost object is used as mask for other objects
2541  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2542  * 
2543  */
2544 void
2545 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2547     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2548     if (desktop == NULL)
2549         return;
2551     SPDocument *document = sp_desktop_document(desktop);
2552     
2553     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2555     // check if something is selected
2556     bool is_empty = selection->isEmpty();
2557     if ( apply_to_layer && is_empty) {
2558         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2559         return;
2560     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2561         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2562         return;
2563     }
2564     
2565     sp_document_ensure_up_to_date(document);
2567     GSList *items = g_slist_copy((GSList *) selection->itemList());
2568     
2569     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2571     // create a list of duplicates
2572     GSList *mask_items = NULL;
2573     GSList *apply_to_items = NULL;
2574     GSList *items_to_delete = NULL;
2575     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2576     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2577     
2578     if (apply_to_layer) {
2579         // all selected items are used for mask, which is applied to a layer
2580         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2582         for (GSList *i = items; i != NULL; i = i->next) {
2583             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2584             mask_items = g_slist_prepend (mask_items, dup);
2586             if (remove_original) {
2587                 SPObject *item = SP_OBJECT (i->data);
2588                 items_to_delete = g_slist_prepend (items_to_delete, item);
2589             }
2590         }
2591     } else if (!topmost) {
2592         // topmost item is used as a mask, which is applied to other items in a selection
2593         GSList *i = items;
2594         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2595         mask_items = g_slist_prepend (mask_items, dup);
2597         if (remove_original) {
2598             SPObject *item = SP_OBJECT (i->data);
2599             items_to_delete = g_slist_prepend (items_to_delete, item);
2600         }
2601         
2602         for (i = i->next; i != NULL; i = i->next) {
2603             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2604         }
2605     } else {
2606         GSList *i = NULL;
2607         for (i = items; NULL != i->next; i = i->next) {
2608             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2609         }
2611         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2612         mask_items = g_slist_prepend (mask_items, dup);
2614         if (remove_original) {
2615             SPObject *item = SP_OBJECT (i->data);
2616             items_to_delete = g_slist_prepend (items_to_delete, item);
2617         }
2618     }
2619     
2620     g_slist_free (items);
2621     items = NULL;
2622             
2623     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2624     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2625         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2626         // inverted object transform should be applied to a mask object,
2627         // as mask is calculated in user space (after applying transform)
2628         NR::Matrix maskTransform (item->transform.inverse());
2630         GSList *mask_items_dup = NULL;
2631         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2632             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2633             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2634         }
2636         const gchar *mask_id = NULL;
2637         if (apply_clip_path) {
2638             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2639         } else {
2640             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2641         }
2643         g_slist_free (mask_items_dup);
2644         mask_items_dup = NULL;
2646         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2647     }
2649     g_slist_free (mask_items);
2650     g_slist_free (apply_to_items);
2652     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2653         SPObject *item = SP_OBJECT (i->data);
2654         item->deleteObject (false);
2655     }
2656     g_slist_free (items_to_delete);
2658     if (apply_clip_path) 
2659         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2660     else 
2661         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2664 void sp_selection_unset_mask(bool apply_clip_path) {
2665     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2666     if (desktop == NULL)
2667         return;
2668     
2669     SPDocument *document = sp_desktop_document(desktop);    
2670     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2672     // check if something is selected
2673     if (selection->isEmpty()) {
2674         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2675         return;
2676     }
2677     
2678     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2679     sp_document_ensure_up_to_date(document);
2681     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2682     std::map<SPObject*,SPItem*> referenced_objects;
2683     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2684         if (remove_original) {
2685             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2686             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2687             Inkscape::URIReference *uri_ref = NULL;
2688         
2689             if (apply_clip_path) {
2690                 uri_ref = item->clip_ref;
2691             } else {
2692                 uri_ref = item->mask_ref;
2693             }
2695             // collect distinct mask object (and associate with item to apply transform)
2696             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2697                 referenced_objects[uri_ref->getObject()] = item;
2698             }
2699         }
2701         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2702     }
2704     // restore mask objects into a document
2705     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2706         SPObject *obj = (*it).first;
2707         GSList *items_to_move = NULL;
2708         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2709             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2710             items_to_move = g_slist_prepend (items_to_move, copy);
2711         }
2713         if (!obj->isReferenced()) {
2714             // delete from defs if no other object references this mask
2715             obj->deleteObject(false);
2716         }
2718         // remember parent and position of the item to which the clippath/mask was applied
2719         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2720         gint pos = SP_OBJECT_REPR((*it).second)->position();
2722         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2723             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2725             // insert into parent, restore pos
2726             parent->appendChild(repr);
2727             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2729             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2730             selection->add(repr);
2732             // transform mask, so it is moved the same spot where mask was applied
2733             NR::Matrix transform (mask_item->transform);
2734             transform *= (*it).second->transform;
2735             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2736         }
2738         g_slist_free (items_to_move);
2739     }
2741     if (apply_clip_path) 
2742         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2743     else 
2744         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2747 void fit_canvas_to_selection(SPDesktop *desktop) {
2748     g_return_if_fail(desktop != NULL);
2749     SPDocument *doc = sp_desktop_document(desktop);
2751     g_return_if_fail(doc != NULL);
2752     g_return_if_fail(desktop->selection != NULL);
2753     g_return_if_fail(!desktop->selection->isEmpty());
2754     NRRect bbox = {0,0,0,0};
2756     desktop->selection->bounds(&bbox);
2757     if (!empty(bbox)) {
2758         doc->fitToRect(bbox);
2759     }
2760 };
2762 void fit_canvas_to_drawing(SPDocument *doc) {
2763     g_return_if_fail(doc != NULL);
2764     NRRect bbox = {0,0,0,0};
2766     sp_document_ensure_up_to_date (doc);
2767     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2769     if (!empty(bbox)) {
2770         doc->fitToRect(bbox);
2771     }
2772 };
2774 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2775     g_return_if_fail(desktop != NULL);
2776     SPDocument *doc = sp_desktop_document(desktop);
2778     g_return_if_fail(doc != NULL);
2779     g_return_if_fail(desktop->selection != NULL);
2781     if (desktop->selection->isEmpty()) {
2782         fit_canvas_to_drawing(doc);
2783     } else {
2784         fit_canvas_to_selection(desktop);
2785     }
2787     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2788                      _("Fit page to selection"));
2789 };
2791 /*
2792   Local Variables:
2793   mode:c++
2794   c-file-style:"stroustrup"
2795   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2796   indent-tabs-mode:nil
2797   fill-column:99
2798   End:
2799 */
2800 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :