Code

Replaced two tests with CxxTest versions.
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "sp-marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-flowtext.h"
39 #include "sp-flowregion.h"
40 #include "text-editing.h"
41 #include "text-context.h"
42 #include "dropper-context.h"
43 #include <glibmm/i18n.h>
44 #include "libnr/nr-matrix-rotate-ops.h"
45 #include "libnr/nr-matrix-translate-ops.h"
46 #include "libnr/nr-rotate-fns.h"
47 #include "libnr/nr-scale-ops.h"
48 #include "libnr/nr-scale-translate-ops.h"
49 #include "libnr/nr-translate-matrix-ops.h"
50 #include "libnr/nr-translate-scale-ops.h"
51 #include "xml/repr.h"
52 #include "style.h"
53 #include "document-private.h"
54 #include "sp-gradient.h"
55 #include "sp-gradient-reference.h"
56 #include "sp-linear-gradient-fns.h"
57 #include "sp-pattern.h"
58 #include "sp-radial-gradient-fns.h"
59 #include "sp-namedview.h"
60 #include "prefs-utils.h"
61 #include "sp-offset.h"
62 #include "sp-clippath.h"
63 #include "sp-mask.h"
64 #include "file.h"
65 #include "layer-fns.h"
66 #include "context-fns.h"
67 #include <map>
68 #include "helper/units.h"
69 #include "sp-item.h"
70 using NR::X;
71 using NR::Y;
73 #include "selection-chemistry.h"
75 /* fixme: find a better place */
76 GSList *clipboard = NULL;
77 GSList *defs_clipboard = NULL;
78 SPCSSAttr *style_clipboard = NULL;
79 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
81 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
83 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
84 {
85     Inkscape::XML::Node *copy = repr->duplicate();
87     // copy complete inherited style
88     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
89     sp_repr_css_set(copy, css, "style");
90     sp_repr_css_attr_unref(css);
92     // write the complete accummulated transform passed to us
93     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
94     gchar affinestr[80];
95     if (sp_svg_transform_write(affinestr, 79, full_t)) {
96         copy->setAttribute("transform", affinestr);
97     } else {
98         copy->setAttribute("transform", NULL);
99     }
101     *clip = g_slist_prepend(*clip, copy);
104 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
107     // Copy stuff referenced by all items to defs_clip:
108     if (defs_clip) {
109         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
110             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
111         }
112         *defs_clip = g_slist_reverse(*defs_clip);
113     }
115     // Store style:
116     if (style_clip) {
117         SPItem *item = SP_ITEM (items->data); // take from the first selected item
118         *style_clip = take_style_from_item (item);
119     }
121     if (clip) {
122         // Sort items:
123         GSList *sorted_items = g_slist_copy ((GSList *) items);
124         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
126         // Copy item reprs:
127         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
128             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
129         }
131         *clip = g_slist_reverse(*clip);
132         g_slist_free ((GSList *) sorted_items);
133     }
136 /**
137 Add gradients/patterns/markers referenced by copied objects to defs
138 */
139 void
140 paste_defs (GSList **defs_clip, SPDocument *doc)
142     if (!defs_clip)
143         return;
145     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
146         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
147         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
148         gchar const *id = repr->attribute("id");
149         if (!id || !doc->getObjectById(id)) {
150             Inkscape::XML::Node *copy = repr->duplicate();
151             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
152             Inkscape::GC::release(copy);
153         }
154     }
157 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
159     paste_defs (defs_clip, document);
161     GSList *copied = NULL;
162     // add objects to document
163     for (GSList *l = *clip; l != NULL; l = l->next) {
164         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
165         Inkscape::XML::Node *copy = repr->duplicate();
167         // premultiply the item transform by the accumulated parent transform in the paste layer
168         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
169         if (!local.test_identity()) {
170             gchar const *t_str = copy->attribute("transform");
171             NR::Matrix item_t (NR::identity());
172             if (t_str)
173                 sp_svg_transform_read(t_str, &item_t);
174             item_t *= local.inverse();
175             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
176             gchar affinestr[80];
177             if (sp_svg_transform_write(affinestr, 79, item_t)) {
178                 copy->setAttribute("transform", affinestr);
179             } else {
180                 copy->setAttribute("transform", NULL);
181             }
182         }
184         parent->appendChildRepr(copy);
185         copied = g_slist_prepend(copied, copy);
186         Inkscape::GC::release(copy);
187     }
188     return copied;
191 void sp_selection_delete_impl(const GSList *items)
193     for (const GSList *i = items ; i ; i = i->next ) {
194         sp_object_ref((SPObject *)i->data, NULL);
195     }
196     for (const GSList *i = items; i != NULL; i = i->next) {
197         SPItem *item = (SPItem *) i->data;
198         SP_OBJECT(item)->deleteObject();
199         sp_object_unref((SPObject *)item, NULL);
200     }
204 void sp_selection_delete()
206     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
207     if (desktop == NULL) {
208         return;
209     }
211     if (tools_isactive (desktop, TOOLS_TEXT))
212         if (sp_text_delete_selection(desktop->event_context)) {
213             sp_document_done(sp_desktop_document(desktop));
214             return;
215         }
217     Inkscape::Selection *selection = sp_desktop_selection(desktop);
219     // check if something is selected
220     if (selection->isEmpty()) {
221         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
222         return;
223     }
225     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
226     selection->clear();
227     sp_selection_delete_impl (selected);
228     g_slist_free ((GSList *) selected);
230     /* a tool may have set up private information in it's selection context
231      * that depends on desktop items.  I think the only sane way to deal with
232      * this currently is to reset the current tool, which will reset it's
233      * associated selection context.  For example: deleting an object
234      * while moving it around the canvas.
235      */
236     tools_switch ( desktop, tools_active ( desktop ) );
238     sp_document_done(sp_desktop_document(desktop));
241 /* fixme: sequencing */
242 void sp_selection_duplicate()
244     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
245     if (desktop == NULL)
246         return;
248     Inkscape::Selection *selection = sp_desktop_selection(desktop);
250     // check if something is selected
251     if (selection->isEmpty()) {
252         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
253         return;
254     }
256     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
258     selection->clear();
260     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
261     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
263     GSList *newsel = NULL;
265     while (reprs) {
266         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
267         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
269         parent->appendChild(copy);
271         newsel = g_slist_prepend(newsel, copy);
272         reprs = g_slist_remove(reprs, reprs->data);
273         Inkscape::GC::release(copy);
274     }
276     sp_document_done(sp_desktop_document(desktop));
278     selection->setReprList(newsel);
280     g_slist_free(newsel);
283 void sp_edit_clear_all()
285     SPDesktop *dt = SP_ACTIVE_DESKTOP;
286     if (!dt)
287         return;
289     SPDocument *doc = sp_desktop_document(dt);
290     sp_desktop_selection(dt)->clear();
292     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
293     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
295     while (items) {
296         SP_OBJECT (items->data)->deleteObject();
297         items = g_slist_remove(items, items->data);
298     }
300     sp_document_done(doc);
303 GSList *
304 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
306     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
307         if (SP_IS_ITEM(child) &&
308             !desktop->isLayer(SP_ITEM(child)) &&
309             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
310             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
311             (!exclude || !g_slist_find ((GSList *) exclude, child))
312             )
313         {
314             list = g_slist_prepend (list, SP_ITEM(child));
315         }
317         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
318             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
319         }
320     }
322     return list;
325 void sp_edit_select_all_full (bool force_all_layers, bool invert)
327     SPDesktop *dt = SP_ACTIVE_DESKTOP;
328     if (!dt)
329         return;
331     Inkscape::Selection *selection = sp_desktop_selection(dt);
333     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
335     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
336     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
337     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
339     GSList *items = NULL;
341     const GSList *exclude = NULL;
342     if (invert) {
343         exclude = selection->itemList();
344     }
346     if (force_all_layers)
347         inlayer = PREFS_SELECTION_ALL;
349     switch (inlayer) {
350         case PREFS_SELECTION_LAYER: {
351         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
352              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
353         return;
355         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
357         for (GSList *i = all_items; i; i = i->next) {
358             SPItem *item = SP_ITEM (i->data);
360             if (item && (!onlysensitive || !item->isLocked())) {
361                 if (!onlyvisible || !dt->itemIsHidden(item)) {
362                     if (!dt->isLayer(item)) {
363                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
364                             items = g_slist_prepend (items, item); // leave it in the list
365                         }
366                     }
367                 }
368             }
369         }
371         g_slist_free (all_items);
372             break;
373         }
374         case PREFS_SELECTION_LAYER_RECURSIVE: {
375             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
376             break;
377         }
378         default: {
379         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
380             break;
381     }
382     }
384     selection->setList (items);
386     if (items) {
387         g_slist_free (items);
388     }
391 void sp_edit_select_all ()
393     sp_edit_select_all_full (false, false);
396 void sp_edit_select_all_in_all_layers ()
398     sp_edit_select_all_full (true, false);
401 void sp_edit_invert ()
403     sp_edit_select_all_full (false, true);
406 void sp_edit_invert_in_all_layers ()
408     sp_edit_select_all_full (true, true);
411 void sp_selection_group()
413     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
414     if (desktop == NULL)
415         return;
417     SPDocument *document = sp_desktop_document (desktop);
419     Inkscape::Selection *selection = sp_desktop_selection(desktop);
421     // Check if something is selected.
422     if (selection->isEmpty()) {
423         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
424         return;
425     }
427     GSList const *l = (GSList *) selection->reprList();
429     // Check if at least two objects are selected.
430     if (l->next == NULL) {
431         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
432         return;
433     }
435     GSList *p = g_slist_copy((GSList *) l);
437     selection->clear();
439     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
441     // Remember the position and parent of the topmost object.
442     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
443     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
445     Inkscape::XML::Node *group = sp_repr_new("svg:g");
447     while (p) {
448         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
450         if (current->parent() == topmost_parent) {
451             Inkscape::XML::Node *spnew = current->duplicate();
452             sp_repr_unparent(current);
453             group->appendChild(spnew);
454             Inkscape::GC::release(spnew);
455             topmost --; // only reduce count for those items deleted from topmost_parent
456         } else { // move it to topmost_parent first
457                 GSList *temp_clip = NULL;
459                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
460                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
461                 gchar const *t_str = current->attribute("transform");
462                 NR::Matrix item_t (NR::identity());
463                 if (t_str)
464                     sp_svg_transform_read(t_str, &item_t);
465                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
466                 //FIXME: when moving both clone and original from a transformed group (either by
467                 //grouping into another parent, or by cut/paste) the transform from the original's
468                 //parent becomes embedded into original itself, and this affects its clones. Fix
469                 //this by remembering the transform diffs we write to each item into an array and
470                 //then, if this is clone, looking up its original in that array and pre-multiplying
471                 //it by the inverse of that original's transform diff.
473                 sp_selection_copy_one (current, item_t, &temp_clip);
474                 sp_repr_unparent(current);
476                 // paste into topmost_parent (temporarily)
477                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
478                 if (temp_clip) g_slist_free (temp_clip);
479                 if (copied) { // if success,
480                     // take pasted object (now in topmost_parent)
481                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
482                     // make a copy
483                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
484                     // remove pasted
485                     sp_repr_unparent(in_topmost);
486                     // put its copy into group
487                     group->appendChild(spnew);
488                     Inkscape::GC::release(spnew);
489                     g_slist_free (copied);
490                 }
491         }
492         p = g_slist_remove(p, current);
493     }
495     // Add the new group to the topmost members' parent
496     topmost_parent->appendChild(group);
498     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
499     group->setPosition(topmost + 1);
501     sp_document_done(sp_desktop_document(desktop));
503     selection->set(group);
504     Inkscape::GC::release(group);
507 void sp_selection_ungroup()
509     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
510     if (desktop == NULL)
511         return;
513     Inkscape::Selection *selection = sp_desktop_selection(desktop);
515     if (selection->isEmpty()) {
516         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
517         return;
518     }
520     GSList *items = g_slist_copy((GSList *) selection->itemList());
521     selection->clear();
523     // Get a copy of current selection.
524     GSList *new_select = NULL;
525     bool ungrouped = false;
526     for (GSList *i = items;
527          i != NULL;
528          i = i->next)
529     {
530         SPItem *group = (SPItem *) i->data;
532         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
533         if (!SP_IS_OBJECT(group)) {
534             continue;
535         }
537         /* We do not allow ungrouping <svg> etc. (lauris) */
538         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
539             // keep the non-group item in the new selection
540             selection->add(group);
541             continue;
542         }
544         GSList *children = NULL;
545         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
546         sp_item_group_ungroup(SP_GROUP(group), &children, false);
547         ungrouped = true;
548         // Add ungrouped items to the new selection.
549         new_select = g_slist_concat(new_select, children);
550     }
552     if (new_select) { // Set new selection.
553         selection->addList(new_select);
554         g_slist_free(new_select);
555     }
556     if (!ungrouped) {
557         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
558     }
560     g_slist_free(items);
562     sp_document_done(sp_desktop_document(desktop));
565 static SPGroup *
566 sp_item_list_common_parent_group(const GSList *items)
568     if (!items) {
569         return NULL;
570     }
571     SPObject *parent = SP_OBJECT_PARENT(items->data);
572     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
573     if (!SP_IS_GROUP(parent)) {
574         return NULL;
575     }
576     for (items = items->next; items; items = items->next) {
577         if (SP_OBJECT_PARENT(items->data) != parent) {
578             return NULL;
579         }
580     }
582     return SP_GROUP(parent);
585 /** Finds out the minimum common bbox of the selected items
586  */
587 NR::Rect
588 enclose_items(const GSList *items)
590     g_assert(items != NULL);
592     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
594     for (GSList *i = items->next; i; i = i->next) {
595         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
596     }
598     return r;
601 SPObject *
602 prev_sibling(SPObject *child)
604     SPObject *parent = SP_OBJECT_PARENT(child);
605     if (!SP_IS_GROUP(parent)) {
606         return NULL;
607     }
608     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
609         if (i->next == child)
610             return i;
611     }
612     return NULL;
615 void
616 sp_selection_raise()
618     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
619     if (!desktop)
620         return;
622     Inkscape::Selection *selection = sp_desktop_selection(desktop);
624     GSList const *items = (GSList *) selection->itemList();
625     if (!items) {
626         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
627         return;
628     }
630     SPGroup const *group = sp_item_list_common_parent_group(items);
631     if (!group) {
632         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
633         return;
634     }
636     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
638     /* construct reverse-ordered list of selected children */
639     GSList *rev = g_slist_copy((GSList *) items);
640     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
642     // find out the common bbox of the selected items
643     NR::Rect selected = enclose_items(items);
645     // for all objects in the selection (starting from top)
646     while (rev) {
647         SPObject *child = SP_OBJECT(rev->data);
648         // for each selected object, find the next sibling
649         for (SPObject *newref = child->next; newref; newref = newref->next) {
650             // if the sibling is an item AND overlaps our selection,
651             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
652                 // AND if it's not one of our selected objects,
653                 if (!g_slist_find((GSList *) items, newref)) {
654                     // move the selected object after that sibling
655                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
656                 }
657                 break;
658             }
659         }
660         rev = g_slist_remove(rev, child);
661     }
663     sp_document_done(sp_desktop_document(desktop));
666 void sp_selection_raise_to_top()
668     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
669     if (desktop == NULL)
670         return;
672     SPDocument *document = sp_desktop_document(desktop);
673     Inkscape::Selection *selection = sp_desktop_selection(desktop);
675     if (selection->isEmpty()) {
676         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
677         return;
678     }
680     GSList const *items = (GSList *) selection->itemList();
682     SPGroup const *group = sp_item_list_common_parent_group(items);
683     if (!group) {
684         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
685         return;
686     }
688     GSList *rl = g_slist_copy((GSList *) selection->reprList());
689     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
691     for (GSList *l = rl; l != NULL; l = l->next) {
692         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
693         repr->setPosition(-1);
694     }
696     g_slist_free(rl);
698     sp_document_done(document);
701 void
702 sp_selection_lower()
704     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
705     if (desktop == NULL)
706         return;
708     Inkscape::Selection *selection = sp_desktop_selection(desktop);
710     GSList const *items = (GSList *) selection->itemList();
711     if (!items) {
712         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
713         return;
714     }
716     SPGroup const *group = sp_item_list_common_parent_group(items);
717     if (!group) {
718         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
719         return;
720     }
722     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
724     // find out the common bbox of the selected items
725     NR::Rect selected = enclose_items(items);
727     /* construct direct-ordered list of selected children */
728     GSList *rev = g_slist_copy((GSList *) items);
729     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
730     rev = g_slist_reverse(rev);
732     // for all objects in the selection (starting from top)
733     while (rev) {
734         SPObject *child = SP_OBJECT(rev->data);
735         // for each selected object, find the prev sibling
736         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
737             // if the sibling is an item AND overlaps our selection,
738             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
739                 // AND if it's not one of our selected objects,
740                 if (!g_slist_find((GSList *) items, newref)) {
741                     // move the selected object before that sibling
742                     SPObject *put_after = prev_sibling(newref);
743                     if (put_after)
744                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
745                     else
746                         SP_OBJECT_REPR(child)->setPosition(0);
747                 }
748                 break;
749             }
750         }
751         rev = g_slist_remove(rev, child);
752     }
754     sp_document_done(sp_desktop_document(desktop));
758 void sp_selection_lower_to_bottom()
760     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
761     if (desktop == NULL)
762         return;
764     SPDocument *document = sp_desktop_document(desktop);
765     Inkscape::Selection *selection = sp_desktop_selection(desktop);
767     if (selection->isEmpty()) {
768         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
769         return;
770     }
772     GSList const *items = (GSList *) selection->itemList();
774     SPGroup const *group = sp_item_list_common_parent_group(items);
775     if (!group) {
776         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
777         return;
778     }
780     GSList *rl;
781     rl = g_slist_copy((GSList *) selection->reprList());
782     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
783     rl = g_slist_reverse(rl);
785     for (GSList *l = rl; l != NULL; l = l->next) {
786         gint minpos;
787         SPObject *pp, *pc;
788         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
789         pp = document->getObjectByRepr(sp_repr_parent(repr));
790         minpos = 0;
791         g_assert(SP_IS_GROUP(pp));
792         pc = sp_object_first_child(pp);
793         while (!SP_IS_ITEM(pc)) {
794             minpos += 1;
795             pc = pc->next;
796         }
797         repr->setPosition(minpos);
798     }
800     g_slist_free(rl);
802     sp_document_done(document);
805 void
806 sp_undo(SPDesktop *desktop, SPDocument *)
808         if (!sp_document_undo(sp_desktop_document(desktop)))
809             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
812 void
813 sp_redo(SPDesktop *desktop, SPDocument *)
815         if (!sp_document_redo(sp_desktop_document(desktop)))
816             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
819 void sp_selection_cut()
821     sp_selection_copy();
822     sp_selection_delete();
825 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
827     SPGradient *ref = gradient;
829     while (ref) {
830         // climb up the refs, copying each one in the chain
831         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
832         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
834         ref = ref->ref->getObject();
835     }
838 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
840     SPPattern *ref = pattern;
842     while (ref) {
843         // climb up the refs, copying each one in the chain
844         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
845         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
847         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
848         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
849             if (!SP_IS_ITEM (child))
850                 continue;
851             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
852         }
854         ref = ref->ref->getObject();
855     }
858 void sp_copy_single (GSList **defs_clip, SPObject *thing)
860     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
861     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
865 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
867     SPItem *path = sp_textpath_get_path_item (tp);
868     if (!path)
869         return;
870     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
871         return;
872     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
873     *defs_clip = g_slist_prepend (*defs_clip, repr);
876 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
878     SPStyle *style = SP_OBJECT_STYLE (item);
880     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
881         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
882         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
883             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
884         if (SP_IS_PATTERN (server))
885             sp_copy_pattern (defs_clip, SP_PATTERN(server));
886     }
888     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
889         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
890         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
891             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
892         if (SP_IS_PATTERN (server))
893             sp_copy_pattern (defs_clip, SP_PATTERN(server));
894     }
896     if (SP_IS_SHAPE (item)) {
897         SPShape *shape = SP_SHAPE (item);
898         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
899             if (shape->marker[i]) {
900                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
901             }
902         }
903     }
905     if (SP_IS_TEXT_TEXTPATH (item)) {
906         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
907     }
909     if (item->clip_ref->getObject()) {
910         sp_copy_single (defs_clip, item->clip_ref->getObject());
911     }
913     if (item->mask_ref->getObject()) {
914         SPObject *mask = item->mask_ref->getObject();
915         sp_copy_single (defs_clip, mask);
916         // recurse into the mask for its gradients etc.
917         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
918             if (SP_IS_ITEM(o))
919                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
920         }
921     }
923     // recurse
924     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
925         if (SP_IS_ITEM(o))
926             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
927     }
930 /**
931  * \pre item != NULL
932  */
933 SPCSSAttr *
934 take_style_from_item (SPItem *item)
936     // write the complete cascaded style, context-free
937     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
938     if (css == NULL)
939         return NULL;
941     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
942         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
943         // if this is a text with exactly one tspan child, merge the style of that tspan as well
944         // If this is a group, merge the style of its topmost (last) child with style
945         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
946             if (SP_OBJECT_STYLE (last_element) != NULL) {
947                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
948                 if (temp) {
949                     sp_repr_css_merge (css, temp);
950                     sp_repr_css_attr_unref (temp);
951                 }
952                 break;
953             }
954         }
955     }
956     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
957         // do not copy text properties from non-text objects, it's confusing
958         css = sp_css_attr_unset_text (css);
959     }
961     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
962     double ex = NR::expansion(sp_item_i2doc_affine(item));
963     if (ex != 1.0) {
964         css = sp_css_attr_scale (css, ex);
965     }
967     return css;
971 void sp_selection_copy()
973     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
974     if (desktop == NULL)
975         return;
977     Inkscape::Selection *selection = sp_desktop_selection(desktop);
979     if (tools_isactive (desktop, TOOLS_DROPPER)) {
980         sp_dropper_context_copy(desktop->event_context);
981         return; // copied color under cursor, nothing else to do
982     }
984     // check if something is selected
985     if (selection->isEmpty()) {
986         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
987         return;
988     }
990     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
992     // 0. Copy text to system clipboard
993     // FIXME: for non-texts, put serialized XML as text to the clipboard;
994     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
995     Glib::ustring text;
996     if (tools_isactive (desktop, TOOLS_TEXT)) {
997         text = sp_text_get_selected_text(desktop->event_context);
998     }
1000     if (text.empty()) {
1001         guint texts = 0;
1002         for (GSList *i = (GSList *) items; i; i = i->next) {
1003             SPItem *item = SP_ITEM (i->data);
1004             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1005                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1006                     text += " ";
1007                 gchar *this_text = sp_te_get_string_multiline (item);
1008                 if (this_text) {
1009                     text += this_text;
1010                     g_free(this_text);
1011                 }
1012                 texts++;
1013             }
1014         }
1015     }
1016     if (!text.empty()) {
1017         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1018         refClipboard->set_text(text);
1019     }
1021     // clear old defs clipboard
1022     while (defs_clipboard) {
1023         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1024         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1025     }
1027     // clear style clipboard
1028     if (style_clipboard) {
1029         sp_repr_css_attr_unref (style_clipboard);
1030         style_clipboard = NULL;
1031     }
1033     //clear main clipboard
1034     while (clipboard) {
1035         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1036         clipboard = g_slist_remove(clipboard, clipboard->data);
1037     }
1039     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1041     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1042         SPStyle *const query = sp_style_new();
1043         if (sp_desktop_query_style_all (desktop, query)) {
1044             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1045             if (css != NULL) {
1046                 // clear style clipboard
1047                 if (style_clipboard) {
1048                     sp_repr_css_attr_unref (style_clipboard);
1049                     style_clipboard = NULL;
1050                 }
1051                 //sp_repr_css_print (css);
1052                 style_clipboard = css;
1053             }
1054         }
1055         g_free (query);
1056     }
1058     size_clipboard = selection->bounds();
1060     g_slist_free ((GSList *) items);
1063 void sp_selection_paste(bool in_place)
1065     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1067     if (desktop == NULL) {
1068         return;
1069     }
1071     SPDocument *document = sp_desktop_document(desktop);
1073     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1074         return;
1075     }
1077     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1079     if (tools_isactive (desktop, TOOLS_TEXT)) {
1080         if (sp_text_paste_inline(desktop->event_context))
1081             return; // pasted from system clipboard into text, nothing else to do
1082     }
1084     // check if something is in the clipboard
1085     if (clipboard == NULL) {
1086         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1087         return;
1088     }
1090     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1091     // add pasted objects to selection
1092     selection->setReprList((GSList const *) copied);
1093     g_slist_free (copied);
1095     if (!in_place) {
1096         sp_document_ensure_up_to_date(document);
1098         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1100         /* Snap the offset of the new item(s) to the grid */
1101         /* FIXME: this gridsnap fiddling is a hack. */
1102         Inkscape::GridSnapper &s = desktop->namedview->grid_snapper;
1103         gdouble const curr_gridsnap = s.getDistance();
1104         s.setDistance(NR_HUGE);
1105         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1106         s.setDistance(curr_gridsnap);
1107         sp_selection_move_relative(selection, m);
1108     }
1110     sp_document_done(document);
1113 void sp_selection_paste_style()
1115     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1116     if (desktop == NULL) return;
1118     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1120     // check if something is in the clipboard
1121     if (clipboard == NULL) {
1122         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1123         return;
1124     }
1126     // check if something is selected
1127     if (selection->isEmpty()) {
1128         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1129         return;
1130     }
1132     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1134     sp_desktop_set_style (desktop, style_clipboard);
1136     sp_document_done(sp_desktop_document (desktop));
1139 void sp_selection_paste_size (bool apply_x, bool apply_y)
1141     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1142     if (desktop == NULL) return;
1144     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1146     // check if something is in the clipboard
1147     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1148         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1149         return;
1150     }
1152     // check if something is selected
1153     if (selection->isEmpty()) {
1154         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1155         return;
1156     }
1158     NR::Rect current = selection->bounds();
1159     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1160         return;
1161     }
1163     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1164     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1166     sp_selection_scale_relative (selection, current.midpoint(), 
1167                                  NR::scale(
1168                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1169                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1171     sp_document_done(sp_desktop_document (desktop));
1174 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1176     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1177     if (desktop == NULL) return;
1179     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1181     // check if something is in the clipboard
1182     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1183         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1184         return;
1185     }
1187     // check if something is selected
1188     if (selection->isEmpty()) {
1189         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1190         return;
1191     }
1193     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1194         SPItem *item = SP_ITEM(l->data);
1196         NR::Rect current = sp_item_bbox_desktop(item);
1197         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1198             continue;
1199         }
1201         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1202         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1204         sp_item_scale_rel (item,
1205                                  NR::scale(
1206                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1207                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1209     }
1211     sp_document_done(sp_desktop_document (desktop));
1214 void sp_selection_to_next_layer ()
1216     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1218     Inkscape::Selection *selection = sp_desktop_selection(dt);
1220     // check if something is selected
1221     if (selection->isEmpty()) {
1222         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1223         return;
1224     }
1226     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1228     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1229     if (next) {
1230         GSList *temp_clip = NULL;
1231         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1232         sp_selection_delete_impl (items);
1233         GSList *copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1234         selection->setReprList((GSList const *) copied);
1235         g_slist_free (copied);
1236         if (temp_clip) g_slist_free (temp_clip);
1237         dt->setCurrentLayer(next);
1238         sp_document_done(sp_desktop_document (dt));
1239     } else {
1240         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1241     }
1243     g_slist_free ((GSList *) items);
1246 void sp_selection_to_prev_layer ()
1248     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1250     Inkscape::Selection *selection = sp_desktop_selection(dt);
1252     // check if something is selected
1253     if (selection->isEmpty()) {
1254         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1255         return;
1256     }
1258     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1260     SPObject *next=Inkscape::previous_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         GSList *copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1266         selection->setReprList((GSList const *) copied);
1267         g_slist_free (copied);
1268         if (temp_clip) g_slist_free (temp_clip);
1269         dt->setCurrentLayer(next);
1270         sp_document_done(sp_desktop_document (dt));
1271     } else {
1272         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1273     }
1275     g_slist_free ((GSList *) items);
1278 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1279 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1280 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1281 that case, items are already in the new position, but the repr is in the old, and this function
1282 then simply updates the repr from item->transform.
1283  */
1284 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1286     if (selection->isEmpty())
1287         return;
1289     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1290         SPItem *item = SP_ITEM(l->data);
1292         NR::Point old_center(0,0);
1293         if (set_i2d && item->isCenterSet())
1294             old_center = item->getCenter();
1296 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1297          At the time of writing, this is the only place to re-enable. */
1298         sp_item_update_cns(*item, selection->desktop());
1299 #endif
1301         // we're moving both a clone and its original
1302         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1303         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)))) ));
1304         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1305         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1307         // "clones are unmoved when original is moved" preference
1308         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1309         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1310         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1312         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1313         // transform of its original and respond to it itself. Without this, a clone is doubly
1314         // transformed, very unintuitive.
1315       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1316       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1317       // Same for linked offset if we are also moving its source: do not move it.
1318         if (transform_textpath_with_path || transform_offset_with_source) {
1319                 // restore item->transform field from the repr, in case it was changed by seltrans
1320             sp_object_read_attr (SP_OBJECT (item), "transform");
1322         } else if (transform_flowtext_with_frame) {
1323             // apply the inverse of the region's transform to the <use> so that the flow remains
1324             // the same (even though the output itself gets transformed)
1325             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1326                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1327                     continue;
1328                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1329                     if (!SP_IS_USE(use)) continue;
1330                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1331                 }
1332             }
1333         } else if (transform_clone_with_original) {
1334             // We are transforming a clone along with its original. The below matrix juggling is
1335             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1336             // transform and its move compensation are both cancelled out.
1338             // restore item->transform field from the repr, in case it was changed by seltrans
1339             sp_object_read_attr (SP_OBJECT (item), "transform");
1341             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1342             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1343             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1344             NR::Matrix result = t_inv * item->transform * t;
1346             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1347                 // we need to cancel out the move compensation, too
1349                 // find out the clone move, same as in sp_use_move_compensate
1350                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1351                 NR::Matrix clone_move = parent.inverse() * t * parent;
1353                 if (prefs_parallel) {
1354                     NR::Matrix move = result * clone_move * t_inv;
1355                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1357                 } else if (prefs_unmoved) {
1358                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1359                         clone_move = NR::identity();
1360                     NR::Matrix move = result * clone_move;
1361                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1362                 }
1364             } else {
1365                 // just apply the result
1366                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1367             }
1369         } else {
1370             if (set_i2d) {
1371                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1372             }
1373             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1374         }
1376         // if we're moving the actual object, not just updating the repr, we can transform the
1377         // center by the same matrix (only necessary for non-translations)
1378         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1379             item->setCenter(old_center * affine);
1380             SP_OBJECT(item)->updateRepr();
1381         }
1382     }
1385 void sp_selection_remove_transform()
1387     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1388     if (desktop == NULL)
1389         return;
1391     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1393     GSList const *l = (GSList *) selection->reprList();
1394     while (l != NULL) {
1395         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1396         l = l->next;
1397     }
1399     sp_document_done(sp_desktop_document(desktop));
1402 void
1403 sp_selection_scale_absolute(Inkscape::Selection *selection,
1404                             double const x0, double const x1,
1405                             double const y0, double const y1)
1407     if (selection->isEmpty())
1408         return;
1410     NR::Rect const bbox(selection->bounds());
1411     if (bbox.isEmpty()) {
1412         return;
1413     }
1415     NR::translate const p2o(-bbox.min());
1417     NR::scale const newSize(x1 - x0,
1418                             y1 - y0);
1419     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1420     NR::translate const o2n(x0, y0);
1421     NR::Matrix const final( p2o * scale * o2n );
1423     sp_selection_apply_affine(selection, final);
1427 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1429     if (selection->isEmpty())
1430         return;
1432     NR::Rect const bbox(selection->bounds());
1434     if (bbox.isEmpty()) {
1435         return;
1436     }
1438     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1439     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1440          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1441     {
1442         return;
1443     }
1445     NR::translate const n2d(-align);
1446     NR::translate const d2n(align);
1447     NR::Matrix const final( n2d * scale * d2n );
1448     sp_selection_apply_affine(selection, final);
1451 void
1452 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1454     NR::translate const d2n(center);
1455     NR::translate const n2d(-center);
1456     NR::rotate const rotate(rotate_degrees(angle_degrees));
1457     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1458     sp_selection_apply_affine(selection, final);
1461 void
1462 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1464     NR::translate const d2n(align);
1465     NR::translate const n2d(-align);
1466     NR::Matrix const skew(1, dy,
1467                           dx, 1,
1468                           0, 0);
1469     NR::Matrix const final( n2d * skew * d2n );
1470     sp_selection_apply_affine(selection, final);
1473 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1475     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1478 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1480     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1484 /**
1485  * \brief sp_selection_rotate_90
1486  *
1487  * This function rotates selected objects 90 degrees clockwise.
1488  *
1489  */
1491 void sp_selection_rotate_90_cw()
1493     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1495     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1497     if (selection->isEmpty())
1498         return;
1500     GSList const *l = selection->itemList();
1501     NR::rotate const rot_neg_90(NR::Point(0, -1));
1502     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1503         SPItem *item = SP_ITEM(l2->data);
1504         sp_item_rotate_rel(item, rot_neg_90);
1505     }
1507     sp_document_done(sp_desktop_document(desktop));
1511 /**
1512  * \brief sp_selection_rotate_90_ccw
1513  *
1514  * This function rotates selected objects 90 degrees counter-clockwise.
1515  *
1516  */
1518 void sp_selection_rotate_90_ccw()
1520     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1522     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1524     if (selection->isEmpty())
1525         return;
1527     GSList const *l = selection->itemList();
1528     NR::rotate const rot_neg_90(NR::Point(0, 1));
1529     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1530         SPItem *item = SP_ITEM(l2->data);
1531         sp_item_rotate_rel(item, rot_neg_90);
1532     }
1534     sp_document_done(sp_desktop_document(desktop));
1537 void
1538 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1540     if (selection->isEmpty())
1541         return;
1543     NR::Point center = selection->center();
1545     sp_selection_rotate_relative(selection, center, angle_degrees);
1547     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1548                            ( ( angle_degrees > 0 )
1549                              ? "selector:rotate:ccw"
1550                              : "selector:rotate:cw" ));
1553 /**
1554 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1555 */
1556 void
1557 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1559     if (selection->isEmpty())
1560         return;
1562     NR::Rect const bbox(selection->bounds());
1564     NR::Point center = selection->center();
1566     gdouble const zoom = selection->desktop()->current_zoom();
1567     gdouble const zmove = angle / zoom;
1568     gdouble const r = NR::L2(bbox.max() - center);
1570     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1572     sp_selection_rotate_relative(selection, center, zangle);
1574     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1575                            ( (angle > 0)
1576                              ? "selector:rotate:ccw"
1577                              : "selector:rotate:cw" ));
1580 void
1581 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1583     if (selection->isEmpty())
1584         return;
1586     NR::Rect const bbox(selection->bounds());
1587     NR::Point const center(bbox.midpoint());
1588     double const max_len = bbox.maxExtent();
1590     // you can't scale "do nizhe pola" (below zero)
1591     if ( max_len + grow <= 1e-3 ) {
1592         return;
1593     }
1595     double const times = 1.0 + grow / max_len;
1596     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1598     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1599                            ( (grow > 0)
1600                              ? "selector:scale:larger"
1601                              : "selector:scale:smaller" ));
1604 void
1605 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1607     sp_selection_scale(selection,
1608                        grow_pixels / selection->desktop()->current_zoom());
1611 void
1612 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1614     if (selection->isEmpty())
1615         return;
1617     NR::Point const center(selection->bounds().midpoint());
1618     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1619     sp_document_done(sp_desktop_document(selection->desktop()));
1622 void
1623 sp_selection_move(gdouble dx, gdouble dy)
1625     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1626     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1627     if (selection->isEmpty()) {
1628         return;
1629     }
1631     sp_selection_move_relative(selection, dx, dy);
1633     if (dx == 0) {
1634         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical");
1635     } else if (dy == 0) {
1636         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal");
1637     } else {
1638         sp_document_done(sp_desktop_document(desktop));
1639     }
1642 void
1643 sp_selection_move_screen(gdouble dx, gdouble dy)
1645     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1647     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1648     if (selection->isEmpty()) {
1649         return;
1650     }
1652     // same as sp_selection_move but divide deltas by zoom factor
1653     gdouble const zoom = desktop->current_zoom();
1654     gdouble const zdx = dx / zoom;
1655     gdouble const zdy = dy / zoom;
1656     sp_selection_move_relative(selection, zdx, zdy);
1658     if (dx == 0) {
1659         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical");
1660     } else if (dy == 0) {
1661         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal");
1662     } else {
1663         sp_document_done(sp_desktop_document(desktop));
1664     }
1667 namespace {
1669 template <typename D>
1670 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1671                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1673 template <typename D>
1674 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1675                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1677 struct Forward {
1678     typedef SPObject *Iterator;
1680     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1681     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1682     static void dispose(Iterator i) {}
1684     static SPObject *object(Iterator i) { return i; }
1685     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1686 };
1688 struct Reverse {
1689     typedef GSList *Iterator;
1691     static Iterator children(SPObject *o) {
1692         return make_list(o->firstChild(), NULL);
1693     }
1694     static Iterator siblings_after(SPObject *o) {
1695         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1696     }
1697     static void dispose(Iterator i) {
1698         g_slist_free(i);
1699     }
1701     static SPObject *object(Iterator i) {
1702         return reinterpret_cast<SPObject *>(i->data);
1703     }
1704     static Iterator next(Iterator i) { return i->next; }
1706 private:
1707     static GSList *make_list(SPObject *object, SPObject *limit) {
1708         GSList *list=NULL;
1709         while ( object != limit ) {
1710             list = g_slist_prepend(list, object);
1711             object = SP_OBJECT_NEXT(object);
1712         }
1713         return list;
1714     }
1715 };
1719 void
1720 sp_selection_item_next(void)
1722     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1723     g_return_if_fail(desktop != NULL);
1724     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1726     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1727     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1728     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1730     SPObject *root;
1731     if (PREFS_SELECTION_ALL != inlayer) {
1732         root = selection->activeContext();
1733     } else {
1734         root = desktop->currentRoot();
1735     }
1737     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1739     if (item) {
1740         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1741         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1742             scroll_to_show_item(desktop, item);
1743         }
1744     }
1747 void
1748 sp_selection_item_prev(void)
1750     SPDocument *document = SP_ACTIVE_DOCUMENT;
1751     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1752     g_return_if_fail(document != NULL);
1753     g_return_if_fail(desktop != NULL);
1754     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1756     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1757     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1758     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1760     SPObject *root;
1761     if (PREFS_SELECTION_ALL != inlayer) {
1762         root = selection->activeContext();
1763     } else {
1764         root = desktop->currentRoot();
1765     }
1767     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1769     if (item) {
1770         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1771         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1772             scroll_to_show_item(desktop, item);
1773         }
1774     }
1777 namespace {
1779 template <typename D>
1780 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1781                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1783     SPObject *current=root;
1784     while (items) {
1785         SPItem *item=SP_ITEM(items->data);
1786         if ( root->isAncestorOf(item) &&
1787              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1788         {
1789             current = item;
1790             break;
1791         }
1792         items = items->next;
1793     }
1795     GSList *path=NULL;
1796     while ( current != root ) {
1797         path = g_slist_prepend(path, current);
1798         current = SP_OBJECT_PARENT(current);
1799     }
1801     SPItem *next;
1802     // first, try from the current object
1803     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1804     g_slist_free(path);
1806     if (!next) { // if we ran out of objects, start over at the root
1807         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1808     }
1810     return next;
1813 template <typename D>
1814 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1815                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1817     typename D::Iterator children;
1818     typename D::Iterator iter;
1820     SPItem *found=NULL;
1822     if (path) {
1823         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1824         g_assert(SP_OBJECT_PARENT(object) == root);
1825         if (desktop->isLayer(object)) {
1826             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1827         }
1828         iter = children = D::siblings_after(object);
1829     } else {
1830         iter = children = D::children(root);
1831     }
1833     while ( iter && !found ) {
1834         SPObject *object=D::object(iter);
1835         if (desktop->isLayer(object)) {
1836             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1837                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1838             }
1839         } else if ( SP_IS_ITEM(object) &&
1840                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1841                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1842                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1843                     !desktop->isLayer(SP_ITEM(object)) )
1844         {
1845             found = SP_ITEM(object);
1846         }
1847         iter = D::next(iter);
1848     }
1850     D::dispose(children);
1852     return found;
1857 /**
1858  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1859  * \a item.
1860  */
1861 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1863     NR::Rect dbox = desktop->get_display_area();
1864     NR::Rect sbox = sp_item_bbox_desktop(item);
1866     if (dbox.contains(sbox) == false) {
1867         NR::Point const s_dt = sbox.midpoint();
1868         NR::Point const s_w = desktop->d2w(s_dt);
1869         NR::Point const d_dt = dbox.midpoint();
1870         NR::Point const d_w = desktop->d2w(d_dt);
1871         NR::Point const moved_w( d_w - s_w );
1872         gint const dx = (gint) moved_w[X];
1873         gint const dy = (gint) moved_w[Y];
1874         desktop->scroll_world(dx, dy);
1875     }
1879 void
1880 sp_selection_clone()
1882     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1883     if (desktop == NULL)
1884         return;
1886     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1888     // check if something is selected
1889     if (selection->isEmpty()) {
1890         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1891         return;
1892     }
1894     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1895   
1896     selection->clear();
1897   
1898     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1899     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1901     GSList *newsel = NULL;
1902  
1903     while (reprs) {
1904         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1905         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1907         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1908         sp_repr_set_attr(clone, "x", "0");
1909         sp_repr_set_attr(clone, "y", "0");
1910         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1912         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1913         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1914         
1915         // add the new clone to the top of the original's parent
1916         parent->appendChild(clone);
1918         newsel = g_slist_prepend(newsel, clone);
1919         reprs = g_slist_remove(reprs, sel_repr);
1920         Inkscape::GC::release(clone);
1921     }
1922     
1923     sp_document_done(sp_desktop_document(desktop));
1925     selection->setReprList(newsel);
1926  
1927     g_slist_free(newsel);
1930 void
1931 sp_selection_unlink()
1933     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1934     if (!desktop)
1935         return;
1937     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1939     if (selection->isEmpty()) {
1940         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
1941         return;
1942     }
1944     // Get a copy of current selection.
1945     GSList *new_select = NULL;
1946     bool unlinked = false;
1947     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1948          items != NULL;
1949          items = items->next)
1950     {
1951         SPItem *use = (SPItem *) items->data;
1953         if (!SP_IS_USE(use)) {
1954             // keep the non-yse item in the new selection
1955             new_select = g_slist_prepend(new_select, use);
1956             continue;
1957         }
1959         SPItem *unlink = sp_use_unlink(SP_USE(use));
1960         unlinked = true;
1961         // Add ungrouped items to the new selection.
1962         new_select = g_slist_prepend(new_select, unlink);
1963     }
1965     if (new_select) { // set new selection
1966         selection->clear();
1967         selection->setList(new_select);
1968         g_slist_free(new_select);
1969     }
1970     if (!unlinked) {
1971         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1972     }
1974     sp_document_done(sp_desktop_document(desktop));
1977 void
1978 sp_select_clone_original()
1980     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1981     if (desktop == NULL)
1982         return;
1984     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1986     SPItem *item = selection->singleItem();
1988     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.");
1990     // Check if other than two objects are selected
1991     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
1992         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1993         return;
1994     }
1996     SPItem *original = NULL;
1997     if (SP_IS_USE(item)) {
1998         original = sp_use_get_original (SP_USE(item));
1999     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2000         original = sp_offset_get_source (SP_OFFSET(item));
2001     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2002         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2003     } else if (SP_IS_FLOWTEXT(item)) {
2004         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2005     } else { // it's an object that we don't know what to do with
2006         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2007         return;
2008     }
2010     if (!original) {
2011         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2012         return;
2013     }
2015     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2016         if (SP_IS_DEFS (o)) {
2017             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2018             return;
2019         }
2020     }
2022     if (original) {
2023         selection->clear();
2024         selection->set(original);
2025         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2026             scroll_to_show_item(desktop, original);
2027         }
2028     }
2031 void
2032 sp_selection_tile(bool apply)
2034     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2035     if (desktop == NULL)
2036         return;
2038     SPDocument *document = sp_desktop_document(desktop);
2040     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2042     // check if something is selected
2043     if (selection->isEmpty()) {
2044         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2045         return;
2046     }
2048     sp_document_ensure_up_to_date(document);
2049     NR::Rect r = selection->bounds();
2050     if (r.isEmpty()) {
2051         return;
2052     }
2054     // calculate the transform to be applied to objects to move them to 0,0
2055     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2056     move_p[NR::Y] = -move_p[NR::Y];
2057     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2059     GSList *items = g_slist_copy((GSList *) selection->itemList());
2061     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2063     // bottommost object, after sorting
2064     SPObject *parent = SP_OBJECT_PARENT (items->data);
2066     // remember the position of the first item
2067     gint pos = SP_OBJECT_REPR (items->data)->position();
2069     // create a list of duplicates
2070     GSList *repr_copies = NULL;
2071     for (GSList *i = items; i != NULL; i = i->next) {
2072         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2073         repr_copies = g_slist_prepend (repr_copies, dup);
2074     }
2076     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2078     if (apply) {
2079         // delete objects so that their clones don't get alerted; this object will be restored shortly
2080         for (GSList *i = items; i != NULL; i = i->next) {
2081             SPObject *item = SP_OBJECT (i->data);
2082             item->deleteObject (false);
2083         }
2084     }
2086     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2087     // without disturbing clones.
2088     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2089     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2090     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2092     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2093                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))), move);
2095     // restore compensation setting
2096     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2098     if (apply) {
2099         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2100         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2101         sp_repr_set_svg_double(rect, "width", bounds.extent(NR::X));
2102         sp_repr_set_svg_double(rect, "height", bounds.extent(NR::Y));
2103         sp_repr_set_svg_double(rect, "x", bounds.min()[NR::X]);
2104         sp_repr_set_svg_double(rect, "y", bounds.min()[NR::Y]);
2106         // restore parent and position
2107         SP_OBJECT_REPR (parent)->appendChild(rect);
2108         rect->setPosition(pos > 0 ? pos : 0);
2109         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2111         Inkscape::GC::release(rect);
2113         selection->clear();
2114         selection->set(rectangle);
2115     }
2117     g_slist_free (items);
2119     sp_document_done (document);
2122 void
2123 sp_selection_untile()
2125     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2126     if (desktop == NULL)
2127         return;
2129     SPDocument *document = sp_desktop_document(desktop);
2131     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2133     // check if something is selected
2134     if (selection->isEmpty()) {
2135         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2136         return;
2137     }
2139     GSList *new_select = NULL;
2141     bool did = false;
2143     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2144          items != NULL;
2145          items = items->next) {
2147         SPItem *item = (SPItem *) items->data;
2149         SPStyle *style = SP_OBJECT_STYLE (item);
2151         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2152             continue;
2154         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2156         if (!SP_IS_PATTERN(server))
2157             continue;
2159         did = true;
2161         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2163         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2164         pat_transform *= item->transform;
2166         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2167             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2168             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2170            // FIXME: relink clones to the new canvas objects
2171            // use SPObject::setid when mental finishes it to steal ids of
2173             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2174             sp_document_ensure_up_to_date (document);
2176             NR::Matrix transform( i->transform * pat_transform );
2177             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2179             new_select = g_slist_prepend(new_select, i);
2180         }
2182         SPCSSAttr *css = sp_repr_css_attr_new ();
2183         sp_repr_css_set_property (css, "fill", "none");
2184         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2185     }
2187     if (!did) {
2188         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2189     } else {
2190         sp_document_done(sp_desktop_document(desktop));
2191         selection->setList(new_select);
2192     }
2195 void
2196 sp_selection_create_bitmap_copy ()
2198     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2199     if (desktop == NULL)
2200         return;
2202     SPDocument *document = sp_desktop_document(desktop);
2204     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2206     // check if something is selected
2207     if (selection->isEmpty()) {
2208         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2209         return;
2210     }
2212     // Get the bounding box of the selection
2213     NRRect bbox;
2214     sp_document_ensure_up_to_date (document);
2215     selection->bounds(&bbox);
2216     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2217         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2218     }
2220     // List of the items to show; all others will be hidden
2221     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2223     // Sort items so that the topmost comes last
2224     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2226     // Generate a random value from the current time (you may create bitmap from the same object(s)
2227     // multiple times, and this is done so that they don't clash)
2228     GTimeVal cu;
2229     g_get_current_time (&cu);
2230     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2232     // Create the filename
2233     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2234     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2235     // digits, and a few other chars, with "_"
2236     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2237     // Build the complete path by adding document->base if set
2238     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2240     //g_print ("%s\n", filepath);
2242     // Remember parent and z-order of the topmost one
2243     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2244     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2245     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2247     // Calculate resolution
2248     double res;
2249     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2250     if (0 < prefs_res) {
2251         // If it's given explicitly in prefs, take it
2252         res = prefs_res;
2253     } else {
2254         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2255         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2256         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2257     }
2259     // The width and height of the bitmap in pixels
2260     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2261     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2263     // Find out if we have to run a filter
2264     const gchar *run = NULL;
2265     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2266     if (filter) {
2267         // filter command is given;
2268         // see if we have a parameter to pass to it
2269         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2270         if (param1) {
2271             if (param1[strlen(param1) - 1] == '%') {
2272                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2273                 gchar p1[256];
2274                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2275                 // the first param is always the image filename, the second is param1
2276                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2277             } else {
2278                 // otherwise pass the param1 unchanged
2279                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2280             }
2281         } else {
2282             // run without extra parameter
2283             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2284         }
2285     }
2287     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2288     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2289     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2291     // Do the export
2292     sp_export_png_file(document, filepath,
2293                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2294                    width, height,
2295                    (guint32) 0xffffff00,
2296                    NULL, NULL,
2297                    true,  /*bool force_overwrite,*/
2298                    items);
2300     g_slist_free (items);
2302     // Run filter, if any
2303     if (run) {
2304         g_print ("Running external filter: %s\n", run);
2305         system (run);
2306     }
2308     // Import the image back
2309     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2310     if (pb) {
2311         // Create the repr for the image
2312         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2313         repr->setAttribute("xlink:href", filename);
2314         repr->setAttribute("sodipodi:absref", filepath);
2315         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2316         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2318         // Write transform
2319         gchar c[256];
2320         if (sp_svg_transform_write(c, 256, t)) {
2321             repr->setAttribute("transform", c);
2322         }
2324         // add the new repr to the parent
2325         parent->appendChild(repr);
2327         // move to the saved position
2328         repr->setPosition(pos > 0 ? pos + 1 : 1);
2330         // Set selection to the new image
2331         selection->clear();
2332         selection->add(repr);
2334         // Clean up
2335         Inkscape::GC::release(repr);
2336         gdk_pixbuf_unref (pb);
2338         // Complete undoable transaction
2339         sp_document_done (document);
2340     }
2342     g_free (filename);
2343     g_free (filepath);
2346 /**
2347  * \brief sp_selection_set_mask
2348  *
2349  * This function creates a mask or clipPath from selection
2350  * Two different modes:
2351  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2352  *       and is applied to current layer
2353  *  otherwise, topmost object is used as mask for other objects
2354  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2355  * 
2356  */
2357 void
2358 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2360     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2361     if (desktop == NULL)
2362         return;
2364     SPDocument *document = sp_desktop_document(desktop);
2365     
2366     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2368     // check if something is selected
2369     bool is_empty = selection->isEmpty();
2370     if ( apply_to_layer && is_empty) {
2371         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2372         return;
2373     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2374         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2375         return;
2376     }
2377     
2378     sp_document_ensure_up_to_date(document);
2380     GSList *items = g_slist_copy((GSList *) selection->itemList());
2381     
2382     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2384     // create a list of duplicates
2385     GSList *mask_items = NULL;
2386     GSList *apply_to_items = NULL;
2387     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2388     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2389     
2390     if (apply_to_layer) {
2391         // all selected items are used for mask, which is applied to a layer
2392         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2394         for (GSList *i = items; i != NULL; i = i->next) {
2395             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2396             mask_items = g_slist_prepend (mask_items, dup);
2398             if (remove_original) {
2399                 SPObject *item = SP_OBJECT (i->data);
2400                 item->deleteObject (false);
2401             }
2402         }
2403     } else if (!topmost) {
2404         // topmost item is used as a mask, which is applied to other items in a selection
2405         GSList *i = items;
2406         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2407         mask_items = g_slist_prepend (mask_items, dup);
2409         if (remove_original) {
2410             SPObject *item = SP_OBJECT (i->data);
2411             item->deleteObject (false);
2412         }
2413         
2414         for (i = i->next; i != NULL; i = i->next) {
2415             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2416         }
2417     } else {
2418         GSList *i = NULL;
2419         for (i = items; NULL != i->next; i = i->next) {
2420             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2421         }
2423         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2424         mask_items = g_slist_prepend (mask_items, dup);
2426         if (remove_original) {
2427             SPObject *item = SP_OBJECT (i->data);
2428             item->deleteObject (false);
2429         }
2430     }
2431     
2432     g_slist_free (items);
2433     items = NULL;
2434             
2435     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2436     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2437         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2438         // inverted object transform should be applied to a mask object,
2439         // as mask is calculated in user space (after applying transform)
2440         NR::Matrix maskTransform (item->transform.inverse());
2442         GSList *mask_items_dup = NULL;
2443         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2444             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2445             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2446         }
2448         const gchar *mask_id = NULL;
2449         if (apply_clip_path) {
2450             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2451         } else {
2452             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2453         }
2455         g_slist_free (mask_items_dup);
2456         mask_items_dup = NULL;
2458         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2459     }
2461     g_slist_free (mask_items);
2462     g_slist_free (apply_to_items);
2464     sp_document_done (document);
2467 void sp_selection_unset_mask(bool apply_clip_path) {
2468     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2469     if (desktop == NULL)
2470         return;
2471     
2472     SPDocument *document = sp_desktop_document(desktop);    
2473     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2475     // check if something is selected
2476     if (selection->isEmpty()) {
2477         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2478         return;
2479     }
2480     
2481     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2482     sp_document_ensure_up_to_date(document);
2484     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2485     std::map<SPObject*,SPItem*> referenced_objects;
2486     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2487         if (remove_original) {
2488             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2489             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2490             Inkscape::URIReference *uri_ref = NULL;
2491         
2492             if (apply_clip_path) {
2493                 uri_ref = item->clip_ref;
2494             } else {
2495                 uri_ref = item->mask_ref;
2496             }
2498             // collect distinct mask object (and associate with item to apply transform)
2499             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2500                 referenced_objects[uri_ref->getObject()] = item;
2501             }
2502         }
2504         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2505     }
2507     // restore mask objects into a document
2508     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2509         SPObject *obj = (*it).first;
2510         GSList *items_to_move = NULL;
2511         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2512             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2513             items_to_move = g_slist_prepend (items_to_move, copy);
2514         }
2516         if (!obj->isReferenced()) {
2517             // delete from defs if no other object references this mask
2518             obj->deleteObject(false);
2519         }
2521         // remember parent and position of the item to which the clippath/mask was applied
2522         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2523         gint pos = SP_OBJECT_REPR((*it).second)->position();
2525         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2526             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2528             // insert into parent, restore pos
2529             parent->appendChild(repr);
2530             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2532             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2533             selection->add(repr);
2535             // transform mask, so it is moved the same spot where mask was applied
2536             NR::Matrix transform (mask_item->transform);
2537             transform *= (*it).second->transform;
2538             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2539         }
2541         g_slist_free (items_to_move);
2542     }
2544     sp_document_done (document);
2547 void fit_canvas_to_selection(SPDesktop *desktop) {
2548     g_return_if_fail(desktop != NULL);
2549     SPDocument *doc = sp_desktop_document(desktop);
2551     g_return_if_fail(doc != NULL);
2552     g_return_if_fail(desktop->selection != NULL);
2553     g_return_if_fail(!desktop->selection->isEmpty());
2554     NRRect bbox = {0,0,0,0};
2556     desktop->selection->bounds(&bbox);
2557     if (!empty(bbox)) {
2558         doc->fitToRect(bbox);
2559     }
2560 };
2562 void fit_canvas_to_drawing(SPDocument *doc) {
2563     g_return_if_fail(doc != NULL);
2564     NRRect bbox = {0,0,0,0};
2566     sp_document_ensure_up_to_date (doc);
2567     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2569     if (!empty(bbox)) {
2570         doc->fitToRect(bbox);
2571     }
2572 };
2574 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2575     g_return_if_fail(desktop != NULL);
2576     SPDocument *doc = sp_desktop_document(desktop);
2578     g_return_if_fail(doc != NULL);
2579     g_return_if_fail(desktop->selection != NULL);
2581     if (desktop->selection->isEmpty()) {
2582         fit_canvas_to_drawing(doc);
2583     } else {
2584         fit_canvas_to_selection(desktop);
2585     }
2587     sp_document_done(doc);
2588 };
2590 /*
2591   Local Variables:
2592   mode:c++
2593   c-file-style:"stroustrup"
2594   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2595   indent-tabs-mode:nil
2596   fill-column:99
2597   End:
2598 */
2599 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :