Code

adapt code to new Maybe/bbox regime
[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::Rect::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) && selected->intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
658                     // AND if it's not one of our selected objects,
659                     if (!g_slist_find((GSList *) items, newref)) {
660                         // move the selected object after that sibling
661                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
662                     }
663                     break;
664                 }
665             }
666             rev = g_slist_remove(rev, child);
667         }
668     } else {
669         g_slist_free(rev);
670     }
672     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
673                      _("Raise"));
676 void sp_selection_raise_to_top()
678     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
679     if (desktop == NULL)
680         return;
682     SPDocument *document = sp_desktop_document(desktop);
683     Inkscape::Selection *selection = sp_desktop_selection(desktop);
685     if (selection->isEmpty()) {
686         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
687         return;
688     }
690     GSList const *items = (GSList *) selection->itemList();
692     SPGroup const *group = sp_item_list_common_parent_group(items);
693     if (!group) {
694         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
695         return;
696     }
698     GSList *rl = g_slist_copy((GSList *) selection->reprList());
699     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
701     for (GSList *l = rl; l != NULL; l = l->next) {
702         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
703         repr->setPosition(-1);
704     }
706     g_slist_free(rl);
708     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
709                      _("Raise to top"));
712 void
713 sp_selection_lower()
715     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
716     if (desktop == NULL)
717         return;
719     Inkscape::Selection *selection = sp_desktop_selection(desktop);
721     GSList const *items = (GSList *) selection->itemList();
722     if (!items) {
723         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
724         return;
725     }
727     SPGroup const *group = sp_item_list_common_parent_group(items);
728     if (!group) {
729         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
730         return;
731     }
733     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
735     // find out the common bbox of the selected items
736     NR::Maybe<NR::Rect> selected = enclose_items(items);
738     /* construct direct-ordered list of selected children */
739     GSList *rev = g_slist_copy((GSList *) items);
740     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
741     rev = g_slist_reverse(rev);
743     // for all objects in the selection (starting from top)
744     if (selected) {
745         while (rev) {
746             SPObject *child = SP_OBJECT(rev->data);
747             // for each selected object, find the prev sibling
748             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
749                 // if the sibling is an item AND overlaps our selection,
750                 if (SP_IS_ITEM(newref) && selected->intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
751                     // AND if it's not one of our selected objects,
752                     if (!g_slist_find((GSList *) items, newref)) {
753                         // move the selected object before that sibling
754                         SPObject *put_after = prev_sibling(newref);
755                         if (put_after)
756                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
757                         else
758                             SP_OBJECT_REPR(child)->setPosition(0);
759                     }
760                     break;
761                 }
762             }
763             rev = g_slist_remove(rev, child);
764         }
765     } else {
766         g_slist_free(rev);
767     }
769     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
770                      _("Lower"));
773 void sp_selection_lower_to_bottom()
775     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
776     if (desktop == NULL)
777         return;
779     SPDocument *document = sp_desktop_document(desktop);
780     Inkscape::Selection *selection = sp_desktop_selection(desktop);
782     if (selection->isEmpty()) {
783         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
784         return;
785     }
787     GSList const *items = (GSList *) selection->itemList();
789     SPGroup const *group = sp_item_list_common_parent_group(items);
790     if (!group) {
791         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
792         return;
793     }
795     GSList *rl;
796     rl = g_slist_copy((GSList *) selection->reprList());
797     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
798     rl = g_slist_reverse(rl);
800     for (GSList *l = rl; l != NULL; l = l->next) {
801         gint minpos;
802         SPObject *pp, *pc;
803         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
804         pp = document->getObjectByRepr(sp_repr_parent(repr));
805         minpos = 0;
806         g_assert(SP_IS_GROUP(pp));
807         pc = sp_object_first_child(pp);
808         while (!SP_IS_ITEM(pc)) {
809             minpos += 1;
810             pc = pc->next;
811         }
812         repr->setPosition(minpos);
813     }
815     g_slist_free(rl);
817     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
818                      _("Lower to bottom"));
821 void
822 sp_undo(SPDesktop *desktop, SPDocument *)
824         if (!sp_document_undo(sp_desktop_document(desktop)))
825             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
828 void
829 sp_redo(SPDesktop *desktop, SPDocument *)
831         if (!sp_document_redo(sp_desktop_document(desktop)))
832             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
835 void sp_selection_cut()
837     sp_selection_copy();
838     sp_selection_delete();
841 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
843     SPGradient *ref = gradient;
845     while (ref) {
846         // climb up the refs, copying each one in the chain
847         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
848         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
850         ref = ref->ref->getObject();
851     }
854 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
856     SPPattern *ref = pattern;
858     while (ref) {
859         // climb up the refs, copying each one in the chain
860         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
861         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
863         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
864         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
865             if (!SP_IS_ITEM (child))
866                 continue;
867             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
868         }
870         ref = ref->ref->getObject();
871     }
874 void sp_copy_single (GSList **defs_clip, SPObject *thing)
876     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
877     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
881 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
883     SPItem *path = sp_textpath_get_path_item (tp);
884     if (!path)
885         return;
886     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
887         return;
888     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
889     *defs_clip = g_slist_prepend (*defs_clip, repr);
892 /**
893  * Copies things like patterns, markers, gradients, etc.
894  */
895 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
897     SPStyle *style = SP_OBJECT_STYLE (item);
899     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
900         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
901         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
902             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
903         if (SP_IS_PATTERN (server))
904             sp_copy_pattern (defs_clip, SP_PATTERN(server));
905     }
907     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
908         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
909         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
910             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
911         if (SP_IS_PATTERN (server))
912             sp_copy_pattern (defs_clip, SP_PATTERN(server));
913     }
915     // For shapes, copy all of the shape's markers into defs_clip
916     if (SP_IS_SHAPE (item)) {
917         SPShape *shape = SP_SHAPE (item);
918         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
919             if (shape->marker[i]) {
920                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
921             }
922         }
923     }
925     if (SP_IS_TEXT_TEXTPATH (item)) {
926         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
927     }
929     if (item->clip_ref->getObject()) {
930         sp_copy_single (defs_clip, item->clip_ref->getObject());
931     }
933     if (item->mask_ref->getObject()) {
934         SPObject *mask = item->mask_ref->getObject();
935         sp_copy_single (defs_clip, mask);
936         // recurse into the mask for its gradients etc.
937         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
938             if (SP_IS_ITEM(o))
939                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
940         }
941     }
943     if (style->filter.filter) {
944         SPObject *filter = style->filter.filter;
945         if (SP_IS_FILTER(filter)) {
946             sp_copy_single (defs_clip, filter);
947         }
948     }
950     // recurse
951     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
952         if (SP_IS_ITEM(o))
953             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
954     }
957 /**
958  * \pre item != NULL
959  */
960 SPCSSAttr *
961 take_style_from_item (SPItem *item)
963     // write the complete cascaded style, context-free
964     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
965     if (css == NULL)
966         return NULL;
968     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
969         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
970         // if this is a text with exactly one tspan child, merge the style of that tspan as well
971         // If this is a group, merge the style of its topmost (last) child with style
972         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
973             if (SP_OBJECT_STYLE (last_element) != NULL) {
974                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
975                 if (temp) {
976                     sp_repr_css_merge (css, temp);
977                     sp_repr_css_attr_unref (temp);
978                 }
979                 break;
980             }
981         }
982     }
983     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
984         // do not copy text properties from non-text objects, it's confusing
985         css = sp_css_attr_unset_text (css);
986     }
988     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
989     double ex = NR::expansion(sp_item_i2doc_affine(item));
990     if (ex != 1.0) {
991         css = sp_css_attr_scale (css, ex);
992     }
994     return css;
998 void sp_selection_copy()
1000     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1001     if (desktop == NULL)
1002         return;
1004     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1006     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1007         sp_dropper_context_copy(desktop->event_context);
1008         return; // copied color under cursor, nothing else to do
1009     }
1011     // check if something is selected
1012     if (selection->isEmpty()) {
1013         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1014         return;
1015     }
1017     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1019     // 0. Copy text to system clipboard
1020     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1021     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1022     Glib::ustring text;
1023     if (tools_isactive (desktop, TOOLS_TEXT)) {
1024         text = sp_text_get_selected_text(desktop->event_context);
1025     }
1027     if (text.empty()) {
1028         guint texts = 0;
1029         for (GSList *i = (GSList *) items; i; i = i->next) {
1030             SPItem *item = SP_ITEM (i->data);
1031             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1032                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1033                     text += " ";
1034                 gchar *this_text = sp_te_get_string_multiline (item);
1035                 if (this_text) {
1036                     text += this_text;
1037                     g_free(this_text);
1038                 }
1039                 texts++;
1040             }
1041         }
1042     }
1043     if (!text.empty()) {
1044         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1045         refClipboard->set_text(text);
1046     }
1048     // clear old defs clipboard
1049     while (defs_clipboard) {
1050         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1051         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1052     }
1054     // clear style clipboard
1055     if (style_clipboard) {
1056         sp_repr_css_attr_unref (style_clipboard);
1057         style_clipboard = NULL;
1058     }
1060     //clear main clipboard
1061     while (clipboard) {
1062         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1063         clipboard = g_slist_remove(clipboard, clipboard->data);
1064     }
1066     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1068     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1069         SPStyle *const query = sp_style_new();
1070         if (sp_desktop_query_style_all (desktop, query)) {
1071             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1072             if (css != NULL) {
1073                 // clear style clipboard
1074                 if (style_clipboard) {
1075                     sp_repr_css_attr_unref (style_clipboard);
1076                     style_clipboard = NULL;
1077                 }
1078                 //sp_repr_css_print (css);
1079                 style_clipboard = css;
1080             }
1081         }
1082         g_free (query);
1083     }
1085     size_clipboard = selection->bounds();
1087     g_slist_free ((GSList *) items);
1090 void sp_selection_paste(bool in_place)
1092     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1094     if (desktop == NULL) {
1095         return;
1096     }
1098     SPDocument *document = sp_desktop_document(desktop);
1100     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1101         return;
1102     }
1104     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1106     if (tools_isactive (desktop, TOOLS_TEXT)) {
1107         if (sp_text_paste_inline(desktop->event_context))
1108             return; // pasted from system clipboard into text, nothing else to do
1109     }
1111     // check if something is in the clipboard
1112     if (clipboard == NULL) {
1113         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1114         return;
1115     }
1117     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1118     // add pasted objects to selection
1119     selection->setReprList((GSList const *) copied);
1120     g_slist_free (copied);
1122     if (!in_place) {
1123         sp_document_ensure_up_to_date(document);
1125         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1127         /* Snap the offset of the new item(s) to the grid */
1128         /* FIXME: this gridsnap fiddling is a hack. */
1129         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1130         gdouble const curr_gridsnap = s.getDistance();
1131         s.setDistance(NR_HUGE);
1132         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1133         s.setDistance(curr_gridsnap);
1134         sp_selection_move_relative(selection, m);
1135     }
1137     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1138                      _("Paste"));
1141 void sp_selection_paste_style()
1143     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1144     if (desktop == NULL) return;
1146     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1148     // check if something is in the clipboard
1149     if (clipboard == NULL) {
1150         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1151         return;
1152     }
1154     // check if something is selected
1155     if (selection->isEmpty()) {
1156         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1157         return;
1158     }
1160     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1162     sp_desktop_set_style (desktop, style_clipboard);
1164     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1165                      _("Paste style"));
1168 void sp_selection_paste_size (bool apply_x, bool apply_y)
1170     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1171     if (desktop == NULL) return;
1173     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1175     // check if something is in the clipboard
1176     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1177         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1178         return;
1179     }
1181     // check if something is selected
1182     if (selection->isEmpty()) {
1183         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1184         return;
1185     }
1187     NR::Rect current = selection->bounds();
1188     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1189         return;
1190     }
1192     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1193     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1195     sp_selection_scale_relative (selection, current.midpoint(), 
1196                                  NR::scale(
1197                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1198                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1200     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1201                      _("Paste size"));
1204 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1206     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1207     if (desktop == NULL) return;
1209     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1211     // check if something is in the clipboard
1212     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1213         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1214         return;
1215     }
1217     // check if something is selected
1218     if (selection->isEmpty()) {
1219         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1220         return;
1221     }
1223     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1224         SPItem *item = SP_ITEM(l->data);
1226         NR::Rect current = sp_item_bbox_desktop(item);
1227         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1228             continue;
1229         }
1231         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1232         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1234         sp_item_scale_rel (item,
1235                                  NR::scale(
1236                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1237                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1239     }
1241     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1242                      _("Paste size separately"));
1245 void sp_selection_to_next_layer ()
1247     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1249     Inkscape::Selection *selection = sp_desktop_selection(dt);
1251     // check if something is selected
1252     if (selection->isEmpty()) {
1253         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1254         return;
1255     }
1257     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1259     bool no_more = false; // Set to true, if no more layers above
1260     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1261     if (next) {
1262         GSList *temp_clip = NULL;
1263         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1264         sp_selection_delete_impl (items);
1265         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1266         GSList *copied;
1267         if(next) {
1268             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1269         } else {
1270             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1271             no_more = true;
1272         }
1273         selection->setReprList((GSList const *) copied);
1274         g_slist_free (copied);
1275         if (temp_clip) g_slist_free (temp_clip);
1276         if (next) dt->setCurrentLayer(next);
1277         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1278                          _("Raise to next layer"));
1279     } else {
1280         no_more = true;
1281     }
1283     if (no_more) {
1284         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1285     }
1287     g_slist_free ((GSList *) items);
1290 void sp_selection_to_prev_layer ()
1292     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1294     Inkscape::Selection *selection = sp_desktop_selection(dt);
1296     // check if something is selected
1297     if (selection->isEmpty()) {
1298         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1299         return;
1300     }
1302     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1304     bool no_more = false; // Set to true, if no more layers below
1305     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1306     if (next) {
1307         GSList *temp_clip = NULL;
1308         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1309         sp_selection_delete_impl (items);
1310         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1311         GSList *copied;
1312         if(next) {
1313             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1314         } else {
1315             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1316             no_more = true;
1317         }
1318         selection->setReprList((GSList const *) copied);
1319         g_slist_free (copied);
1320         if (temp_clip) g_slist_free (temp_clip);
1321         if (next) dt->setCurrentLayer(next);
1322         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1323                          _("Lower to previous layer"));
1324     } else {
1325         no_more = true;
1326     }
1328     if (no_more) {
1329         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1330     }
1332     g_slist_free ((GSList *) items);
1335 bool
1336 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1338     bool contains_original = false;
1339     bool is_use = SP_IS_USE(item);
1340     SPItem *item_use = item;
1341     SPItem *item_use_first = item;
1342     while (is_use && item_use && !contains_original)
1343     {
1344         item_use = sp_use_get_original (SP_USE(item_use));
1345         contains_original |= selection->includes(item_use);
1346         if (item_use == item_use_first)
1347             break;
1348         is_use = SP_IS_USE(item_use);
1349     }   
1350     return contains_original;
1354 bool
1355 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1357     bool clone_with_original = false;
1358     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1359         SPItem *item = SP_ITEM(l->data);
1360         clone_with_original |= selection_contains_original(item, selection);
1361         if (clone_with_original) 
1362             break;
1363     }
1364     return clone_with_original;
1368 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1369 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1370 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1371 that case, items are already in the new position, but the repr is in the old, and this function
1372 then simply updates the repr from item->transform.
1373  */
1374 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1376     if (selection->isEmpty())
1377         return;
1379     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1380         SPItem *item = SP_ITEM(l->data);
1382         NR::Point old_center(0,0);
1383         if (set_i2d && item->isCenterSet())
1384             old_center = item->getCenter();
1386 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1387          At the time of writing, this is the only place to re-enable. */
1388         sp_item_update_cns(*item, selection->desktop());
1389 #endif
1391         // we're moving both a clone and its original or any ancestor in clone chain?
1392         bool transform_clone_with_original = selection_contains_original(item, selection);
1393         // ...both a text-on-path and its path?
1394         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)))) ));
1395         // ...both a flowtext and its frame?
1396         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)
1397         // ...both an offset and its source?
1398         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1399        
1400         // If we're moving a connector, we want to detach it
1401         // from shapes that aren't part of the selection, but
1402         // leave it attached if they are
1403         if (cc_item_is_connector(item)) {
1404             SPItem *attItem[2];
1405             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1406             
1407             for (int n = 0; n < 2; ++n) {
1408                 if (!selection->includes(attItem[n])) {
1409                     sp_conn_end_detach(item, n);
1410                 }
1411             }
1412         }
1413         
1414         // "clones are unmoved when original is moved" preference
1415         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1416         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1417         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1419         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1420         // transform of its original and respond to it itself. Without this, a clone is doubly
1421         // transformed, very unintuitive.
1422       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1423       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1424       // Same for linked offset if we are also moving its source: do not move it.
1425         if (transform_textpath_with_path || transform_offset_with_source) {
1426                 // restore item->transform field from the repr, in case it was changed by seltrans
1427             sp_object_read_attr (SP_OBJECT (item), "transform");
1429         } else if (transform_flowtext_with_frame) {
1430             // apply the inverse of the region's transform to the <use> so that the flow remains
1431             // the same (even though the output itself gets transformed)
1432             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1433                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1434                     continue;
1435                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1436                     if (!SP_IS_USE(use)) continue;
1437                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1438                 }
1439             }
1440         } else if (transform_clone_with_original) {
1441             // We are transforming a clone along with its original. The below matrix juggling is
1442             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1443             // transform and its move compensation are both cancelled out.
1445             // restore item->transform field from the repr, in case it was changed by seltrans
1446             sp_object_read_attr (SP_OBJECT (item), "transform");
1448             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1449             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1450             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1451             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1452             NR::Matrix result = t_inv * item->transform * t;
1454             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1455                 // we need to cancel out the move compensation, too
1457                 // find out the clone move, same as in sp_use_move_compensate
1458                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1459                 NR::Matrix clone_move = parent.inverse() * t * parent;
1461                 if (prefs_parallel) {
1462                     NR::Matrix move = result * clone_move * t_inv;
1463                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1465                 } else if (prefs_unmoved) {
1466                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1467                     //    clone_move = NR::identity();
1468                     NR::Matrix move = result * clone_move;
1469                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1470                 }
1472             } else {
1473                 // just apply the result
1474                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1475             }
1477         } else {
1478             if (set_i2d) {
1479                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1480             }
1481             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1482         }
1484         // if we're moving the actual object, not just updating the repr, we can transform the
1485         // center by the same matrix (only necessary for non-translations)
1486         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1487             item->setCenter(old_center * affine);
1488             SP_OBJECT(item)->updateRepr();
1489         }
1490     }
1493 void sp_selection_remove_transform()
1495     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1496     if (desktop == NULL)
1497         return;
1499     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1501     GSList const *l = (GSList *) selection->reprList();
1502     while (l != NULL) {
1503         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1504         l = l->next;
1505     }
1507     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1508                      _("Remove transform"));
1511 void
1512 sp_selection_scale_absolute(Inkscape::Selection *selection,
1513                             double const x0, double const x1,
1514                             double const y0, double const y1)
1516     if (selection->isEmpty())
1517         return;
1519     NR::Rect const bbox(selection->bounds());
1520     if (bbox.isEmpty()) {
1521         return;
1522     }
1524     NR::translate const p2o(-bbox.min());
1526     NR::scale const newSize(x1 - x0,
1527                             y1 - y0);
1528     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1529     NR::translate const o2n(x0, y0);
1530     NR::Matrix const final( p2o * scale * o2n );
1532     sp_selection_apply_affine(selection, final);
1536 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1538     if (selection->isEmpty())
1539         return;
1541     NR::Rect const bbox(selection->bounds());
1543     if (bbox.isEmpty()) {
1544         return;
1545     }
1547     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1548     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1549          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1550     {
1551         return;
1552     }
1554     NR::translate const n2d(-align);
1555     NR::translate const d2n(align);
1556     NR::Matrix const final( n2d * scale * d2n );
1557     sp_selection_apply_affine(selection, final);
1560 void
1561 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1563     NR::translate const d2n(center);
1564     NR::translate const n2d(-center);
1565     NR::rotate const rotate(rotate_degrees(angle_degrees));
1566     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1567     sp_selection_apply_affine(selection, final);
1570 void
1571 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1573     NR::translate const d2n(align);
1574     NR::translate const n2d(-align);
1575     NR::Matrix const skew(1, dy,
1576                           dx, 1,
1577                           0, 0);
1578     NR::Matrix const final( n2d * skew * d2n );
1579     sp_selection_apply_affine(selection, final);
1582 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1584     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1587 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1589     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1593 /**
1594  * \brief sp_selection_rotate_90
1595  *
1596  * This function rotates selected objects 90 degrees clockwise.
1597  *
1598  */
1600 void sp_selection_rotate_90_cw()
1602     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1604     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1606     if (selection->isEmpty())
1607         return;
1609     GSList const *l = selection->itemList();
1610     NR::rotate const rot_neg_90(NR::Point(0, -1));
1611     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1612         SPItem *item = SP_ITEM(l2->data);
1613         sp_item_rotate_rel(item, rot_neg_90);
1614     }
1616     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1617                      _("Rotate 90&#176; CW"));
1621 /**
1622  * \brief sp_selection_rotate_90_ccw
1623  *
1624  * This function rotates selected objects 90 degrees counter-clockwise.
1625  *
1626  */
1628 void sp_selection_rotate_90_ccw()
1630     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1632     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1634     if (selection->isEmpty())
1635         return;
1637     GSList const *l = selection->itemList();
1638     NR::rotate const rot_neg_90(NR::Point(0, 1));
1639     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1640         SPItem *item = SP_ITEM(l2->data);
1641         sp_item_rotate_rel(item, rot_neg_90);
1642     }
1644     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1645                      _("Rotate 90&#176; CCW"));
1648 void
1649 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1651     if (selection->isEmpty())
1652         return;
1654     NR::Point center = selection->center();
1656     sp_selection_rotate_relative(selection, center, angle_degrees);
1658     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1659                            ( ( angle_degrees > 0 )
1660                              ? "selector:rotate:ccw"
1661                              : "selector:rotate:cw" ), 
1662                            SP_VERB_CONTEXT_SELECT, 
1663                            _("Rotate"));
1666 /**
1667 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1668 */
1669 void
1670 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1672     if (selection->isEmpty())
1673         return;
1675     NR::Rect const bbox(selection->bounds());
1677     NR::Point center = selection->center();
1679     gdouble const zoom = selection->desktop()->current_zoom();
1680     gdouble const zmove = angle / zoom;
1681     gdouble const r = NR::L2(bbox.max() - center);
1683     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1685     sp_selection_rotate_relative(selection, center, zangle);
1687     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1688                            ( (angle > 0)
1689                              ? "selector:rotate:ccw"
1690                              : "selector:rotate:cw" ),
1691                            SP_VERB_CONTEXT_SELECT, 
1692                            _("Rotate by pixels"));
1695 void
1696 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1698     if (selection->isEmpty())
1699         return;
1701     NR::Rect const bbox(selection->bounds());
1702     NR::Point const center(bbox.midpoint());
1703     double const max_len = bbox.maxExtent();
1705     // you can't scale "do nizhe pola" (below zero)
1706     if ( max_len + grow <= 1e-3 ) {
1707         return;
1708     }
1710     double const times = 1.0 + grow / max_len;
1711     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1713     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1714                            ( (grow > 0)
1715                              ? "selector:scale:larger"
1716                              : "selector:scale:smaller" ),
1717                            SP_VERB_CONTEXT_SELECT,
1718                            _("Scale"));
1721 void
1722 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1724     sp_selection_scale(selection,
1725                        grow_pixels / selection->desktop()->current_zoom());
1728 void
1729 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1731     if (selection->isEmpty())
1732         return;
1734     NR::Point const center(selection->bounds().midpoint());
1735     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1736     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1737                      _("Scale by whole factor"));
1740 void
1741 sp_selection_move(gdouble dx, gdouble dy)
1743     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1744     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1745     if (selection->isEmpty()) {
1746         return;
1747     }
1749     sp_selection_move_relative(selection, dx, dy);
1751     if (dx == 0) {
1752         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1753                                _("Move vertically"));
1754     } else if (dy == 0) {
1755         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1756                                _("Move horizontally"));
1757     } else {
1758         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1759                          _("Move"));
1760     }
1763 void
1764 sp_selection_move_screen(gdouble dx, gdouble dy)
1766     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1768     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1769     if (selection->isEmpty()) {
1770         return;
1771     }
1773     // same as sp_selection_move but divide deltas by zoom factor
1774     gdouble const zoom = desktop->current_zoom();
1775     gdouble const zdx = dx / zoom;
1776     gdouble const zdy = dy / zoom;
1777     sp_selection_move_relative(selection, zdx, zdy);
1779     if (dx == 0) {
1780         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1781                                _("Move vertically by pixels"));
1782     } else if (dy == 0) {
1783         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1784                                _("Move horizontally by pixels"));
1785     } else {
1786         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1787                          _("Move"));
1788     }
1791 namespace {
1793 template <typename D>
1794 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1795                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1797 template <typename D>
1798 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1799                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1801 struct Forward {
1802     typedef SPObject *Iterator;
1804     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1805     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1806     static void dispose(Iterator i) {}
1808     static SPObject *object(Iterator i) { return i; }
1809     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1810 };
1812 struct Reverse {
1813     typedef GSList *Iterator;
1815     static Iterator children(SPObject *o) {
1816         return make_list(o->firstChild(), NULL);
1817     }
1818     static Iterator siblings_after(SPObject *o) {
1819         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1820     }
1821     static void dispose(Iterator i) {
1822         g_slist_free(i);
1823     }
1825     static SPObject *object(Iterator i) {
1826         return reinterpret_cast<SPObject *>(i->data);
1827     }
1828     static Iterator next(Iterator i) { return i->next; }
1830 private:
1831     static GSList *make_list(SPObject *object, SPObject *limit) {
1832         GSList *list=NULL;
1833         while ( object != limit ) {
1834             list = g_slist_prepend(list, object);
1835             object = SP_OBJECT_NEXT(object);
1836         }
1837         return list;
1838     }
1839 };
1843 void
1844 sp_selection_item_next(void)
1846     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1847     g_return_if_fail(desktop != NULL);
1848     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1850     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1851     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1852     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1854     SPObject *root;
1855     if (PREFS_SELECTION_ALL != inlayer) {
1856         root = selection->activeContext();
1857     } else {
1858         root = desktop->currentRoot();
1859     }
1861     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1863     if (item) {
1864         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1865         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1866             scroll_to_show_item(desktop, item);
1867         }
1868     }
1871 void
1872 sp_selection_item_prev(void)
1874     SPDocument *document = SP_ACTIVE_DOCUMENT;
1875     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1876     g_return_if_fail(document != NULL);
1877     g_return_if_fail(desktop != NULL);
1878     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1880     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1881     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1882     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1884     SPObject *root;
1885     if (PREFS_SELECTION_ALL != inlayer) {
1886         root = selection->activeContext();
1887     } else {
1888         root = desktop->currentRoot();
1889     }
1891     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1893     if (item) {
1894         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1895         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1896             scroll_to_show_item(desktop, item);
1897         }
1898     }
1901 namespace {
1903 template <typename D>
1904 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1905                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1907     SPObject *current=root;
1908     while (items) {
1909         SPItem *item=SP_ITEM(items->data);
1910         if ( root->isAncestorOf(item) &&
1911              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1912         {
1913             current = item;
1914             break;
1915         }
1916         items = items->next;
1917     }
1919     GSList *path=NULL;
1920     while ( current != root ) {
1921         path = g_slist_prepend(path, current);
1922         current = SP_OBJECT_PARENT(current);
1923     }
1925     SPItem *next;
1926     // first, try from the current object
1927     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1928     g_slist_free(path);
1930     if (!next) { // if we ran out of objects, start over at the root
1931         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1932     }
1934     return next;
1937 template <typename D>
1938 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1939                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1941     typename D::Iterator children;
1942     typename D::Iterator iter;
1944     SPItem *found=NULL;
1946     if (path) {
1947         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1948         g_assert(SP_OBJECT_PARENT(object) == root);
1949         if (desktop->isLayer(object)) {
1950             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1951         }
1952         iter = children = D::siblings_after(object);
1953     } else {
1954         iter = children = D::children(root);
1955     }
1957     while ( iter && !found ) {
1958         SPObject *object=D::object(iter);
1959         if (desktop->isLayer(object)) {
1960             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1961                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1962             }
1963         } else if ( SP_IS_ITEM(object) &&
1964                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1965                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1966                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1967                     !desktop->isLayer(SP_ITEM(object)) )
1968         {
1969             found = SP_ITEM(object);
1970         }
1971         iter = D::next(iter);
1972     }
1974     D::dispose(children);
1976     return found;
1981 /**
1982  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1983  * \a item.
1984  */
1985 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1987     NR::Rect dbox = desktop->get_display_area();
1988     NR::Rect sbox = sp_item_bbox_desktop(item);
1990     if (dbox.contains(sbox) == false) {
1991         NR::Point const s_dt = sbox.midpoint();
1992         NR::Point const s_w = desktop->d2w(s_dt);
1993         NR::Point const d_dt = dbox.midpoint();
1994         NR::Point const d_w = desktop->d2w(d_dt);
1995         NR::Point const moved_w( d_w - s_w );
1996         gint const dx = (gint) moved_w[X];
1997         gint const dy = (gint) moved_w[Y];
1998         desktop->scroll_world(dx, dy);
1999     }
2003 void
2004 sp_selection_clone()
2006     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2007     if (desktop == NULL)
2008         return;
2010     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2012     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2014     // check if something is selected
2015     if (selection->isEmpty()) {
2016         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2017         return;
2018     }
2020     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2021   
2022     selection->clear();
2023   
2024     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2025     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2027     GSList *newsel = NULL;
2028  
2029     while (reprs) {
2030         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2031         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2033         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2034         sp_repr_set_attr(clone, "x", "0");
2035         sp_repr_set_attr(clone, "y", "0");
2036         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2038         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2039         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2040         
2041         // add the new clone to the top of the original's parent
2042         parent->appendChild(clone);
2044         newsel = g_slist_prepend(newsel, clone);
2045         reprs = g_slist_remove(reprs, sel_repr);
2046         Inkscape::GC::release(clone);
2047     }
2048     
2049     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2050                      _("Clone"));
2052     selection->setReprList(newsel);
2053  
2054     g_slist_free(newsel);
2057 void
2058 sp_selection_unlink()
2060     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2061     if (!desktop)
2062         return;
2064     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2066     if (selection->isEmpty()) {
2067         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2068         return;
2069     }
2071     // Get a copy of current selection.
2072     GSList *new_select = NULL;
2073     bool unlinked = false;
2074     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2075          items != NULL;
2076          items = items->next)
2077     {
2078         SPItem *use = (SPItem *) items->data;
2080         if (!SP_IS_USE(use)) {
2081             // keep the non-yse item in the new selection
2082             new_select = g_slist_prepend(new_select, use);
2083             continue;
2084         }
2086         SPItem *unlink = sp_use_unlink(SP_USE(use));
2087         unlinked = true;
2088         // Add ungrouped items to the new selection.
2089         new_select = g_slist_prepend(new_select, unlink);
2090     }
2092     if (new_select) { // set new selection
2093         selection->clear();
2094         selection->setList(new_select);
2095         g_slist_free(new_select);
2096     }
2097     if (!unlinked) {
2098         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2099     }
2101     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2102                      _("Unlink clone"));
2105 void
2106 sp_select_clone_original()
2108     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2109     if (desktop == NULL)
2110         return;
2112     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2114     SPItem *item = selection->singleItem();
2116     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.");
2118     // Check if other than two objects are selected
2119     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2120         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2121         return;
2122     }
2124     SPItem *original = NULL;
2125     if (SP_IS_USE(item)) {
2126         original = sp_use_get_original (SP_USE(item));
2127     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2128         original = sp_offset_get_source (SP_OFFSET(item));
2129     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2130         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2131     } else if (SP_IS_FLOWTEXT(item)) {
2132         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2133     } else { // it's an object that we don't know what to do with
2134         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2135         return;
2136     }
2138     if (!original) {
2139         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2140         return;
2141     }
2143     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2144         if (SP_IS_DEFS (o)) {
2145             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2146             return;
2147         }
2148     }
2150     if (original) {
2151         selection->clear();
2152         selection->set(original);
2153         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2154             scroll_to_show_item(desktop, original);
2155         }
2156     }
2159 void
2160 sp_selection_tile(bool apply)
2162     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2163     if (desktop == NULL)
2164         return;
2166     SPDocument *document = sp_desktop_document(desktop);
2167     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2169     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2171     // check if something is selected
2172     if (selection->isEmpty()) {
2173         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2174         return;
2175     }
2177     sp_document_ensure_up_to_date(document);
2178     NR::Rect r = selection->bounds();
2179     if (r.isEmpty()) {
2180         return;
2181     }
2183     // calculate the transform to be applied to objects to move them to 0,0
2184     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2185     move_p[NR::Y] = -move_p[NR::Y];
2186     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2188     GSList *items = g_slist_copy((GSList *) selection->itemList());
2190     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2192     // bottommost object, after sorting
2193     SPObject *parent = SP_OBJECT_PARENT (items->data);
2195     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2197     // remember the position of the first item
2198     gint pos = SP_OBJECT_REPR (items->data)->position();
2200     // create a list of duplicates
2201     GSList *repr_copies = NULL;
2202     for (GSList *i = items; i != NULL; i = i->next) {
2203         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2204         repr_copies = g_slist_prepend (repr_copies, dup);
2205     }
2207     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2209     if (apply) {
2210         // delete objects so that their clones don't get alerted; this object will be restored shortly
2211         for (GSList *i = items; i != NULL; i = i->next) {
2212             SPObject *item = SP_OBJECT (i->data);
2213             item->deleteObject (false);
2214         }
2215     }
2217     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2218     // without disturbing clones.
2219     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2220     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2221     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2223     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2224                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2226     // restore compensation setting
2227     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2229     if (apply) {
2230         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2231         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2233         NR::Point min = bounds.min() * parent_transform.inverse();
2234         NR::Point max = bounds.max() * parent_transform.inverse();
2236         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2237         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2238         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2239         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2241         // restore parent and position
2242         SP_OBJECT_REPR (parent)->appendChild(rect);
2243         rect->setPosition(pos > 0 ? pos : 0);
2244         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2246         Inkscape::GC::release(rect);
2248         selection->clear();
2249         selection->set(rectangle);
2250     }
2252     g_slist_free (items);
2254     sp_document_done (document, SP_VERB_EDIT_TILE, 
2255                       _("Objects to pattern"));
2258 void
2259 sp_selection_untile()
2261     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2262     if (desktop == NULL)
2263         return;
2265     SPDocument *document = sp_desktop_document(desktop);
2267     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2269     // check if something is selected
2270     if (selection->isEmpty()) {
2271         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2272         return;
2273     }
2275     GSList *new_select = NULL;
2277     bool did = false;
2279     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2280          items != NULL;
2281          items = items->next) {
2283         SPItem *item = (SPItem *) items->data;
2285         SPStyle *style = SP_OBJECT_STYLE (item);
2287         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2288             continue;
2290         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2292         if (!SP_IS_PATTERN(server))
2293             continue;
2295         did = true;
2297         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2299         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2300         pat_transform *= item->transform;
2302         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2303             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2304             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2306            // FIXME: relink clones to the new canvas objects
2307            // use SPObject::setid when mental finishes it to steal ids of
2309             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2310             sp_document_ensure_up_to_date (document);
2312             NR::Matrix transform( i->transform * pat_transform );
2313             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2315             new_select = g_slist_prepend(new_select, i);
2316         }
2318         SPCSSAttr *css = sp_repr_css_attr_new ();
2319         sp_repr_css_set_property (css, "fill", "none");
2320         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2321     }
2323     if (!did) {
2324         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2325     } else {
2326         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2327                          _("Pattern to objects"));
2328         selection->setList(new_select);
2329     }
2332 void
2333 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2335     if (selection->isEmpty()) {
2336         return;
2337     }
2339     const GSList * reprlst = selection->reprList();
2340     bool filename_search = TRUE;
2341     bool xdpi_search = TRUE;
2342     bool ydpi_search = TRUE;
2344     for(; reprlst != NULL &&
2345             filename_search &&
2346             xdpi_search &&
2347             ydpi_search;
2348         reprlst = reprlst->next) {
2349         const gchar * dpi_string;
2350         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2352         if (filename_search) {
2353             *filename = repr->attribute("inkscape:export-filename");
2354             if (*filename != NULL)
2355                 filename_search = FALSE;
2356         }
2358         if (xdpi_search) {
2359             dpi_string = NULL;
2360             dpi_string = repr->attribute("inkscape:export-xdpi");
2361             if (dpi_string != NULL) {
2362                 *xdpi = atof(dpi_string);
2363                 xdpi_search = FALSE;
2364             }
2365         }
2367         if (ydpi_search) {
2368             dpi_string = NULL;
2369             dpi_string = repr->attribute("inkscape:export-ydpi");
2370             if (dpi_string != NULL) {
2371                 *ydpi = atof(dpi_string);
2372                 ydpi_search = FALSE;
2373             }
2374         }
2375     }
2378 void
2379 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2381     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2382     const gchar * dpi_string;
2384     *filename = repr->attribute("inkscape:export-filename");
2386     dpi_string = NULL;
2387     dpi_string = repr->attribute("inkscape:export-xdpi");
2388     if (dpi_string != NULL) {
2389         *xdpi = atof(dpi_string);
2390     }
2392     dpi_string = NULL;
2393     dpi_string = repr->attribute("inkscape:export-ydpi");
2394     if (dpi_string != NULL) {
2395         *ydpi = atof(dpi_string);
2396     }
2399 void
2400 sp_selection_create_bitmap_copy ()
2402     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2403     if (desktop == NULL)
2404         return;
2406     SPDocument *document = sp_desktop_document(desktop);
2407     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2409     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2411     // check if something is selected
2412     if (selection->isEmpty()) {
2413         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2414         return;
2415     }
2417     // Get the bounding box of the selection
2418     NRRect bbox;
2419     sp_document_ensure_up_to_date (document);
2420     selection->bounds(&bbox);
2421     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2422         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2423     }
2425     // List of the items to show; all others will be hidden
2426     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2428     // Sort items so that the topmost comes last
2429     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2431     // Generate a random value from the current time (you may create bitmap from the same object(s)
2432     // multiple times, and this is done so that they don't clash)
2433     GTimeVal cu;
2434     g_get_current_time (&cu);
2435     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2437     // Create the filename
2438     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2439     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2440     // digits, and a few other chars, with "_"
2441     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2442     // Build the complete path by adding document->base if set
2443     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2445     //g_print ("%s\n", filepath);
2447     // Remember parent and z-order of the topmost one
2448     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2449     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2450     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2452     // Calculate resolution
2453     double res;
2454     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2455     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2456     if (0 < prefs_res) {
2457         // If it's given explicitly in prefs, take it
2458         res = prefs_res;
2459     } else if (0 < prefs_min) {
2460         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2461         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2462     } else {
2463         float hint_xdpi = 0, hint_ydpi = 0;
2464         const char *hint_filename;
2465         // take resolution hint from the selected objects
2466         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2467         if (hint_xdpi != 0) {
2468             res = hint_xdpi;
2469         } else {
2470             // take resolution hint from the document
2471             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2472             if (hint_xdpi != 0) {
2473                 res = hint_xdpi;
2474             } else {
2475                 // if all else fails, take the default 90 dpi
2476                 res = PX_PER_IN;
2477             }
2478         }
2479     }
2481     // The width and height of the bitmap in pixels
2482     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2483     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2485     // Find out if we have to run a filter
2486     const gchar *run = NULL;
2487     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2488     if (filter) {
2489         // filter command is given;
2490         // see if we have a parameter to pass to it
2491         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2492         if (param1) {
2493             if (param1[strlen(param1) - 1] == '%') {
2494                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2495                 gchar p1[256];
2496                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2497                 // the first param is always the image filename, the second is param1
2498                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2499             } else {
2500                 // otherwise pass the param1 unchanged
2501                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2502             }
2503         } else {
2504             // run without extra parameter
2505             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2506         }
2507     }
2509     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2510     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2511     NR::Matrix t;
2513     double shift_x = bbox.x0;
2514     double shift_y = bbox.y1; 
2515     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2516         shift_x = round (shift_x);
2517         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2518     }
2519     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2521     // Do the export
2522     sp_export_png_file(document, filepath,
2523                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2524                    width, height, res, res,
2525                    (guint32) 0xffffff00,
2526                    NULL, NULL,
2527                    true,  /*bool force_overwrite,*/
2528                    items);
2530     g_slist_free (items);
2532     // Run filter, if any
2533     if (run) {
2534         g_print ("Running external filter: %s\n", run);
2535         system (run);
2536     }
2538     // Import the image back
2539     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2540     if (pb) {
2541         // Create the repr for the image
2542         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2543         repr->setAttribute("xlink:href", filename);
2544         repr->setAttribute("sodipodi:absref", filepath);
2545         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2546             sp_repr_set_svg_double(repr, "width", width);
2547             sp_repr_set_svg_double(repr, "height", height);
2548         } else {
2549             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2550             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2551         }
2553         // Write transform
2554         gchar *c=sp_svg_transform_write(t);
2555         repr->setAttribute("transform", c);
2556         g_free(c);
2558         // add the new repr to the parent
2559         parent->appendChild(repr);
2561         // move to the saved position
2562         repr->setPosition(pos > 0 ? pos + 1 : 1);
2564         // Set selection to the new image
2565         selection->clear();
2566         selection->add(repr);
2568         // Clean up
2569         Inkscape::GC::release(repr);
2570         gdk_pixbuf_unref (pb);
2572         // Complete undoable transaction
2573         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2574                           _("Create bitmap"));
2575     }
2577     g_free (filename);
2578     g_free (filepath);
2581 /**
2582  * \brief sp_selection_set_mask
2583  *
2584  * This function creates a mask or clipPath from selection
2585  * Two different modes:
2586  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2587  *       and is applied to current layer
2588  *  otherwise, topmost object is used as mask for other objects
2589  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2590  * 
2591  */
2592 void
2593 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2595     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2596     if (desktop == NULL)
2597         return;
2599     SPDocument *document = sp_desktop_document(desktop);
2600     
2601     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2603     // check if something is selected
2604     bool is_empty = selection->isEmpty();
2605     if ( apply_to_layer && is_empty) {
2606         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2607         return;
2608     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2609         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2610         return;
2611     }
2613     // FIXME: temporary patch to prevent crash! 
2614     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2615     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2616     if (clone_with_original) {
2617         return; // in this version, you cannot clip/mask an object with its own clone
2618     }
2619     // /END FIXME
2620     
2621     sp_document_ensure_up_to_date(document);
2623     GSList *items = g_slist_copy((GSList *) selection->itemList());
2624     
2625     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2627     // create a list of duplicates
2628     GSList *mask_items = NULL;
2629     GSList *apply_to_items = NULL;
2630     GSList *items_to_delete = NULL;
2631     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2632     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2633     
2634     if (apply_to_layer) {
2635         // all selected items are used for mask, which is applied to a layer
2636         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2638         for (GSList *i = items; i != NULL; i = i->next) {
2639             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2640             mask_items = g_slist_prepend (mask_items, dup);
2642             if (remove_original) {
2643                 SPObject *item = SP_OBJECT (i->data);
2644                 items_to_delete = g_slist_prepend (items_to_delete, item);
2645             }
2646         }
2647     } else if (!topmost) {
2648         // topmost item is used as a mask, which is applied to other items in a selection
2649         GSList *i = items;
2650         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2651         mask_items = g_slist_prepend (mask_items, dup);
2653         if (remove_original) {
2654             SPObject *item = SP_OBJECT (i->data);
2655             items_to_delete = g_slist_prepend (items_to_delete, item);
2656         }
2657         
2658         for (i = i->next; i != NULL; i = i->next) {
2659             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2660         }
2661     } else {
2662         GSList *i = NULL;
2663         for (i = items; NULL != i->next; i = i->next) {
2664             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2665         }
2667         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2668         mask_items = g_slist_prepend (mask_items, dup);
2670         if (remove_original) {
2671             SPObject *item = SP_OBJECT (i->data);
2672             items_to_delete = g_slist_prepend (items_to_delete, item);
2673         }
2674     }
2675     
2676     g_slist_free (items);
2677     items = NULL;
2678             
2679     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2680     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2681         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2682         // inverted object transform should be applied to a mask object,
2683         // as mask is calculated in user space (after applying transform)
2684         NR::Matrix maskTransform (item->transform.inverse());
2686         GSList *mask_items_dup = NULL;
2687         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2688             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2689             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2690         }
2692         const gchar *mask_id = NULL;
2693         if (apply_clip_path) {
2694             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2695         } else {
2696             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2697         }
2699         g_slist_free (mask_items_dup);
2700         mask_items_dup = NULL;
2702         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2703     }
2705     g_slist_free (mask_items);
2706     g_slist_free (apply_to_items);
2708     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2709         SPObject *item = SP_OBJECT (i->data);
2710         item->deleteObject (false);
2711     }
2712     g_slist_free (items_to_delete);
2714     if (apply_clip_path) 
2715         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2716     else 
2717         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2720 void sp_selection_unset_mask(bool apply_clip_path) {
2721     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2722     if (desktop == NULL)
2723         return;
2724     
2725     SPDocument *document = sp_desktop_document(desktop);    
2726     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2728     // check if something is selected
2729     if (selection->isEmpty()) {
2730         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2731         return;
2732     }
2733     
2734     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2735     sp_document_ensure_up_to_date(document);
2737     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2738     std::map<SPObject*,SPItem*> referenced_objects;
2739     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2740         if (remove_original) {
2741             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2742             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2743             Inkscape::URIReference *uri_ref = NULL;
2744         
2745             if (apply_clip_path) {
2746                 uri_ref = item->clip_ref;
2747             } else {
2748                 uri_ref = item->mask_ref;
2749             }
2751             // collect distinct mask object (and associate with item to apply transform)
2752             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2753                 referenced_objects[uri_ref->getObject()] = item;
2754             }
2755         }
2757         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2758     }
2760     // restore mask objects into a document
2761     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2762         SPObject *obj = (*it).first;
2763         GSList *items_to_move = NULL;
2764         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2765             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2766             items_to_move = g_slist_prepend (items_to_move, copy);
2767         }
2769         if (!obj->isReferenced()) {
2770             // delete from defs if no other object references this mask
2771             obj->deleteObject(false);
2772         }
2774         // remember parent and position of the item to which the clippath/mask was applied
2775         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2776         gint pos = SP_OBJECT_REPR((*it).second)->position();
2778         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2779             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2781             // insert into parent, restore pos
2782             parent->appendChild(repr);
2783             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2785             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2786             selection->add(repr);
2788             // transform mask, so it is moved the same spot where mask was applied
2789             NR::Matrix transform (mask_item->transform);
2790             transform *= (*it).second->transform;
2791             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2792         }
2794         g_slist_free (items_to_move);
2795     }
2797     if (apply_clip_path) 
2798         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2799     else 
2800         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2803 void fit_canvas_to_selection(SPDesktop *desktop) {
2804     g_return_if_fail(desktop != NULL);
2805     SPDocument *doc = sp_desktop_document(desktop);
2807     g_return_if_fail(doc != NULL);
2808     g_return_if_fail(desktop->selection != NULL);
2809     g_return_if_fail(!desktop->selection->isEmpty());
2810     NRRect bbox = {0,0,0,0};
2812     desktop->selection->bounds(&bbox);
2813     if (!empty(bbox)) {
2814         doc->fitToRect(bbox);
2815     }
2816 };
2818 void fit_canvas_to_drawing(SPDocument *doc) {
2819     g_return_if_fail(doc != NULL);
2820     NRRect bbox = {0,0,0,0};
2822     sp_document_ensure_up_to_date (doc);
2823     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2825     if (!empty(bbox)) {
2826         doc->fitToRect(bbox);
2827     }
2828 };
2830 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2831     g_return_if_fail(desktop != NULL);
2832     SPDocument *doc = sp_desktop_document(desktop);
2834     g_return_if_fail(doc != NULL);
2835     g_return_if_fail(desktop->selection != NULL);
2837     if (desktop->selection->isEmpty()) {
2838         fit_canvas_to_drawing(doc);
2839     } else {
2840         fit_canvas_to_selection(desktop);
2841     }
2843     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2844                      _("Fit page to selection"));
2845 };
2847 /*
2848   Local Variables:
2849   mode:c++
2850   c-file-style:"stroustrup"
2851   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2852   indent-tabs-mode:nil
2853   fill-column:99
2854   End:
2855 */
2856 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :