Code

Merge further bbox work
[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 "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 /**
89  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
90  * then prepends the copy to 'clip'.
91  */
92 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
93 {
94     Inkscape::XML::Node *copy = repr->duplicate();
96     // copy complete inherited style
97     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
98     sp_repr_css_set(copy, css, "style");
99     sp_repr_css_attr_unref(css);
101     // write the complete accumulated transform passed to us
102     // (we're dealing with unattached repr, so we write to its attr 
103     // instead of using sp_item_set_transform)
104     gchar *affinestr=sp_svg_transform_write(full_t);
105     copy->setAttribute("transform", affinestr);
106     g_free(affinestr);
108     *clip = g_slist_prepend(*clip, copy);
111 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
114     // Copy stuff referenced by all items to defs_clip:
115     if (defs_clip) {
116         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
117             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
118         }
119         *defs_clip = g_slist_reverse(*defs_clip);
120     }
122     // Store style:
123     if (style_clip) {
124         SPItem *item = SP_ITEM (items->data); // take from the first selected item
125         *style_clip = take_style_from_item (item);
126     }
128     if (clip) {
129         // Sort items:
130         GSList *sorted_items = g_slist_copy ((GSList *) items);
131         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
133         // Copy item reprs:
134         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
135             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
136         }
138         *clip = g_slist_reverse(*clip);
139         g_slist_free ((GSList *) sorted_items);
140     }
143 /**
144  * Add gradients/patterns/markers referenced by copied objects to defs.
145  * Iterates through 'defs_clip', and for each item it adds the data
146  * repr into the global defs.
147  */
148 void
149 paste_defs (GSList **defs_clip, SPDocument *doc)
151     if (!defs_clip)
152         return;
154     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
155         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
156         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
157         gchar const *id = repr->attribute("id");
158         if (!id || !doc->getObjectById(id)) {
159             Inkscape::XML::Node *copy = repr->duplicate();
160             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
161             Inkscape::GC::release(copy);
162         }
163     }
166 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
168     paste_defs (defs_clip, document);
170     GSList *copied = NULL;
171     // add objects to document
172     for (GSList *l = *clip; l != NULL; l = l->next) {
173         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
174         Inkscape::XML::Node *copy = repr->duplicate();
176         // premultiply the item transform by the accumulated parent transform in the paste layer
177         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
178         if (!local.test_identity()) {
179             gchar const *t_str = copy->attribute("transform");
180             NR::Matrix item_t (NR::identity());
181             if (t_str)
182                 sp_svg_transform_read(t_str, &item_t);
183             item_t *= local.inverse();
184             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
185             gchar *affinestr=sp_svg_transform_write(item_t);
186             copy->setAttribute("transform", affinestr);
187             g_free(affinestr);
188         }
190         parent->appendChildRepr(copy);
191         copied = g_slist_prepend(copied, copy);
192         Inkscape::GC::release(copy);
193     }
194     return copied;
197 void sp_selection_delete_impl(const GSList *items)
199     for (const GSList *i = items ; i ; i = i->next ) {
200         sp_object_ref((SPObject *)i->data, NULL);
201     }
202     for (const GSList *i = items; i != NULL; i = i->next) {
203         SPItem *item = (SPItem *) i->data;
204         SP_OBJECT(item)->deleteObject();
205         sp_object_unref((SPObject *)item, NULL);
206     }
210 void sp_selection_delete()
212     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
213     if (desktop == NULL) {
214         return;
215     }
217     if (tools_isactive (desktop, TOOLS_TEXT))
218         if (sp_text_delete_selection(desktop->event_context)) {
219             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
220                              _("Delete text"));
221             return;
222         }
224     Inkscape::Selection *selection = sp_desktop_selection(desktop);
226     // check if something is selected
227     if (selection->isEmpty()) {
228         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
229         return;
230     }
232     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
233     selection->clear();
234     sp_selection_delete_impl (selected);
235     g_slist_free ((GSList *) selected);
237     /* a tool may have set up private information in it's selection context
238      * that depends on desktop items.  I think the only sane way to deal with
239      * this currently is to reset the current tool, which will reset it's
240      * associated selection context.  For example: deleting an object
241      * while moving it around the canvas.
242      */
243     tools_switch ( desktop, tools_active ( desktop ) );
245     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
246                      _("Delete"));
249 /* fixme: sequencing */
250 void sp_selection_duplicate()
252     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
253     if (desktop == NULL)
254         return;
256     Inkscape::Selection *selection = sp_desktop_selection(desktop);
258     // check if something is selected
259     if (selection->isEmpty()) {
260         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
261         return;
262     }
264     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
266     selection->clear();
268     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
269     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
271     GSList *newsel = NULL;
273     while (reprs) {
274         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
275         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
277         parent->appendChild(copy);
279         newsel = g_slist_prepend(newsel, copy);
280         reprs = g_slist_remove(reprs, reprs->data);
281         Inkscape::GC::release(copy);
282     }
284     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
285                      _("Duplicate"));
287     selection->setReprList(newsel);
289     g_slist_free(newsel);
292 void sp_edit_clear_all()
294     SPDesktop *dt = SP_ACTIVE_DESKTOP;
295     if (!dt)
296         return;
298     SPDocument *doc = sp_desktop_document(dt);
299     sp_desktop_selection(dt)->clear();
301     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
302     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
304     while (items) {
305         SP_OBJECT (items->data)->deleteObject();
306         items = g_slist_remove(items, items->data);
307     }
309     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
310                      _("Delete all"));
313 GSList *
314 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
316     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
317         if (SP_IS_ITEM(child) &&
318             !desktop->isLayer(SP_ITEM(child)) &&
319             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
320             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
321             (!exclude || !g_slist_find ((GSList *) exclude, child))
322             )
323         {
324             list = g_slist_prepend (list, SP_ITEM(child));
325         }
327         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
328             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
329         }
330     }
332     return list;
335 void sp_edit_select_all_full (bool force_all_layers, bool invert)
337     SPDesktop *dt = SP_ACTIVE_DESKTOP;
338     if (!dt)
339         return;
341     Inkscape::Selection *selection = sp_desktop_selection(dt);
343     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
345     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
346     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
347     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
349     GSList *items = NULL;
351     const GSList *exclude = NULL;
352     if (invert) {
353         exclude = selection->itemList();
354     }
356     if (force_all_layers)
357         inlayer = PREFS_SELECTION_ALL;
359     switch (inlayer) {
360         case PREFS_SELECTION_LAYER: {
361         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
362              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
363         return;
365         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
367         for (GSList *i = all_items; i; i = i->next) {
368             SPItem *item = SP_ITEM (i->data);
370             if (item && (!onlysensitive || !item->isLocked())) {
371                 if (!onlyvisible || !dt->itemIsHidden(item)) {
372                     if (!dt->isLayer(item)) {
373                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
374                             items = g_slist_prepend (items, item); // leave it in the list
375                         }
376                     }
377                 }
378             }
379         }
381         g_slist_free (all_items);
382             break;
383         }
384         case PREFS_SELECTION_LAYER_RECURSIVE: {
385             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
386             break;
387         }
388         default: {
389         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
390             break;
391     }
392     }
394     selection->setList (items);
396     if (items) {
397         g_slist_free (items);
398     }
401 void sp_edit_select_all ()
403     sp_edit_select_all_full (false, false);
406 void sp_edit_select_all_in_all_layers ()
408     sp_edit_select_all_full (true, false);
411 void sp_edit_invert ()
413     sp_edit_select_all_full (false, true);
416 void sp_edit_invert_in_all_layers ()
418     sp_edit_select_all_full (true, true);
421 void sp_selection_group()
423     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
424     if (desktop == NULL)
425         return;
427     SPDocument *document = sp_desktop_document (desktop);
428     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
430     Inkscape::Selection *selection = sp_desktop_selection(desktop);
432     // Check if something is selected.
433     if (selection->isEmpty()) {
434         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
435         return;
436     }
438     GSList const *l = (GSList *) selection->reprList();
440     GSList *p = g_slist_copy((GSList *) l);
442     selection->clear();
444     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
446     // Remember the position and parent of the topmost object.
447     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
448     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
450     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
452     while (p) {
453         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
455         if (current->parent() == topmost_parent) {
456             Inkscape::XML::Node *spnew = current->duplicate();
457             sp_repr_unparent(current);
458             group->appendChild(spnew);
459             Inkscape::GC::release(spnew);
460             topmost --; // only reduce count for those items deleted from topmost_parent
461         } else { // move it to topmost_parent first
462                 GSList *temp_clip = NULL;
464                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
465                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
466                 gchar const *t_str = current->attribute("transform");
467                 NR::Matrix item_t (NR::identity());
468                 if (t_str)
469                     sp_svg_transform_read(t_str, &item_t);
470                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
471                 //FIXME: when moving both clone and original from a transformed group (either by
472                 //grouping into another parent, or by cut/paste) the transform from the original's
473                 //parent becomes embedded into original itself, and this affects its clones. Fix
474                 //this by remembering the transform diffs we write to each item into an array and
475                 //then, if this is clone, looking up its original in that array and pre-multiplying
476                 //it by the inverse of that original's transform diff.
478                 sp_selection_copy_one (current, item_t, &temp_clip);
479                 sp_repr_unparent(current);
481                 // paste into topmost_parent (temporarily)
482                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
483                 if (temp_clip) g_slist_free (temp_clip);
484                 if (copied) { // if success,
485                     // take pasted object (now in topmost_parent)
486                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
487                     // make a copy
488                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
489                     // remove pasted
490                     sp_repr_unparent(in_topmost);
491                     // put its copy into group
492                     group->appendChild(spnew);
493                     Inkscape::GC::release(spnew);
494                     g_slist_free (copied);
495                 }
496         }
497         p = g_slist_remove(p, current);
498     }
500     // Add the new group to the topmost members' parent
501     topmost_parent->appendChild(group);
503     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
504     group->setPosition(topmost + 1);
506     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
507                      _("Group"));
509     selection->set(group);
510     Inkscape::GC::release(group);
513 void sp_selection_ungroup()
515     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
516     if (desktop == NULL)
517         return;
519     Inkscape::Selection *selection = sp_desktop_selection(desktop);
521     if (selection->isEmpty()) {
522         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
523         return;
524     }
526     GSList *items = g_slist_copy((GSList *) selection->itemList());
527     selection->clear();
529     // Get a copy of current selection.
530     GSList *new_select = NULL;
531     bool ungrouped = false;
532     for (GSList *i = items;
533          i != NULL;
534          i = i->next)
535     {
536         SPItem *group = (SPItem *) i->data;
538         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
539         if (!SP_IS_OBJECT(group)) {
540             continue;
541         }
543         /* We do not allow ungrouping <svg> etc. (lauris) */
544         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
545             // keep the non-group item in the new selection
546             selection->add(group);
547             continue;
548         }
550         GSList *children = NULL;
551         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
552         sp_item_group_ungroup(SP_GROUP(group), &children, false);
553         ungrouped = true;
554         // Add ungrouped items to the new selection.
555         new_select = g_slist_concat(new_select, children);
556     }
558     if (new_select) { // Set new selection.
559         selection->addList(new_select);
560         g_slist_free(new_select);
561     }
562     if (!ungrouped) {
563         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
564     }
566     g_slist_free(items);
568     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
569                      _("Ungroup"));
572 static SPGroup *
573 sp_item_list_common_parent_group(const GSList *items)
575     if (!items) {
576         return NULL;
577     }
578     SPObject *parent = SP_OBJECT_PARENT(items->data);
579     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
580     if (!SP_IS_GROUP(parent)) {
581         return NULL;
582     }
583     for (items = items->next; items; items = items->next) {
584         if (SP_OBJECT_PARENT(items->data) != parent) {
585             return NULL;
586         }
587     }
589     return SP_GROUP(parent);
592 /** Finds out the minimum common bbox of the selected items
593  */
594 static NR::Maybe<NR::Rect>
595 enclose_items(const GSList *items)
597     g_assert(items != NULL);
599     NR::Maybe<NR::Rect> r = NR::Nothing();
600     for (GSList const *i = items; i; i = i->next) {
601         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
602     }
603     return r;
606 SPObject *
607 prev_sibling(SPObject *child)
609     SPObject *parent = SP_OBJECT_PARENT(child);
610     if (!SP_IS_GROUP(parent)) {
611         return NULL;
612     }
613     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
614         if (i->next == child)
615             return i;
616     }
617     return NULL;
620 void
621 sp_selection_raise()
623     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
624     if (!desktop)
625         return;
627     Inkscape::Selection *selection = sp_desktop_selection(desktop);
629     GSList const *items = (GSList *) selection->itemList();
630     if (!items) {
631         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
632         return;
633     }
635     SPGroup const *group = sp_item_list_common_parent_group(items);
636     if (!group) {
637         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
638         return;
639     }
641     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
643     /* construct reverse-ordered list of selected children */
644     GSList *rev = g_slist_copy((GSList *) items);
645     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
647     // find out the common bbox of the selected items
648     NR::Maybe<NR::Rect> selected = enclose_items(items);
650     // for all objects in the selection (starting from top)
651     if (selected) {
652         while (rev) {
653             SPObject *child = SP_OBJECT(rev->data);
654             // for each selected object, find the next sibling
655             for (SPObject *newref = child->next; newref; newref = newref->next) {
656                 // if the sibling is an item AND overlaps our selection,
657                 if (SP_IS_ITEM(newref)) {
658                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
659                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
660                         // AND if it's not one of our selected objects,
661                         if (!g_slist_find((GSList *) items, newref)) {
662                             // move the selected object after that sibling
663                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
664                         }
665                         break;
666                     }
667                 }
668             }
669             rev = g_slist_remove(rev, child);
670         }
671     } else {
672         g_slist_free(rev);
673     }
675     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
676                      _("Raise"));
679 void sp_selection_raise_to_top()
681     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
682     if (desktop == NULL)
683         return;
685     SPDocument *document = sp_desktop_document(desktop);
686     Inkscape::Selection *selection = sp_desktop_selection(desktop);
688     if (selection->isEmpty()) {
689         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
690         return;
691     }
693     GSList const *items = (GSList *) selection->itemList();
695     SPGroup const *group = sp_item_list_common_parent_group(items);
696     if (!group) {
697         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
698         return;
699     }
701     GSList *rl = g_slist_copy((GSList *) selection->reprList());
702     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
704     for (GSList *l = rl; l != NULL; l = l->next) {
705         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
706         repr->setPosition(-1);
707     }
709     g_slist_free(rl);
711     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
712                      _("Raise to top"));
715 void
716 sp_selection_lower()
718     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
719     if (desktop == NULL)
720         return;
722     Inkscape::Selection *selection = sp_desktop_selection(desktop);
724     GSList const *items = (GSList *) selection->itemList();
725     if (!items) {
726         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
727         return;
728     }
730     SPGroup const *group = sp_item_list_common_parent_group(items);
731     if (!group) {
732         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
733         return;
734     }
736     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
738     // find out the common bbox of the selected items
739     NR::Maybe<NR::Rect> selected = enclose_items(items);
741     /* construct direct-ordered list of selected children */
742     GSList *rev = g_slist_copy((GSList *) items);
743     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
744     rev = g_slist_reverse(rev);
746     // for all objects in the selection (starting from top)
747     if (selected) {
748         while (rev) {
749             SPObject *child = SP_OBJECT(rev->data);
750             // for each selected object, find the prev sibling
751             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
752                 // if the sibling is an item AND overlaps our selection,
753                 if (SP_IS_ITEM(newref)) {
754                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
755                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
756                         // AND if it's not one of our selected objects,
757                         if (!g_slist_find((GSList *) items, newref)) {
758                             // move the selected object before that sibling
759                             SPObject *put_after = prev_sibling(newref);
760                             if (put_after)
761                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
762                             else
763                                 SP_OBJECT_REPR(child)->setPosition(0);
764                         }
765                         break;
766                     }
767                 }
768             }
769             rev = g_slist_remove(rev, child);
770         }
771     } else {
772         g_slist_free(rev);
773     }
775     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
776                      _("Lower"));
779 void sp_selection_lower_to_bottom()
781     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
782     if (desktop == NULL)
783         return;
785     SPDocument *document = sp_desktop_document(desktop);
786     Inkscape::Selection *selection = sp_desktop_selection(desktop);
788     if (selection->isEmpty()) {
789         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
790         return;
791     }
793     GSList const *items = (GSList *) selection->itemList();
795     SPGroup const *group = sp_item_list_common_parent_group(items);
796     if (!group) {
797         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
798         return;
799     }
801     GSList *rl;
802     rl = g_slist_copy((GSList *) selection->reprList());
803     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
804     rl = g_slist_reverse(rl);
806     for (GSList *l = rl; l != NULL; l = l->next) {
807         gint minpos;
808         SPObject *pp, *pc;
809         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
810         pp = document->getObjectByRepr(sp_repr_parent(repr));
811         minpos = 0;
812         g_assert(SP_IS_GROUP(pp));
813         pc = sp_object_first_child(pp);
814         while (!SP_IS_ITEM(pc)) {
815             minpos += 1;
816             pc = pc->next;
817         }
818         repr->setPosition(minpos);
819     }
821     g_slist_free(rl);
823     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
824                      _("Lower to bottom"));
827 void
828 sp_undo(SPDesktop *desktop, SPDocument *)
830         if (!sp_document_undo(sp_desktop_document(desktop)))
831             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
834 void
835 sp_redo(SPDesktop *desktop, SPDocument *)
837         if (!sp_document_redo(sp_desktop_document(desktop)))
838             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
841 void sp_selection_cut()
843     sp_selection_copy();
844     sp_selection_delete();
847 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
849     SPGradient *ref = gradient;
851     while (ref) {
852         // climb up the refs, copying each one in the chain
853         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
854         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
856         ref = ref->ref->getObject();
857     }
860 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
862     SPPattern *ref = pattern;
864     while (ref) {
865         // climb up the refs, copying each one in the chain
866         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
867         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
869         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
870         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
871             if (!SP_IS_ITEM (child))
872                 continue;
873             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
874         }
876         ref = ref->ref->getObject();
877     }
880 void sp_copy_single (GSList **defs_clip, SPObject *thing)
882     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
883     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
887 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
889     SPItem *path = sp_textpath_get_path_item (tp);
890     if (!path)
891         return;
892     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
893         return;
894     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
895     *defs_clip = g_slist_prepend (*defs_clip, repr);
898 /**
899  * Copies things like patterns, markers, gradients, etc.
900  */
901 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
903     SPStyle *style = SP_OBJECT_STYLE (item);
905     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
906         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
907         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
908             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
909         if (SP_IS_PATTERN (server))
910             sp_copy_pattern (defs_clip, SP_PATTERN(server));
911     }
913     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
914         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
915         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
916             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
917         if (SP_IS_PATTERN (server))
918             sp_copy_pattern (defs_clip, SP_PATTERN(server));
919     }
921     // For shapes, copy all of the shape's markers into defs_clip
922     if (SP_IS_SHAPE (item)) {
923         SPShape *shape = SP_SHAPE (item);
924         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
925             if (shape->marker[i]) {
926                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
927             }
928         }
929     }
931     if (SP_IS_TEXT_TEXTPATH (item)) {
932         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
933     }
935     if (item->clip_ref->getObject()) {
936         sp_copy_single (defs_clip, item->clip_ref->getObject());
937     }
939     if (item->mask_ref->getObject()) {
940         SPObject *mask = item->mask_ref->getObject();
941         sp_copy_single (defs_clip, mask);
942         // recurse into the mask for its gradients etc.
943         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
944             if (SP_IS_ITEM(o))
945                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
946         }
947     }
949     if (style->filter.filter) {
950         SPObject *filter = style->filter.filter;
951         if (SP_IS_FILTER(filter)) {
952             sp_copy_single (defs_clip, filter);
953         }
954     }
956     // recurse
957     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
958         if (SP_IS_ITEM(o))
959             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
960     }
963 /**
964  * \pre item != NULL
965  */
966 SPCSSAttr *
967 take_style_from_item (SPItem *item)
969     // write the complete cascaded style, context-free
970     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
971     if (css == NULL)
972         return NULL;
974     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
975         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
976         // if this is a text with exactly one tspan child, merge the style of that tspan as well
977         // If this is a group, merge the style of its topmost (last) child with style
978         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
979             if (SP_OBJECT_STYLE (last_element) != NULL) {
980                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
981                 if (temp) {
982                     sp_repr_css_merge (css, temp);
983                     sp_repr_css_attr_unref (temp);
984                 }
985                 break;
986             }
987         }
988     }
989     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
990         // do not copy text properties from non-text objects, it's confusing
991         css = sp_css_attr_unset_text (css);
992     }
994     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
995     double ex = NR::expansion(sp_item_i2doc_affine(item));
996     if (ex != 1.0) {
997         css = sp_css_attr_scale (css, ex);
998     }
1000     return css;
1004 void sp_selection_copy()
1006     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1007     if (desktop == NULL)
1008         return;
1010     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1012     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1013         sp_dropper_context_copy(desktop->event_context);
1014         return; // copied color under cursor, nothing else to do
1015     }
1017     // check if something is selected
1018     if (selection->isEmpty()) {
1019         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1020         return;
1021     }
1023     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1025     // 0. Copy text to system clipboard
1026     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1027     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1028     Glib::ustring text;
1029     if (tools_isactive (desktop, TOOLS_TEXT)) {
1030         text = sp_text_get_selected_text(desktop->event_context);
1031     }
1033     if (text.empty()) {
1034         guint texts = 0;
1035         for (GSList *i = (GSList *) items; i; i = i->next) {
1036             SPItem *item = SP_ITEM (i->data);
1037             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1038                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1039                     text += " ";
1040                 gchar *this_text = sp_te_get_string_multiline (item);
1041                 if (this_text) {
1042                     text += this_text;
1043                     g_free(this_text);
1044                 }
1045                 texts++;
1046             }
1047         }
1048     }
1049     if (!text.empty()) {
1050         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1051         refClipboard->set_text(text);
1052     }
1054     // clear old defs clipboard
1055     while (defs_clipboard) {
1056         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1057         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1058     }
1060     // clear style clipboard
1061     if (style_clipboard) {
1062         sp_repr_css_attr_unref (style_clipboard);
1063         style_clipboard = NULL;
1064     }
1066     //clear main clipboard
1067     while (clipboard) {
1068         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1069         clipboard = g_slist_remove(clipboard, clipboard->data);
1070     }
1072     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1074     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1075         SPStyle *const query = sp_style_new();
1076         if (sp_desktop_query_style_all (desktop, query)) {
1077             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1078             if (css != NULL) {
1079                 // clear style clipboard
1080                 if (style_clipboard) {
1081                     sp_repr_css_attr_unref (style_clipboard);
1082                     style_clipboard = NULL;
1083                 }
1084                 //sp_repr_css_print (css);
1085                 style_clipboard = css;
1086             }
1087         }
1088         g_free (query);
1089     }
1091     size_clipboard = selection->bounds();
1093     g_slist_free ((GSList *) items);
1096 void sp_selection_paste(bool in_place)
1098     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1100     if (desktop == NULL) {
1101         return;
1102     }
1104     SPDocument *document = sp_desktop_document(desktop);
1106     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1107         return;
1108     }
1110     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1112     if (tools_isactive (desktop, TOOLS_TEXT)) {
1113         if (sp_text_paste_inline(desktop->event_context))
1114             return; // pasted from system clipboard into text, nothing else to do
1115     }
1117     // check if something is in the clipboard
1118     if (clipboard == NULL) {
1119         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1120         return;
1121     }
1123     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1124     // add pasted objects to selection
1125     selection->setReprList((GSList const *) copied);
1126     g_slist_free (copied);
1128     if (!in_place) {
1129         sp_document_ensure_up_to_date(document);
1131         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1133         /* Snap the offset of the new item(s) to the grid */
1134         /* FIXME: this gridsnap fiddling is a hack. */
1135         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1136         gdouble const curr_gridsnap = s.getDistance();
1137         s.setDistance(NR_HUGE);
1138         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1139         s.setDistance(curr_gridsnap);
1140         sp_selection_move_relative(selection, m);
1141     }
1143     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1144                      _("Paste"));
1147 void sp_selection_paste_style()
1149     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1150     if (desktop == NULL) return;
1152     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1154     // check if something is in the clipboard
1155     if (clipboard == NULL) {
1156         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1157         return;
1158     }
1160     // check if something is selected
1161     if (selection->isEmpty()) {
1162         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1163         return;
1164     }
1166     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1168     sp_desktop_set_style (desktop, style_clipboard);
1170     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1171                      _("Paste style"));
1174 void sp_selection_paste_size (bool apply_x, bool apply_y)
1176     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1177     if (desktop == NULL) return;
1179     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1181     // check if something is in the clipboard
1182     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1183         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1184         return;
1185     }
1187     // check if something is selected
1188     if (selection->isEmpty()) {
1189         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1190         return;
1191     }
1193     NR::Rect current = selection->bounds();
1194     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1195         return;
1196     }
1198     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1199     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1201     sp_selection_scale_relative (selection, current.midpoint(), 
1202                                  NR::scale(
1203                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1204                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1206     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1207                      _("Paste size"));
1210 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1212     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1213     if (desktop == NULL) return;
1215     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1217     // check if something is in the clipboard
1218     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1219         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1220         return;
1221     }
1223     // check if something is selected
1224     if (selection->isEmpty()) {
1225         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1226         return;
1227     }
1229     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1230         SPItem *item = SP_ITEM(l->data);
1232         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1233         if ( !current || current->extent(NR::X) < 1e-6 || current->extent(NR::Y) < 1e-6 ) {
1234             continue;
1235         }
1237         double scale_x = size_clipboard.extent(NR::X) / current->extent(NR::X);
1238         double scale_y = size_clipboard.extent(NR::Y) / current->extent(NR::Y);
1240         sp_item_scale_rel (item,
1241                                  NR::scale(
1242                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1243                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1245     }
1247     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1248                      _("Paste size separately"));
1251 void sp_selection_to_next_layer ()
1253     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1255     Inkscape::Selection *selection = sp_desktop_selection(dt);
1257     // check if something is selected
1258     if (selection->isEmpty()) {
1259         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1260         return;
1261     }
1263     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1265     bool no_more = false; // Set to true, if no more layers above
1266     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1267     if (next) {
1268         GSList *temp_clip = NULL;
1269         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1270         sp_selection_delete_impl (items);
1271         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1272         GSList *copied;
1273         if(next) {
1274             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1275         } else {
1276             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1277             no_more = true;
1278         }
1279         selection->setReprList((GSList const *) copied);
1280         g_slist_free (copied);
1281         if (temp_clip) g_slist_free (temp_clip);
1282         if (next) dt->setCurrentLayer(next);
1283         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1284                          _("Raise to next layer"));
1285     } else {
1286         no_more = true;
1287     }
1289     if (no_more) {
1290         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1291     }
1293     g_slist_free ((GSList *) items);
1296 void sp_selection_to_prev_layer ()
1298     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1300     Inkscape::Selection *selection = sp_desktop_selection(dt);
1302     // check if something is selected
1303     if (selection->isEmpty()) {
1304         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1305         return;
1306     }
1308     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1310     bool no_more = false; // Set to true, if no more layers below
1311     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1312     if (next) {
1313         GSList *temp_clip = NULL;
1314         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1315         sp_selection_delete_impl (items);
1316         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1317         GSList *copied;
1318         if(next) {
1319             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1320         } else {
1321             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1322             no_more = true;
1323         }
1324         selection->setReprList((GSList const *) copied);
1325         g_slist_free (copied);
1326         if (temp_clip) g_slist_free (temp_clip);
1327         if (next) dt->setCurrentLayer(next);
1328         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1329                          _("Lower to previous layer"));
1330     } else {
1331         no_more = true;
1332     }
1334     if (no_more) {
1335         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1336     }
1338     g_slist_free ((GSList *) items);
1341 bool
1342 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1344     bool contains_original = false;
1345     bool is_use = SP_IS_USE(item);
1346     SPItem *item_use = item;
1347     SPItem *item_use_first = item;
1348     while (is_use && item_use && !contains_original)
1349     {
1350         item_use = sp_use_get_original (SP_USE(item_use));
1351         contains_original |= selection->includes(item_use);
1352         if (item_use == item_use_first)
1353             break;
1354         is_use = SP_IS_USE(item_use);
1355     }   
1356     return contains_original;
1360 bool
1361 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1363     bool clone_with_original = false;
1364     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1365         SPItem *item = SP_ITEM(l->data);
1366         clone_with_original |= selection_contains_original(item, selection);
1367         if (clone_with_original) 
1368             break;
1369     }
1370     return clone_with_original;
1374 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1375 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1376 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1377 that case, items are already in the new position, but the repr is in the old, and this function
1378 then simply updates the repr from item->transform.
1379  */
1380 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1382     if (selection->isEmpty())
1383         return;
1385     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1386         SPItem *item = SP_ITEM(l->data);
1388         NR::Point old_center(0,0);
1389         if (set_i2d && item->isCenterSet())
1390             old_center = item->getCenter();
1392 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1393          At the time of writing, this is the only place to re-enable. */
1394         sp_item_update_cns(*item, selection->desktop());
1395 #endif
1397         // we're moving both a clone and its original or any ancestor in clone chain?
1398         bool transform_clone_with_original = selection_contains_original(item, selection);
1399         // ...both a text-on-path and its path?
1400         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)))) ));
1401         // ...both a flowtext and its frame?
1402         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // (only the first frame is checked so far)
1403         // ...both an offset and its source?
1404         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1405        
1406         // If we're moving a connector, we want to detach it
1407         // from shapes that aren't part of the selection, but
1408         // leave it attached if they are
1409         if (cc_item_is_connector(item)) {
1410             SPItem *attItem[2];
1411             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1412             
1413             for (int n = 0; n < 2; ++n) {
1414                 if (!selection->includes(attItem[n])) {
1415                     sp_conn_end_detach(item, n);
1416                 }
1417             }
1418         }
1419         
1420         // "clones are unmoved when original is moved" preference
1421         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1422         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1423         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1425         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1426         // transform of its original and respond to it itself. Without this, a clone is doubly
1427         // transformed, very unintuitive.
1428       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1429       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1430       // Same for linked offset if we are also moving its source: do not move it.
1431         if (transform_textpath_with_path || transform_offset_with_source) {
1432                 // restore item->transform field from the repr, in case it was changed by seltrans
1433             sp_object_read_attr (SP_OBJECT (item), "transform");
1435         } else if (transform_flowtext_with_frame) {
1436             // apply the inverse of the region's transform to the <use> so that the flow remains
1437             // the same (even though the output itself gets transformed)
1438             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1439                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1440                     continue;
1441                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1442                     if (!SP_IS_USE(use)) continue;
1443                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1444                 }
1445             }
1446         } else if (transform_clone_with_original) {
1447             // We are transforming a clone along with its original. The below matrix juggling is
1448             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1449             // transform and its move compensation are both cancelled out.
1451             // restore item->transform field from the repr, in case it was changed by seltrans
1452             sp_object_read_attr (SP_OBJECT (item), "transform");
1454             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1455             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1456             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1457             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1458             NR::Matrix result = t_inv * item->transform * t;
1460             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1461                 // we need to cancel out the move compensation, too
1463                 // find out the clone move, same as in sp_use_move_compensate
1464                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1465                 NR::Matrix clone_move = parent.inverse() * t * parent;
1467                 if (prefs_parallel) {
1468                     NR::Matrix move = result * clone_move * t_inv;
1469                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1471                 } else if (prefs_unmoved) {
1472                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1473                     //    clone_move = NR::identity();
1474                     NR::Matrix move = result * clone_move;
1475                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1476                 }
1478             } else {
1479                 // just apply the result
1480                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1481             }
1483         } else {
1484             if (set_i2d) {
1485                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1486             }
1487             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1488         }
1490         // if we're moving the actual object, not just updating the repr, we can transform the
1491         // center by the same matrix (only necessary for non-translations)
1492         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1493             item->setCenter(old_center * affine);
1494             SP_OBJECT(item)->updateRepr();
1495         }
1496     }
1499 void sp_selection_remove_transform()
1501     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1502     if (desktop == NULL)
1503         return;
1505     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1507     GSList const *l = (GSList *) selection->reprList();
1508     while (l != NULL) {
1509         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1510         l = l->next;
1511     }
1513     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1514                      _("Remove transform"));
1517 void
1518 sp_selection_scale_absolute(Inkscape::Selection *selection,
1519                             double const x0, double const x1,
1520                             double const y0, double const y1)
1522     if (selection->isEmpty())
1523         return;
1525     NR::Rect const bbox(selection->bounds());
1526     if (bbox.isEmpty()) {
1527         return;
1528     }
1530     NR::translate const p2o(-bbox.min());
1532     NR::scale const newSize(x1 - x0,
1533                             y1 - y0);
1534     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1535     NR::translate const o2n(x0, y0);
1536     NR::Matrix const final( p2o * scale * o2n );
1538     sp_selection_apply_affine(selection, final);
1542 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1544     if (selection->isEmpty())
1545         return;
1547     NR::Rect const bbox(selection->bounds());
1549     if (bbox.isEmpty()) {
1550         return;
1551     }
1553     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1554     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1555          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1556     {
1557         return;
1558     }
1560     NR::translate const n2d(-align);
1561     NR::translate const d2n(align);
1562     NR::Matrix const final( n2d * scale * d2n );
1563     sp_selection_apply_affine(selection, final);
1566 void
1567 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1569     NR::translate const d2n(center);
1570     NR::translate const n2d(-center);
1571     NR::rotate const rotate(rotate_degrees(angle_degrees));
1572     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1573     sp_selection_apply_affine(selection, final);
1576 void
1577 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1579     NR::translate const d2n(align);
1580     NR::translate const n2d(-align);
1581     NR::Matrix const skew(1, dy,
1582                           dx, 1,
1583                           0, 0);
1584     NR::Matrix const final( n2d * skew * d2n );
1585     sp_selection_apply_affine(selection, final);
1588 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1590     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1593 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1595     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1599 /**
1600  * \brief sp_selection_rotate_90
1601  *
1602  * This function rotates selected objects 90 degrees clockwise.
1603  *
1604  */
1606 void sp_selection_rotate_90_cw()
1608     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1610     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1612     if (selection->isEmpty())
1613         return;
1615     GSList const *l = selection->itemList();
1616     NR::rotate const rot_neg_90(NR::Point(0, -1));
1617     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1618         SPItem *item = SP_ITEM(l2->data);
1619         sp_item_rotate_rel(item, rot_neg_90);
1620     }
1622     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1623                      _("Rotate 90&#176; CW"));
1627 /**
1628  * \brief sp_selection_rotate_90_ccw
1629  *
1630  * This function rotates selected objects 90 degrees counter-clockwise.
1631  *
1632  */
1634 void sp_selection_rotate_90_ccw()
1636     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1638     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1640     if (selection->isEmpty())
1641         return;
1643     GSList const *l = selection->itemList();
1644     NR::rotate const rot_neg_90(NR::Point(0, 1));
1645     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1646         SPItem *item = SP_ITEM(l2->data);
1647         sp_item_rotate_rel(item, rot_neg_90);
1648     }
1650     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1651                      _("Rotate 90&#176; CCW"));
1654 void
1655 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1657     if (selection->isEmpty())
1658         return;
1660     NR::Point center = selection->center();
1662     sp_selection_rotate_relative(selection, center, angle_degrees);
1664     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1665                            ( ( angle_degrees > 0 )
1666                              ? "selector:rotate:ccw"
1667                              : "selector:rotate:cw" ), 
1668                            SP_VERB_CONTEXT_SELECT, 
1669                            _("Rotate"));
1672 /**
1673 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1674 */
1675 void
1676 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1678     if (selection->isEmpty())
1679         return;
1681     NR::Rect const bbox(selection->bounds());
1683     NR::Point center = selection->center();
1685     gdouble const zoom = selection->desktop()->current_zoom();
1686     gdouble const zmove = angle / zoom;
1687     gdouble const r = NR::L2(bbox.max() - center);
1689     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1691     sp_selection_rotate_relative(selection, center, zangle);
1693     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1694                            ( (angle > 0)
1695                              ? "selector:rotate:ccw"
1696                              : "selector:rotate:cw" ),
1697                            SP_VERB_CONTEXT_SELECT, 
1698                            _("Rotate by pixels"));
1701 void
1702 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1704     if (selection->isEmpty())
1705         return;
1707     NR::Rect const bbox(selection->bounds());
1708     NR::Point const center(bbox.midpoint());
1709     double const max_len = bbox.maxExtent();
1711     // you can't scale "do nizhe pola" (below zero)
1712     if ( max_len + grow <= 1e-3 ) {
1713         return;
1714     }
1716     double const times = 1.0 + grow / max_len;
1717     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1719     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1720                            ( (grow > 0)
1721                              ? "selector:scale:larger"
1722                              : "selector:scale:smaller" ),
1723                            SP_VERB_CONTEXT_SELECT,
1724                            _("Scale"));
1727 void
1728 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1730     sp_selection_scale(selection,
1731                        grow_pixels / selection->desktop()->current_zoom());
1734 void
1735 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1737     if (selection->isEmpty())
1738         return;
1740     NR::Point const center(selection->bounds().midpoint());
1741     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1742     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1743                      _("Scale by whole factor"));
1746 void
1747 sp_selection_move(gdouble dx, gdouble dy)
1749     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1750     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1751     if (selection->isEmpty()) {
1752         return;
1753     }
1755     sp_selection_move_relative(selection, dx, dy);
1757     if (dx == 0) {
1758         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1759                                _("Move vertically"));
1760     } else if (dy == 0) {
1761         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1762                                _("Move horizontally"));
1763     } else {
1764         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1765                          _("Move"));
1766     }
1769 void
1770 sp_selection_move_screen(gdouble dx, gdouble dy)
1772     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1774     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1775     if (selection->isEmpty()) {
1776         return;
1777     }
1779     // same as sp_selection_move but divide deltas by zoom factor
1780     gdouble const zoom = desktop->current_zoom();
1781     gdouble const zdx = dx / zoom;
1782     gdouble const zdy = dy / zoom;
1783     sp_selection_move_relative(selection, zdx, zdy);
1785     if (dx == 0) {
1786         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1787                                _("Move vertically by pixels"));
1788     } else if (dy == 0) {
1789         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1790                                _("Move horizontally by pixels"));
1791     } else {
1792         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1793                          _("Move"));
1794     }
1797 namespace {
1799 template <typename D>
1800 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1801                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1803 template <typename D>
1804 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1805                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1807 struct Forward {
1808     typedef SPObject *Iterator;
1810     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1811     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1812     static void dispose(Iterator i) {}
1814     static SPObject *object(Iterator i) { return i; }
1815     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1816 };
1818 struct Reverse {
1819     typedef GSList *Iterator;
1821     static Iterator children(SPObject *o) {
1822         return make_list(o->firstChild(), NULL);
1823     }
1824     static Iterator siblings_after(SPObject *o) {
1825         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1826     }
1827     static void dispose(Iterator i) {
1828         g_slist_free(i);
1829     }
1831     static SPObject *object(Iterator i) {
1832         return reinterpret_cast<SPObject *>(i->data);
1833     }
1834     static Iterator next(Iterator i) { return i->next; }
1836 private:
1837     static GSList *make_list(SPObject *object, SPObject *limit) {
1838         GSList *list=NULL;
1839         while ( object != limit ) {
1840             list = g_slist_prepend(list, object);
1841             object = SP_OBJECT_NEXT(object);
1842         }
1843         return list;
1844     }
1845 };
1849 void
1850 sp_selection_item_next(void)
1852     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1853     g_return_if_fail(desktop != NULL);
1854     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1856     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1857     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1858     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1860     SPObject *root;
1861     if (PREFS_SELECTION_ALL != inlayer) {
1862         root = selection->activeContext();
1863     } else {
1864         root = desktop->currentRoot();
1865     }
1867     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1869     if (item) {
1870         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1871         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1872             scroll_to_show_item(desktop, item);
1873         }
1874     }
1877 void
1878 sp_selection_item_prev(void)
1880     SPDocument *document = SP_ACTIVE_DOCUMENT;
1881     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1882     g_return_if_fail(document != NULL);
1883     g_return_if_fail(desktop != NULL);
1884     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1886     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1887     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1888     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1890     SPObject *root;
1891     if (PREFS_SELECTION_ALL != inlayer) {
1892         root = selection->activeContext();
1893     } else {
1894         root = desktop->currentRoot();
1895     }
1897     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1899     if (item) {
1900         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1901         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1902             scroll_to_show_item(desktop, item);
1903         }
1904     }
1907 namespace {
1909 template <typename D>
1910 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1911                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1913     SPObject *current=root;
1914     while (items) {
1915         SPItem *item=SP_ITEM(items->data);
1916         if ( root->isAncestorOf(item) &&
1917              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1918         {
1919             current = item;
1920             break;
1921         }
1922         items = items->next;
1923     }
1925     GSList *path=NULL;
1926     while ( current != root ) {
1927         path = g_slist_prepend(path, current);
1928         current = SP_OBJECT_PARENT(current);
1929     }
1931     SPItem *next;
1932     // first, try from the current object
1933     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1934     g_slist_free(path);
1936     if (!next) { // if we ran out of objects, start over at the root
1937         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1938     }
1940     return next;
1943 template <typename D>
1944 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1945                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1947     typename D::Iterator children;
1948     typename D::Iterator iter;
1950     SPItem *found=NULL;
1952     if (path) {
1953         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1954         g_assert(SP_OBJECT_PARENT(object) == root);
1955         if (desktop->isLayer(object)) {
1956             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1957         }
1958         iter = children = D::siblings_after(object);
1959     } else {
1960         iter = children = D::children(root);
1961     }
1963     while ( iter && !found ) {
1964         SPObject *object=D::object(iter);
1965         if (desktop->isLayer(object)) {
1966             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1967                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1968             }
1969         } else if ( SP_IS_ITEM(object) &&
1970                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1971                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1972                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1973                     !desktop->isLayer(SP_ITEM(object)) )
1974         {
1975             found = SP_ITEM(object);
1976         }
1977         iter = D::next(iter);
1978     }
1980     D::dispose(children);
1982     return found;
1987 /**
1988  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1989  * \a item.
1990  */
1991 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1993     NR::Rect dbox = desktop->get_display_area();
1994     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
1996     if ( sbox && dbox.contains(*sbox) == false ) {
1997         NR::Point const s_dt = sbox->midpoint();
1998         NR::Point const s_w = desktop->d2w(s_dt);
1999         NR::Point const d_dt = dbox.midpoint();
2000         NR::Point const d_w = desktop->d2w(d_dt);
2001         NR::Point const moved_w( d_w - s_w );
2002         gint const dx = (gint) moved_w[X];
2003         gint const dy = (gint) moved_w[Y];
2004         desktop->scroll_world(dx, dy);
2005     }
2009 void
2010 sp_selection_clone()
2012     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2013     if (desktop == NULL)
2014         return;
2016     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2018     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2020     // check if something is selected
2021     if (selection->isEmpty()) {
2022         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2023         return;
2024     }
2026     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2027   
2028     selection->clear();
2029   
2030     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2031     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2033     GSList *newsel = NULL;
2034  
2035     while (reprs) {
2036         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2037         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2039         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2040         sp_repr_set_attr(clone, "x", "0");
2041         sp_repr_set_attr(clone, "y", "0");
2042         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2044         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2045         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2046         
2047         // add the new clone to the top of the original's parent
2048         parent->appendChild(clone);
2050         newsel = g_slist_prepend(newsel, clone);
2051         reprs = g_slist_remove(reprs, sel_repr);
2052         Inkscape::GC::release(clone);
2053     }
2054     
2055     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2056                      _("Clone"));
2058     selection->setReprList(newsel);
2059  
2060     g_slist_free(newsel);
2063 void
2064 sp_selection_unlink()
2066     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2067     if (!desktop)
2068         return;
2070     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2072     if (selection->isEmpty()) {
2073         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2074         return;
2075     }
2077     // Get a copy of current selection.
2078     GSList *new_select = NULL;
2079     bool unlinked = false;
2080     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2081          items != NULL;
2082          items = items->next)
2083     {
2084         SPItem *use = (SPItem *) items->data;
2086         if (!SP_IS_USE(use)) {
2087             // keep the non-yse item in the new selection
2088             new_select = g_slist_prepend(new_select, use);
2089             continue;
2090         }
2092         SPItem *unlink = sp_use_unlink(SP_USE(use));
2093         unlinked = true;
2094         // Add ungrouped items to the new selection.
2095         new_select = g_slist_prepend(new_select, unlink);
2096     }
2098     if (new_select) { // set new selection
2099         selection->clear();
2100         selection->setList(new_select);
2101         g_slist_free(new_select);
2102     }
2103     if (!unlinked) {
2104         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2105     }
2107     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2108                      _("Unlink clone"));
2111 void
2112 sp_select_clone_original()
2114     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2115     if (desktop == NULL)
2116         return;
2118     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2120     SPItem *item = selection->singleItem();
2122     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.");
2124     // Check if other than two objects are selected
2125     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2126         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2127         return;
2128     }
2130     SPItem *original = NULL;
2131     if (SP_IS_USE(item)) {
2132         original = sp_use_get_original (SP_USE(item));
2133     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2134         original = sp_offset_get_source (SP_OFFSET(item));
2135     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2136         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2137     } else if (SP_IS_FLOWTEXT(item)) {
2138         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2139     } else { // it's an object that we don't know what to do with
2140         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2141         return;
2142     }
2144     if (!original) {
2145         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2146         return;
2147     }
2149     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2150         if (SP_IS_DEFS (o)) {
2151             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2152             return;
2153         }
2154     }
2156     if (original) {
2157         selection->clear();
2158         selection->set(original);
2159         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2160             scroll_to_show_item(desktop, original);
2161         }
2162     }
2165 void
2166 sp_selection_tile(bool apply)
2168     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2169     if (desktop == NULL)
2170         return;
2172     SPDocument *document = sp_desktop_document(desktop);
2173     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2175     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2177     // check if something is selected
2178     if (selection->isEmpty()) {
2179         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2180         return;
2181     }
2183     sp_document_ensure_up_to_date(document);
2184     NR::Rect r = selection->bounds();
2185     if (r.isEmpty()) {
2186         return;
2187     }
2189     // calculate the transform to be applied to objects to move them to 0,0
2190     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2191     move_p[NR::Y] = -move_p[NR::Y];
2192     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2194     GSList *items = g_slist_copy((GSList *) selection->itemList());
2196     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2198     // bottommost object, after sorting
2199     SPObject *parent = SP_OBJECT_PARENT (items->data);
2201     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2203     // remember the position of the first item
2204     gint pos = SP_OBJECT_REPR (items->data)->position();
2206     // create a list of duplicates
2207     GSList *repr_copies = NULL;
2208     for (GSList *i = items; i != NULL; i = i->next) {
2209         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2210         repr_copies = g_slist_prepend (repr_copies, dup);
2211     }
2213     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2215     if (apply) {
2216         // delete objects so that their clones don't get alerted; this object will be restored shortly
2217         for (GSList *i = items; i != NULL; i = i->next) {
2218             SPObject *item = SP_OBJECT (i->data);
2219             item->deleteObject (false);
2220         }
2221     }
2223     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2224     // without disturbing clones.
2225     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2226     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2227     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2229     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2230                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2232     // restore compensation setting
2233     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2235     if (apply) {
2236         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2237         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2239         NR::Point min = bounds.min() * parent_transform.inverse();
2240         NR::Point max = bounds.max() * parent_transform.inverse();
2242         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2243         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2244         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2245         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2247         // restore parent and position
2248         SP_OBJECT_REPR (parent)->appendChild(rect);
2249         rect->setPosition(pos > 0 ? pos : 0);
2250         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2252         Inkscape::GC::release(rect);
2254         selection->clear();
2255         selection->set(rectangle);
2256     }
2258     g_slist_free (items);
2260     sp_document_done (document, SP_VERB_EDIT_TILE, 
2261                       _("Objects to pattern"));
2264 void
2265 sp_selection_untile()
2267     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2268     if (desktop == NULL)
2269         return;
2271     SPDocument *document = sp_desktop_document(desktop);
2273     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2275     // check if something is selected
2276     if (selection->isEmpty()) {
2277         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2278         return;
2279     }
2281     GSList *new_select = NULL;
2283     bool did = false;
2285     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2286          items != NULL;
2287          items = items->next) {
2289         SPItem *item = (SPItem *) items->data;
2291         SPStyle *style = SP_OBJECT_STYLE (item);
2293         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2294             continue;
2296         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2298         if (!SP_IS_PATTERN(server))
2299             continue;
2301         did = true;
2303         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2305         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2306         pat_transform *= item->transform;
2308         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2309             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2310             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2312            // FIXME: relink clones to the new canvas objects
2313            // use SPObject::setid when mental finishes it to steal ids of
2315             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2316             sp_document_ensure_up_to_date (document);
2318             NR::Matrix transform( i->transform * pat_transform );
2319             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2321             new_select = g_slist_prepend(new_select, i);
2322         }
2324         SPCSSAttr *css = sp_repr_css_attr_new ();
2325         sp_repr_css_set_property (css, "fill", "none");
2326         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2327     }
2329     if (!did) {
2330         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2331     } else {
2332         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2333                          _("Pattern to objects"));
2334         selection->setList(new_select);
2335     }
2338 void
2339 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2341     if (selection->isEmpty()) {
2342         return;
2343     }
2345     const GSList * reprlst = selection->reprList();
2346     bool filename_search = TRUE;
2347     bool xdpi_search = TRUE;
2348     bool ydpi_search = TRUE;
2350     for(; reprlst != NULL &&
2351             filename_search &&
2352             xdpi_search &&
2353             ydpi_search;
2354         reprlst = reprlst->next) {
2355         const gchar * dpi_string;
2356         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2358         if (filename_search) {
2359             *filename = repr->attribute("inkscape:export-filename");
2360             if (*filename != NULL)
2361                 filename_search = FALSE;
2362         }
2364         if (xdpi_search) {
2365             dpi_string = NULL;
2366             dpi_string = repr->attribute("inkscape:export-xdpi");
2367             if (dpi_string != NULL) {
2368                 *xdpi = atof(dpi_string);
2369                 xdpi_search = FALSE;
2370             }
2371         }
2373         if (ydpi_search) {
2374             dpi_string = NULL;
2375             dpi_string = repr->attribute("inkscape:export-ydpi");
2376             if (dpi_string != NULL) {
2377                 *ydpi = atof(dpi_string);
2378                 ydpi_search = FALSE;
2379             }
2380         }
2381     }
2384 void
2385 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2387     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2388     const gchar * dpi_string;
2390     *filename = repr->attribute("inkscape:export-filename");
2392     dpi_string = NULL;
2393     dpi_string = repr->attribute("inkscape:export-xdpi");
2394     if (dpi_string != NULL) {
2395         *xdpi = atof(dpi_string);
2396     }
2398     dpi_string = NULL;
2399     dpi_string = repr->attribute("inkscape:export-ydpi");
2400     if (dpi_string != NULL) {
2401         *ydpi = atof(dpi_string);
2402     }
2405 void
2406 sp_selection_create_bitmap_copy ()
2408     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2409     if (desktop == NULL)
2410         return;
2412     SPDocument *document = sp_desktop_document(desktop);
2413     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2415     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2417     // check if something is selected
2418     if (selection->isEmpty()) {
2419         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2420         return;
2421     }
2423     // Get the bounding box of the selection
2424     NRRect bbox;
2425     sp_document_ensure_up_to_date (document);
2426     selection->bounds(&bbox);
2427     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2428         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2429     }
2431     // List of the items to show; all others will be hidden
2432     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2434     // Sort items so that the topmost comes last
2435     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2437     // Generate a random value from the current time (you may create bitmap from the same object(s)
2438     // multiple times, and this is done so that they don't clash)
2439     GTimeVal cu;
2440     g_get_current_time (&cu);
2441     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2443     // Create the filename
2444     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2445     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2446     // digits, and a few other chars, with "_"
2447     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2448     // Build the complete path by adding document->base if set
2449     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2451     //g_print ("%s\n", filepath);
2453     // Remember parent and z-order of the topmost one
2454     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2455     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2456     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2458     // Calculate resolution
2459     double res;
2460     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2461     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2462     if (0 < prefs_res) {
2463         // If it's given explicitly in prefs, take it
2464         res = prefs_res;
2465     } else if (0 < prefs_min) {
2466         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2467         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2468     } else {
2469         float hint_xdpi = 0, hint_ydpi = 0;
2470         const char *hint_filename;
2471         // take resolution hint from the selected objects
2472         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2473         if (hint_xdpi != 0) {
2474             res = hint_xdpi;
2475         } else {
2476             // take resolution hint from the document
2477             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2478             if (hint_xdpi != 0) {
2479                 res = hint_xdpi;
2480             } else {
2481                 // if all else fails, take the default 90 dpi
2482                 res = PX_PER_IN;
2483             }
2484         }
2485     }
2487     // The width and height of the bitmap in pixels
2488     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2489     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2491     // Find out if we have to run a filter
2492     const gchar *run = NULL;
2493     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2494     if (filter) {
2495         // filter command is given;
2496         // see if we have a parameter to pass to it
2497         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2498         if (param1) {
2499             if (param1[strlen(param1) - 1] == '%') {
2500                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2501                 gchar p1[256];
2502                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2503                 // the first param is always the image filename, the second is param1
2504                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2505             } else {
2506                 // otherwise pass the param1 unchanged
2507                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2508             }
2509         } else {
2510             // run without extra parameter
2511             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2512         }
2513     }
2515     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2516     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2517     NR::Matrix t;
2519     double shift_x = bbox.x0;
2520     double shift_y = bbox.y1; 
2521     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2522         shift_x = round (shift_x);
2523         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2524     }
2525     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2527     // Do the export
2528     sp_export_png_file(document, filepath,
2529                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2530                    width, height, res, res,
2531                    (guint32) 0xffffff00,
2532                    NULL, NULL,
2533                    true,  /*bool force_overwrite,*/
2534                    items);
2536     g_slist_free (items);
2538     // Run filter, if any
2539     if (run) {
2540         g_print ("Running external filter: %s\n", run);
2541         system (run);
2542     }
2544     // Import the image back
2545     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2546     if (pb) {
2547         // Create the repr for the image
2548         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2549         repr->setAttribute("xlink:href", filename);
2550         repr->setAttribute("sodipodi:absref", filepath);
2551         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2552             sp_repr_set_svg_double(repr, "width", width);
2553             sp_repr_set_svg_double(repr, "height", height);
2554         } else {
2555             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2556             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2557         }
2559         // Write transform
2560         gchar *c=sp_svg_transform_write(t);
2561         repr->setAttribute("transform", c);
2562         g_free(c);
2564         // add the new repr to the parent
2565         parent->appendChild(repr);
2567         // move to the saved position
2568         repr->setPosition(pos > 0 ? pos + 1 : 1);
2570         // Set selection to the new image
2571         selection->clear();
2572         selection->add(repr);
2574         // Clean up
2575         Inkscape::GC::release(repr);
2576         gdk_pixbuf_unref (pb);
2578         // Complete undoable transaction
2579         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2580                           _("Create bitmap"));
2581     }
2583     g_free (filename);
2584     g_free (filepath);
2587 /**
2588  * \brief sp_selection_set_mask
2589  *
2590  * This function creates a mask or clipPath from selection
2591  * Two different modes:
2592  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2593  *       and is applied to current layer
2594  *  otherwise, topmost object is used as mask for other objects
2595  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2596  * 
2597  */
2598 void
2599 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2601     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2602     if (desktop == NULL)
2603         return;
2605     SPDocument *document = sp_desktop_document(desktop);
2606     
2607     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2609     // check if something is selected
2610     bool is_empty = selection->isEmpty();
2611     if ( apply_to_layer && is_empty) {
2612         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2613         return;
2614     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2615         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2616         return;
2617     }
2619     // FIXME: temporary patch to prevent crash! 
2620     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2621     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2622     if (clone_with_original) {
2623         return; // in this version, you cannot clip/mask an object with its own clone
2624     }
2625     // /END FIXME
2626     
2627     sp_document_ensure_up_to_date(document);
2629     GSList *items = g_slist_copy((GSList *) selection->itemList());
2630     
2631     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2633     // create a list of duplicates
2634     GSList *mask_items = NULL;
2635     GSList *apply_to_items = NULL;
2636     GSList *items_to_delete = NULL;
2637     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2638     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2639     
2640     if (apply_to_layer) {
2641         // all selected items are used for mask, which is applied to a layer
2642         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2644         for (GSList *i = items; i != NULL; i = i->next) {
2645             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2646             mask_items = g_slist_prepend (mask_items, dup);
2648             if (remove_original) {
2649                 SPObject *item = SP_OBJECT (i->data);
2650                 items_to_delete = g_slist_prepend (items_to_delete, item);
2651             }
2652         }
2653     } else if (!topmost) {
2654         // topmost item is used as a mask, which is applied to other items in a selection
2655         GSList *i = items;
2656         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2657         mask_items = g_slist_prepend (mask_items, dup);
2659         if (remove_original) {
2660             SPObject *item = SP_OBJECT (i->data);
2661             items_to_delete = g_slist_prepend (items_to_delete, item);
2662         }
2663         
2664         for (i = i->next; i != NULL; i = i->next) {
2665             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2666         }
2667     } else {
2668         GSList *i = NULL;
2669         for (i = items; NULL != i->next; i = i->next) {
2670             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2671         }
2673         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2674         mask_items = g_slist_prepend (mask_items, dup);
2676         if (remove_original) {
2677             SPObject *item = SP_OBJECT (i->data);
2678             items_to_delete = g_slist_prepend (items_to_delete, item);
2679         }
2680     }
2681     
2682     g_slist_free (items);
2683     items = NULL;
2684             
2685     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2686     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2687         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2688         // inverted object transform should be applied to a mask object,
2689         // as mask is calculated in user space (after applying transform)
2690         NR::Matrix maskTransform (item->transform.inverse());
2692         GSList *mask_items_dup = NULL;
2693         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2694             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2695             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2696         }
2698         const gchar *mask_id = NULL;
2699         if (apply_clip_path) {
2700             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2701         } else {
2702             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2703         }
2705         g_slist_free (mask_items_dup);
2706         mask_items_dup = NULL;
2708         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2709     }
2711     g_slist_free (mask_items);
2712     g_slist_free (apply_to_items);
2714     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2715         SPObject *item = SP_OBJECT (i->data);
2716         item->deleteObject (false);
2717     }
2718     g_slist_free (items_to_delete);
2720     if (apply_clip_path) 
2721         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2722     else 
2723         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2726 void sp_selection_unset_mask(bool apply_clip_path) {
2727     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2728     if (desktop == NULL)
2729         return;
2730     
2731     SPDocument *document = sp_desktop_document(desktop);    
2732     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2734     // check if something is selected
2735     if (selection->isEmpty()) {
2736         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2737         return;
2738     }
2739     
2740     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2741     sp_document_ensure_up_to_date(document);
2743     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2744     std::map<SPObject*,SPItem*> referenced_objects;
2745     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2746         if (remove_original) {
2747             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2748             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2749             Inkscape::URIReference *uri_ref = NULL;
2750         
2751             if (apply_clip_path) {
2752                 uri_ref = item->clip_ref;
2753             } else {
2754                 uri_ref = item->mask_ref;
2755             }
2757             // collect distinct mask object (and associate with item to apply transform)
2758             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2759                 referenced_objects[uri_ref->getObject()] = item;
2760             }
2761         }
2763         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2764     }
2766     // restore mask objects into a document
2767     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2768         SPObject *obj = (*it).first;
2769         GSList *items_to_move = NULL;
2770         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2771             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2772             items_to_move = g_slist_prepend (items_to_move, copy);
2773         }
2775         if (!obj->isReferenced()) {
2776             // delete from defs if no other object references this mask
2777             obj->deleteObject(false);
2778         }
2780         // remember parent and position of the item to which the clippath/mask was applied
2781         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2782         gint pos = SP_OBJECT_REPR((*it).second)->position();
2784         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2785             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2787             // insert into parent, restore pos
2788             parent->appendChild(repr);
2789             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2791             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2792             selection->add(repr);
2794             // transform mask, so it is moved the same spot where mask was applied
2795             NR::Matrix transform (mask_item->transform);
2796             transform *= (*it).second->transform;
2797             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2798         }
2800         g_slist_free (items_to_move);
2801     }
2803     if (apply_clip_path) 
2804         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2805     else 
2806         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2809 void fit_canvas_to_selection(SPDesktop *desktop) {
2810     g_return_if_fail(desktop != NULL);
2811     SPDocument *doc = sp_desktop_document(desktop);
2813     g_return_if_fail(doc != NULL);
2814     g_return_if_fail(desktop->selection != NULL);
2815     g_return_if_fail(!desktop->selection->isEmpty());
2816     NRRect bbox(0, 0, 0, 0);
2818     desktop->selection->bounds(&bbox);
2819     if (!nr_rect_d_test_empty(&bbox)) {
2820         doc->fitToRect(bbox);
2821     }
2822 };
2824 void fit_canvas_to_drawing(SPDocument *doc) {
2825     g_return_if_fail(doc != NULL);
2826     NRRect bbox(0, 0, 0, 0);
2828     sp_document_ensure_up_to_date (doc);
2829     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2831     if (!nr_rect_d_test_empty(&bbox)) {
2832         doc->fitToRect(bbox);
2833     }
2834 };
2836 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2837     g_return_if_fail(desktop != NULL);
2838     SPDocument *doc = sp_desktop_document(desktop);
2840     g_return_if_fail(doc != NULL);
2841     g_return_if_fail(desktop->selection != NULL);
2843     if (desktop->selection->isEmpty()) {
2844         fit_canvas_to_drawing(doc);
2845     } else {
2846         fit_canvas_to_selection(desktop);
2847     }
2849     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2850                      _("Fit page to selection"));
2851 };
2853 /*
2854   Local Variables:
2855   mode:c++
2856   c-file-style:"stroustrup"
2857   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2858   indent-tabs-mode:nil
2859   fill-column:99
2860   End:
2861 */
2862 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :