Code

Catch failures in fopen of XML files. Fixes #1374551.
[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  *
12  * Copyright (C) 1999-2005 authors
13  * Copyright (C) 2001-2002 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
22 #include <gtkmm/clipboard.h>
24 #include "svg/svg.h"
25 #include "inkscape.h"
26 #include "desktop.h"
27 #include "desktop-style.h"
28 #include "selection.h"
29 #include "tools-switch.h"
30 #include "desktop-handles.h"
31 #include "message-stack.h"
32 #include "sp-item-transform.h"
33 #include "sp-marker.h"
34 #include "sp-use.h"
35 #include "sp-textpath.h"
36 #include "sp-tspan.h"
37 #include "sp-flowtext.h"
38 #include "sp-flowregion.h"
39 #include "text-editing.h"
40 #include "text-context.h"
41 #include "dropper-context.h"
42 #include <glibmm/i18n.h>
43 #include "libnr/nr-matrix-rotate-ops.h"
44 #include "libnr/nr-matrix-translate-ops.h"
45 #include "libnr/nr-rotate-fns.h"
46 #include "libnr/nr-scale-ops.h"
47 #include "libnr/nr-scale-translate-ops.h"
48 #include "libnr/nr-translate-matrix-ops.h"
49 #include "libnr/nr-translate-scale-ops.h"
50 #include "xml/repr.h"
51 #include "style.h"
52 #include "document-private.h"
53 #include "sp-gradient.h"
54 #include "sp-gradient-reference.h"
55 #include "sp-linear-gradient-fns.h"
56 #include "sp-pattern.h"
57 #include "sp-radial-gradient-fns.h"
58 #include "sp-namedview.h"
59 #include "prefs-utils.h"
60 #include "sp-offset.h"
61 #include "file.h"
62 #include "layer-fns.h"
63 #include "context-fns.h"
64 using NR::X;
65 using NR::Y;
67 #include "selection-chemistry.h"
69 /* fixme: find a better place */
70 GSList *clipboard = NULL;
71 GSList *defs_clipboard = NULL;
72 SPCSSAttr *style_clipboard = NULL;
74 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
76 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
77 {
78     Inkscape::XML::Node *copy = repr->duplicate();
80     // copy complete inherited style
81     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
82     sp_repr_css_set(copy, css, "style");
83     sp_repr_css_attr_unref(css);
85     // write the complete accummulated transform passed to us
86     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
87     gchar affinestr[80];
88     if (sp_svg_transform_write(affinestr, 79, full_t)) {
89         copy->setAttribute("transform", affinestr);
90     } else {
91         copy->setAttribute("transform", NULL);
92     }
94     *clip = g_slist_prepend(*clip, copy);
95 }
97 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
98 {
100     // Copy stuff referenced by all items to defs_clip:
101     if (defs_clip) {
102         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
103             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
104         }
105         *defs_clip = g_slist_reverse(*defs_clip);
106     }
108     // Store style:
109     if (style_clip) {
110         SPItem *item = SP_ITEM (items->data); // take from the first selected item
111         *style_clip = take_style_from_item (item);
112     }
114     if (clip) {
115         // Sort items:
116         GSList *sorted_items = g_slist_copy ((GSList *) items);
117         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
119         // Copy item reprs:
120         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
121             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
122         }
124         *clip = g_slist_reverse(*clip);
125         g_slist_free ((GSList *) sorted_items);
126     }
129 /**
130 Add gradients/patterns/markers referenced by copied objects to defs
131 */
132 void 
133 paste_defs (GSList **defs_clip, SPDocument *doc)
135     if (!defs_clip)
136         return;
138     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
139         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
140         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
141         gchar const *id = repr->attribute("id");
142         if (!id || !doc->getObjectById(id)) {
143             Inkscape::XML::Node *copy = repr->duplicate();
144             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
145             Inkscape::GC::release(copy);
146         }
147     }
150 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
152     paste_defs (defs_clip, document);
154     GSList *copied = NULL;
155     // add objects to document
156     for (GSList *l = *clip; l != NULL; l = l->next) {
157         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
158         Inkscape::XML::Node *copy = repr->duplicate();
160         // premultiply the item transform by the accumulated parent transform in the paste layer
161         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
162         if (!local.test_identity()) {
163             gchar const *t_str = copy->attribute("transform");
164             NR::Matrix item_t (NR::identity());
165             if (t_str)
166                 sp_svg_transform_read(t_str, &item_t);
167             item_t *= local.inverse();
168             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
169             gchar affinestr[80];
170             if (sp_svg_transform_write(affinestr, 79, item_t)) {
171                 copy->setAttribute("transform", affinestr);
172             } else {
173                 copy->setAttribute("transform", NULL);
174             }
175         }
177         parent->appendChildRepr(copy);
178         copied = g_slist_prepend(copied, copy);
179         Inkscape::GC::release(copy);
180     }
181     return copied;
184 void sp_selection_delete_impl(const GSList *items)
186     for (const GSList *i = items ; i ; i = i->next ) {
187         sp_object_ref((SPObject *)i->data, NULL);
188     }
189     for (const GSList *i = items; i != NULL; i = i->next) {
190         SPItem *item = (SPItem *) i->data;
191         SP_OBJECT(item)->deleteObject();
192         sp_object_unref((SPObject *)item, NULL);
193     }
197 void sp_selection_delete()
199     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
200     if (desktop == NULL) {
201         return;
202     }
204     if (tools_isactive (desktop, TOOLS_TEXT))
205         if (sp_text_delete_selection(desktop->event_context)) {
206             sp_document_done(SP_DT_DOCUMENT(desktop));
207             return;
208         }
210     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
212     // check if something is selected
213     if (selection->isEmpty()) {
214         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
215         return;
216     }
218     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
219     selection->clear();
220     sp_selection_delete_impl (selected);
221     g_slist_free ((GSList *) selected);
223     /* a tool may have set up private information in it's selection context
224      * that depends on desktop items.  I think the only sane way to deal with
225      * this currently is to reset the current tool, which will reset it's
226      * associated selection context.  For example: deleting an object
227      * while moving it around the canvas.
228      */
229     tools_switch ( desktop, tools_active ( desktop ) );
231     sp_document_done(SP_DT_DOCUMENT(desktop));
234 /* fixme: sequencing */
235 void sp_selection_duplicate()
237     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
238     if (desktop == NULL)
239         return;
241     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
243     // check if something is selected
244     if (selection->isEmpty()) {
245         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
246         return;
247     }
249     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
251     selection->clear();
253     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
254     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
256     GSList *newsel = NULL;
258     while (reprs) {
259         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
260         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
262         parent->appendChild(copy);
264         newsel = g_slist_prepend(newsel, copy);
265         reprs = g_slist_remove(reprs, reprs->data);
266         Inkscape::GC::release(copy);
267     }
269     sp_document_done(SP_DT_DOCUMENT(desktop));
271     selection->setReprList(newsel);
273     g_slist_free(newsel);
276 void sp_edit_clear_all()
278     SPDesktop *dt = SP_ACTIVE_DESKTOP;
279     if (!dt)
280         return;
282     SPDocument *doc = SP_DT_DOCUMENT(dt);
283     SP_DT_SELECTION(dt)->clear();
285     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
286     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
288     while (items) {
289         SP_OBJECT (items->data)->deleteObject();
290         items = g_slist_remove(items, items->data);
291     }
293     sp_document_done(doc);
296 GSList *
297 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
299     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
300         if (SP_IS_ITEM(child) &&
301             !desktop->isLayer(SP_ITEM(child)) &&
302             (!onlysensitive || !SP_ITEM(child)->isLocked()) && 
303             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
304             (!exclude || !g_slist_find ((GSList *) exclude, child))
305             )
306         {
307             list = g_slist_prepend (list, SP_ITEM(child));
308         }
310         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
311             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
312         }
313     }
315     return list;
318 void sp_edit_select_all_full (bool force_all_layers, bool invert)
320     SPDesktop *dt = SP_ACTIVE_DESKTOP;
321     if (!dt)
322         return;
324     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
326     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
328     bool inlayer = prefs_get_int_attribute ("options.kbselection", "inlayer", 1);
329     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
330     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
332     GSList *items = NULL;
334     const GSList *exclude = NULL;
335     if (invert) {
336         exclude = selection->itemList();
337     }
339     if (inlayer && !force_all_layers) {
341         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
342              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
343         return;
345         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
347         for (GSList *i = all_items; i; i = i->next) {
348             SPItem *item = SP_ITEM (i->data);
350             if (item && (!onlysensitive || !item->isLocked())) {
351                 if (!onlyvisible || !dt->itemIsHidden(item)) {
352                     if (!dt->isLayer(item)) {
353                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
354                             items = g_slist_prepend (items, item); // leave it in the list
355                         }
356                     }
357                 }
358             }
359         }
361         g_slist_free (all_items);
363     } else {
364         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
365     }
367     selection->setList (items);
369     if (items) {
370         g_slist_free (items);
371     }
374 void sp_edit_select_all ()
376     sp_edit_select_all_full (false, false);
379 void sp_edit_select_all_in_all_layers ()
381     sp_edit_select_all_full (true, false);
384 void sp_edit_invert ()
386     sp_edit_select_all_full (false, true);
389 void sp_edit_invert_in_all_layers ()
391     sp_edit_select_all_full (true, true);
394 void sp_selection_group()
396     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
397     if (desktop == NULL)
398         return;
400     SPDocument *document = SP_DT_DOCUMENT (desktop);
402     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
404     // Check if something is selected.
405     if (selection->isEmpty()) {
406         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
407         return;
408     }
410     GSList const *l = (GSList *) selection->reprList();
412     // Check if at least two objects are selected.
413     if (l->next == NULL) {
414         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
415         return;
416     }
418     GSList *p = g_slist_copy((GSList *) l);
420     selection->clear();
422     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
424     // Remember the position and parent of the topmost object.
425     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
426     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
428     Inkscape::XML::Node *group = sp_repr_new("svg:g");
430     while (p) {
431         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
433         if (current->parent() == topmost_parent) {
434             Inkscape::XML::Node *spnew = current->duplicate();
435             sp_repr_unparent(current);
436             group->appendChild(spnew);
437             Inkscape::GC::release(spnew);
438             topmost --; // only reduce count for those items deleted from topmost_parent
439         } else { // move it to topmost_parent first
440                 GSList *temp_clip = NULL;
442                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
443                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
444                 gchar const *t_str = current->attribute("transform");
445                 NR::Matrix item_t (NR::identity());
446                 if (t_str)
447                     sp_svg_transform_read(t_str, &item_t);
448                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
449                 //FIXME: when moving both clone and original from a transformed group (either by
450                 //grouping into another parent, or by cut/paste) the transform from the original's
451                 //parent becomes embedded into original itself, and this affects its clones. Fix
452                 //this by remembering the transform diffs we write to each item into an array and
453                 //then, if this is clone, looking up its original in that array and pre-multiplying
454                 //it by the inverse of that original's transform diff.
456                 sp_selection_copy_one (current, item_t, &temp_clip);
457                 sp_repr_unparent(current);
459                 // paste into topmost_parent (temporarily)
460                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
461                 if (temp_clip) g_slist_free (temp_clip);
462                 if (copied) { // if success,
463                     // take pasted object (now in topmost_parent)
464                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
465                     // make a copy
466                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
467                     // remove pasted
468                     sp_repr_unparent(in_topmost);
469                     // put its copy into group
470                     group->appendChild(spnew);
471                     Inkscape::GC::release(spnew);
472                     g_slist_free (copied);
473                 }
474         }
475         p = g_slist_remove(p, current);
476     }
478     // Add the new group to the topmost members' parent
479     topmost_parent->appendChild(group);
481     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
482     group->setPosition(topmost + 1);
484     sp_document_done(SP_DT_DOCUMENT(desktop));
486     selection->set(group);
487     Inkscape::GC::release(group);
490 void sp_selection_ungroup()
492     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
493     if (desktop == NULL)
494         return;
496     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
498     if (selection->isEmpty()) {
499         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
500         return;
501     }
503     GSList *items = g_slist_copy((GSList *) selection->itemList());
504     selection->clear();
506     // Get a copy of current selection.
507     GSList *new_select = NULL;
508     bool ungrouped = false;
509     for (GSList *i = items;
510          i != NULL;
511          i = i->next)
512     {
513         SPItem *group = (SPItem *) i->data;
515         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
516         if (!SP_IS_OBJECT(group)) {
517             continue;
518         }
520         /* We do not allow ungrouping <svg> etc. (lauris) */
521         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
522             // keep the non-group item in the new selection
523             selection->add(group);
524             continue;
525         }
527         GSList *children = NULL;
528         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
529         sp_item_group_ungroup(SP_GROUP(group), &children, false);
530         ungrouped = true;
531         // Add ungrouped items to the new selection.
532         new_select = g_slist_concat(new_select, children);
533     }
535     if (new_select) { // Set new selection.
536         selection->addList(new_select);
537         g_slist_free(new_select);
538     }
539     if (!ungrouped) {
540         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
541     }
543     g_slist_free(items);
545     sp_document_done(SP_DT_DOCUMENT(desktop));
548 static SPGroup *
549 sp_item_list_common_parent_group(const GSList *items)
551     if (!items) {
552         return NULL;
553     }
554     SPObject *parent = SP_OBJECT_PARENT(items->data);
555     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
556     if (!SP_IS_GROUP(parent)) {
557         return NULL;
558     }
559     for (items = items->next; items; items = items->next) {
560         if (SP_OBJECT_PARENT(items->data) != parent) {
561             return NULL;
562         }
563     }
565     return SP_GROUP(parent);
568 /** Finds out the minimum common bbox of the selected items
569  */
570 NR::Rect
571 enclose_items(const GSList *items)
573     g_assert(items != NULL);
575     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
577     for (GSList *i = items->next; i; i = i->next) {
578         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
579     }
581     return r;
584 SPObject *
585 prev_sibling(SPObject *child)
587     SPObject *parent = SP_OBJECT_PARENT(child);
588     if (!SP_IS_GROUP(parent)) {
589         return NULL;
590     }
591     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
592         if (i->next == child)
593             return i;
594     }
595     return NULL;
598 void
599 sp_selection_raise()
601     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
602     if (!desktop)
603         return;
605     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
607     GSList const *items = (GSList *) selection->itemList();
608     if (!items) {
609         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
610         return;
611     }
613     SPGroup const *group = sp_item_list_common_parent_group(items);
614     if (!group) {
615         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
616         return;
617     }
619     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
621     /* construct reverse-ordered list of selected children */
622     GSList *rev = g_slist_copy((GSList *) items);
623     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
625     // find out the common bbox of the selected items
626     NR::Rect selected = enclose_items(items);
628     // for all objects in the selection (starting from top)
629     while (rev) {
630         SPObject *child = SP_OBJECT(rev->data);
631         // for each selected object, find the next sibling
632         for (SPObject *newref = child->next; newref; newref = newref->next) {
633             // if the sibling is an item AND overlaps our selection,
634             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
635                 // AND if it's not one of our selected objects,
636                 if (!g_slist_find((GSList *) items, newref)) {
637                     // move the selected object after that sibling
638                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
639                 }
640                 break;
641             }
642         }
643         rev = g_slist_remove(rev, child);
644     }
646     sp_document_done(SP_DT_DOCUMENT(desktop));
649 void sp_selection_raise_to_top()
651     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
652     if (desktop == NULL)
653         return;
655     SPDocument *document = SP_DT_DOCUMENT(desktop);
656     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
658     if (selection->isEmpty()) {
659         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
660         return;
661     }
663     GSList const *items = (GSList *) selection->itemList();
665     SPGroup const *group = sp_item_list_common_parent_group(items);
666     if (!group) {
667         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
668         return;
669     }
671     GSList *rl = g_slist_copy((GSList *) selection->reprList());
672     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
674     for (GSList *l = rl; l != NULL; l = l->next) {
675         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
676         repr->setPosition(-1);
677     }
679     g_slist_free(rl);
681     sp_document_done(document);
684 void
685 sp_selection_lower()
687     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
688     if (desktop == NULL)
689         return;
691     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
693     GSList const *items = (GSList *) selection->itemList();
694     if (!items) {
695         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
696         return;
697     }
699     SPGroup const *group = sp_item_list_common_parent_group(items);
700     if (!group) {
701         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
702         return;
703     }
705     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
707     // find out the common bbox of the selected items
708     NR::Rect selected = enclose_items(items);
710     /* construct direct-ordered list of selected children */
711     GSList *rev = g_slist_copy((GSList *) items);
712     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
713     rev = g_slist_reverse(rev);
715     // for all objects in the selection (starting from top)
716     while (rev) {
717         SPObject *child = SP_OBJECT(rev->data);
718         // for each selected object, find the prev sibling
719         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
720             // if the sibling is an item AND overlaps our selection,
721             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
722                 // AND if it's not one of our selected objects,
723                 if (!g_slist_find((GSList *) items, newref)) {
724                     // move the selected object before that sibling
725                     SPObject *put_after = prev_sibling(newref);
726                     if (put_after)
727                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
728                     else
729                         SP_OBJECT_REPR(child)->setPosition(0);
730                 }
731                 break;
732             }
733         }
734         rev = g_slist_remove(rev, child);
735     }
737     sp_document_done(SP_DT_DOCUMENT(desktop));
741 void sp_selection_lower_to_bottom()
743     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
744     if (desktop == NULL)
745         return;
747     SPDocument *document = SP_DT_DOCUMENT(desktop);
748     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
750     if (selection->isEmpty()) {
751         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
752         return;
753     }
755     GSList const *items = (GSList *) selection->itemList();
757     SPGroup const *group = sp_item_list_common_parent_group(items);
758     if (!group) {
759         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
760         return;
761     }
763     GSList *rl;
764     rl = g_slist_copy((GSList *) selection->reprList());
765     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
766     rl = g_slist_reverse(rl);
768     for (GSList *l = rl; l != NULL; l = l->next) {
769         gint minpos;
770         SPObject *pp, *pc;
771         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
772         pp = document->getObjectByRepr(sp_repr_parent(repr));
773         minpos = 0;
774         g_assert(SP_IS_GROUP(pp));
775         pc = sp_object_first_child(pp);
776         while (!SP_IS_ITEM(pc)) {
777             minpos += 1;
778             pc = pc->next;
779         }
780         repr->setPosition(minpos);
781     }
783     g_slist_free(rl);
785     sp_document_done(document);
788 void
789 sp_undo(SPDesktop *desktop, SPDocument *doc)
791         if (!sp_document_undo(SP_DT_DOCUMENT(desktop)))
792             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
795 void
796 sp_redo(SPDesktop *desktop, SPDocument *doc)
798         if (!sp_document_redo(SP_DT_DOCUMENT(desktop)))
799             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
802 void sp_selection_cut()
804     sp_selection_copy();
805     sp_selection_delete();
808 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
810     SPGradient *ref = gradient;
812     while (ref) { 
813         // climb up the refs, copying each one in the chain
814         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
815         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
817         ref = ref->ref->getObject();
818     }
821 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
823     SPPattern *ref = pattern;
825     while (ref) {
826         // climb up the refs, copying each one in the chain
827         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
828         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
830         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
831         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
832             if (!SP_IS_ITEM (child))
833                 continue;
834             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
835         }
837         ref = ref->ref->getObject();
838     }
841 void sp_copy_marker (GSList **defs_clip, SPMarker *marker)
843     Inkscape::XML::Node *marker_repr = SP_OBJECT_REPR(marker)->duplicate();
844     *defs_clip = g_slist_prepend (*defs_clip, marker_repr);
848 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
850     SPItem *path = sp_textpath_get_path_item (tp);
851     if (!path)
852         return;
853     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
854         return;
855     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
856     *defs_clip = g_slist_prepend (*defs_clip, repr);
859 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
861     SPStyle *style = SP_OBJECT_STYLE (item); 
863     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) { 
864         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
865         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
866             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
867         if (SP_IS_PATTERN (server))
868             sp_copy_pattern (defs_clip, SP_PATTERN(server));
869     }
871     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) { 
872         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
873         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
874             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
875         if (SP_IS_PATTERN (server))
876             sp_copy_pattern (defs_clip, SP_PATTERN(server));
877     }
879     if (SP_IS_SHAPE (item)) { 
880         SPShape *shape = SP_SHAPE (item);
881         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
882             if (shape->marker[i]) {
883                 sp_copy_marker (defs_clip, SP_MARKER (shape->marker[i]));
884             }
885         }
886     }
888     if (SP_IS_TEXT_TEXTPATH (item)) {
889         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
890     }
892     // recurse
893     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
894         if (SP_IS_ITEM(o))
895             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
896     }
899 /**
900  * \pre item != NULL
901  */
902 SPCSSAttr *
903 take_style_from_item (SPItem *item)
905     // write the complete cascaded style, context-free
906     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
907     if (css == NULL)
908         return NULL;
910     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
911         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
912         // if this is a text with exactly one tspan child, merge the style of that tspan as well
913         // If this is a group, merge the style of its topmost (last) child with style
914         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
915             if (SP_OBJECT_STYLE (last_element) != NULL) {
916                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
917                 if (temp) {
918                     sp_repr_css_merge (css, temp);
919                     sp_repr_css_attr_unref (temp);
920                 }
921                 break;
922             }
923         }
924     }
925     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
926         // do not copy text properties from non-text objects, it's confusing
927         css = sp_css_attr_unset_text (css);
928     }
930     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
931     double ex = NR::expansion(sp_item_i2doc_affine(item));
932     if (ex != 1.0) {
933         css = sp_css_attr_scale (css, ex);
934     }
936     return css;
940 void sp_selection_copy()
942     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
943     if (desktop == NULL)
944         return;
946     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
948     if (tools_isactive (desktop, TOOLS_DROPPER)) {
949         sp_dropper_context_copy(desktop->event_context);
950         return; // copied color under cursor, nothing else to do
951     }
953     // check if something is selected
954     if (selection->isEmpty()) {
955         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
956         return;
957     }
959     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
961     // 0. Copy text to system clipboard
962     // FIXME: for non-texts, put serialized XML as text to the clipboard; 
963     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
964     Glib::ustring text;
965     if (tools_isactive (desktop, TOOLS_TEXT)) {
966         text = sp_text_get_selected_text(desktop->event_context);
967     }
969     if (text.empty()) {
970         guint texts = 0;
971         for (GSList *i = (GSList *) items; i; i = i->next) {
972             SPItem *item = SP_ITEM (i->data);
973             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
974                 if (texts > 0) // if more than one text object is copied, separate them by spaces
975                     text += " ";
976                 gchar *this_text = sp_te_get_string_multiline (item);
977                 if (this_text) {
978                     text += this_text;
979                     g_free(this_text);
980                 }
981                 texts++;
982             }
983         }
984     }
985     if (!text.empty()) {
986         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
987         refClipboard->set_text(text);
988     }
990     // clear old defs clipboard
991     while (defs_clipboard) {
992         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
993         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
994     }
996     // clear style clipboard
997     if (style_clipboard) {
998         sp_repr_css_attr_unref (style_clipboard);
999         style_clipboard = NULL;
1000     }
1001   
1002     //clear main clipboard 
1003     while (clipboard) {
1004         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1005         clipboard = g_slist_remove(clipboard, clipboard->data);
1006     }
1008     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1010     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1011         SPStyle *const query = sp_style_new();
1012         if (sp_desktop_query_style_all (desktop, query)) {
1013             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1014             if (css != NULL) {
1015                 // clear style clipboard
1016                 if (style_clipboard) {
1017                     sp_repr_css_attr_unref (style_clipboard);
1018                     style_clipboard = NULL;
1019                 }
1020                 //sp_repr_css_print (css);
1021                 style_clipboard = css;
1022             }
1023         }
1024         g_free (query);
1025     }
1027     g_slist_free ((GSList *) items);
1030 void sp_selection_paste(bool in_place)
1032     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1033     
1034     if (desktop == NULL) {
1035         return;
1036     }
1038     SPDocument *document = SP_DT_DOCUMENT(desktop);
1040     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1041         return;
1042     }
1044     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1046     if (tools_isactive (desktop, TOOLS_TEXT)) {
1047         if (sp_text_paste_inline(desktop->event_context))
1048             return; // pasted from system clipboard into text, nothing else to do
1049     }
1051     // check if something is in the clipboard
1052     if (clipboard == NULL) {
1053         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1054         return;
1055     }
1057     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1058     // add pasted objects to selection
1059     selection->setReprList((GSList const *) copied);
1060     g_slist_free (copied);
1062     if (!in_place) {
1063         sp_document_ensure_up_to_date(document);
1065         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1067         /* Snap the offset of the new item(s) to the grid */
1068         /* FIXME: this gridsnap fiddling is a hack. */
1069         Inkscape::GridSnapper &s = desktop->namedview->grid_snapper;
1070         gdouble const curr_gridsnap = s.getDistance();
1071         s.setDistance(NR_HUGE);
1072         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1073         s.setDistance(curr_gridsnap);
1074         sp_selection_move_relative(selection, m);
1075     }
1077     sp_document_done(document);
1080 void sp_selection_paste_style()
1082     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1083     if (desktop == NULL) return;
1085     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1087     // check if something is in the clipboard
1088     if (clipboard == NULL) {
1089         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1090         return;
1091     }
1093     // check if something is selected
1094     if (selection->isEmpty()) {
1095         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1096         return;
1097     }
1099     paste_defs (&defs_clipboard, SP_DT_DOCUMENT(desktop));
1101     sp_desktop_set_style (desktop, style_clipboard);
1103     sp_document_done(SP_DT_DOCUMENT (desktop));
1106 void sp_selection_to_next_layer () 
1108     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1110     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
1112     // check if something is selected
1113     if (selection->isEmpty()) {
1114         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1115         return;
1116     }
1118     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1120     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1121     if (next) {
1122         GSList *temp_clip = NULL;
1123         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1124         sp_selection_delete_impl (items);
1125         GSList *copied = sp_selection_paste_impl (SP_DT_DOCUMENT (dt), next, &temp_clip, NULL);
1126         selection->setReprList((GSList const *) copied);
1127         g_slist_free (copied);
1128         if (temp_clip) g_slist_free (temp_clip);
1129         dt->setCurrentLayer(next);
1130         sp_document_done(SP_DT_DOCUMENT (dt));
1131     } else {
1132         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1133     }
1135     g_slist_free ((GSList *) items);
1138 void sp_selection_to_prev_layer () 
1140     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1142     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
1144     // check if something is selected
1145     if (selection->isEmpty()) {
1146         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1147         return;
1148     }
1150     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1152     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1153     if (next) {
1154         GSList *temp_clip = NULL;
1155         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1156         sp_selection_delete_impl (items); 
1157         GSList *copied = sp_selection_paste_impl (SP_DT_DOCUMENT (dt), next, &temp_clip, NULL);
1158         selection->setReprList((GSList const *) copied);
1159         g_slist_free (copied);
1160         if (temp_clip) g_slist_free (temp_clip);
1161         dt->setCurrentLayer(next);
1162         sp_document_done(SP_DT_DOCUMENT (dt));
1163     } else {
1164         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1165     }
1167     g_slist_free ((GSList *) items);
1170 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1172     if (selection->isEmpty())
1173         return;
1175     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1176         SPItem *item = SP_ITEM(l->data);
1178 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1179          At the time of writing, this is the only place to re-enable. */
1180         sp_item_update_cns(*item, selection->desktop());
1181 #endif
1183         // we're moving both a clone and its original
1184         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1185         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)))) ));
1186         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1187         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1189         // "clones are unmoved when original is moved" preference
1190         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1191         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1192         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1194         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1195         // transform of its original and respond to it itself. Without this, a clone is doubly
1196         // transformed, very unintuitive.
1197       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1198       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1199       // Same for linked offset if we are also moving its source: do not move it.
1200         if (transform_textpath_with_path || transform_offset_with_source) {
1201                 // restore item->transform field from the repr, in case it was changed by seltrans
1202             sp_object_read_attr (SP_OBJECT (item), "transform");
1204         } else if (transform_flowtext_with_frame) {
1205             // apply the inverse of the region's transform to the <use> so that the flow remains
1206             // the same (even though the output itself gets transformed)
1207             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1208                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1209                     continue;
1210                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1211                     if (!SP_IS_USE(use)) continue;
1212                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1213                 }
1214             }
1215         } else if (transform_clone_with_original) {
1216             // We are transforming a clone along with its original. The below matrix juggling is
1217             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1218             // transform and its move compensation are both cancelled out.
1220             // restore item->transform field from the repr, in case it was changed by seltrans
1221             sp_object_read_attr (SP_OBJECT (item), "transform");
1223             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1224             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1225             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item); 
1226             NR::Matrix result = t_inv * item->transform * t;
1228             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1229                 // we need to cancel out the move compensation, too
1231                 // find out the clone move, same as in sp_use_move_compensate
1232                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1233                 NR::Matrix clone_move = parent.inverse() * t * parent;
1235                 if (prefs_parallel) {
1236                     NR::Matrix move = result * clone_move * t_inv;
1237                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1239                 } else if (prefs_unmoved) {
1240                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1241                         clone_move = NR::identity();
1242                     NR::Matrix move = result * clone_move;
1243                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1244                 }
1246             } else {
1247                 // just apply the result
1248                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1249             }
1251         } else {
1252             if (set_i2d) {
1253                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1254             }
1255             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1256         }
1257     }
1260 void sp_selection_remove_transform()
1262     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1263     if (desktop == NULL)
1264         return;
1266     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1268     GSList const *l = (GSList *) selection->reprList();
1269     while (l != NULL) {
1270         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1271         l = l->next;
1272     }
1274     sp_document_done(SP_DT_DOCUMENT(desktop));
1277 void
1278 sp_selection_scale_absolute(Inkscape::Selection *selection,
1279                             double const x0, double const x1,
1280                             double const y0, double const y1)
1282     if (selection->isEmpty())
1283         return;
1285     NR::Rect const bbox(selection->bounds());
1286     if (bbox.isEmpty()) {
1287         return; 
1288     }
1290     NR::translate const p2o(-bbox.min());
1292     NR::scale const newSize(x1 - x0,
1293                             y1 - y0);
1294     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1295     NR::translate const o2n(x0, y0);
1296     NR::Matrix const final( p2o * scale * o2n );
1298     sp_selection_apply_affine(selection, final);
1302 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1304     if (selection->isEmpty())
1305         return;
1307     NR::Rect const bbox(selection->bounds());
1309     if (bbox.isEmpty()) {
1310         return;
1311     }
1313     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1314     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1315          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1316     {
1317         return;
1318     }
1320     NR::translate const n2d(-align);
1321     NR::translate const d2n(align);
1322     NR::Matrix const final( n2d * scale * d2n );
1323     sp_selection_apply_affine(selection, final);
1326 void
1327 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1329     NR::translate const d2n(center);
1330     NR::translate const n2d(-center);
1331     NR::rotate const rotate(rotate_degrees(angle_degrees));
1332     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1333     sp_selection_apply_affine(selection, final);
1336 void
1337 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1339     NR::translate const d2n(align);
1340     NR::translate const n2d(-align);
1341     NR::Matrix const skew(1, dy,
1342                           dx, 1,
1343                           0, 0);
1344     NR::Matrix const final( n2d * skew * d2n );
1345     sp_selection_apply_affine(selection, final);
1348 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1350     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1353 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1355     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1359 /**
1360  * \brief sp_selection_rotate_90
1361  *
1362  * This function rotates selected objects 90 degrees clockwise.
1363  *
1364  */
1366 void sp_selection_rotate_90_cw()
1368     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1370     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1372     if (selection->isEmpty())
1373         return;
1375     GSList const *l = selection->itemList();
1376     NR::rotate const rot_neg_90(NR::Point(0, -1));
1377     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1378         SPItem *item = SP_ITEM(l2->data);
1379         sp_item_rotate_rel(item, rot_neg_90);
1380     }
1382     sp_document_done(SP_DT_DOCUMENT(desktop));
1386 /**
1387  * \brief sp_selection_rotate_90_ccw
1388  *
1389  * This function rotates selected objects 90 degrees counter-clockwise.
1390  *
1391  */
1393 void sp_selection_rotate_90_ccw()
1395     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1397     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1399     if (selection->isEmpty())
1400         return;
1402     GSList const *l = selection->itemList();
1403     NR::rotate const rot_neg_90(NR::Point(0, 1));
1404     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1405         SPItem *item = SP_ITEM(l2->data);
1406         sp_item_rotate_rel(item, rot_neg_90);
1407     }
1409     sp_document_done(SP_DT_DOCUMENT(desktop));
1412 void
1413 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1415     if (selection->isEmpty())
1416         return;
1418     NR::Point const center(selection->bounds().midpoint());
1420     sp_selection_rotate_relative(selection, center, angle_degrees);
1422     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1423                            ( ( angle_degrees > 0 )
1424                              ? "selector:rotate:ccw"
1425                              : "selector:rotate:cw" ));
1428 /**
1429 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1430 */
1431 void
1432 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1434     if (selection->isEmpty())
1435         return;
1437     NR::Rect const bbox(selection->bounds());
1438     NR::Point const center(bbox.midpoint());
1440     gdouble const zoom = selection->desktop()->current_zoom();
1441     gdouble const zmove = angle / zoom;
1442     gdouble const r = NR::L2(bbox.max() - center);
1444     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1446     sp_selection_rotate_relative(selection, center, zangle);
1448     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1449                            ( (angle > 0)
1450                              ? "selector:rotate:ccw"
1451                              : "selector:rotate:cw" ));
1454 void
1455 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1457     if (selection->isEmpty())
1458         return;
1460     NR::Rect const bbox(selection->bounds());
1461     NR::Point const center(bbox.midpoint());
1462     double const max_len = bbox.maxExtent();
1464     // you can't scale "do nizhe pola" (below zero)
1465     if ( max_len + grow <= 1e-3 ) {
1466         return;
1467     }
1469     double const times = 1.0 + grow / max_len;
1470     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1472     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1473                            ( (grow > 0)
1474                              ? "selector:scale:larger"
1475                              : "selector:scale:smaller" ));
1478 void
1479 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1481     sp_selection_scale(selection,
1482                        grow_pixels / selection->desktop()->current_zoom());
1485 void
1486 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1488     if (selection->isEmpty())
1489         return;
1491     NR::Point const center(selection->bounds().midpoint());
1492     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1493     sp_document_done(SP_DT_DOCUMENT(selection->desktop()));
1496 void
1497 sp_selection_move(gdouble dx, gdouble dy)
1499     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1500     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1501     if (selection->isEmpty()) {
1502         return;
1503     }
1505     sp_selection_move_relative(selection, dx, dy);
1507     if (dx == 0) {
1508         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1509     } else if (dy == 0) {
1510         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1511     } else {
1512         sp_document_done(SP_DT_DOCUMENT(desktop));
1513     }
1516 void
1517 sp_selection_move_screen(gdouble dx, gdouble dy)
1519     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1521     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1522     if (selection->isEmpty()) {
1523         return;
1524     }
1526     // same as sp_selection_move but divide deltas by zoom factor
1527     gdouble const zoom = desktop->current_zoom();
1528     gdouble const zdx = dx / zoom;
1529     gdouble const zdy = dy / zoom;
1530     sp_selection_move_relative(selection, zdx, zdy);
1532     if (dx == 0) {
1533         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1534     } else if (dy == 0) {
1535         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1536     } else {
1537         sp_document_done(SP_DT_DOCUMENT(desktop));
1538     }
1541 namespace {
1543 template <typename D>
1544 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1545                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive);
1547 template <typename D>
1548 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root, 
1549                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive);
1551 struct Forward {
1552     typedef SPObject *Iterator;
1554     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1555     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1556     static void dispose(Iterator i) {}
1558     static SPObject *object(Iterator i) { return i; }
1559     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1560 };
1562 struct Reverse {
1563     typedef GSList *Iterator;
1565     static Iterator children(SPObject *o) {
1566         return make_list(o->firstChild(), NULL);
1567     }
1568     static Iterator siblings_after(SPObject *o) {
1569         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1570     }
1571     static void dispose(Iterator i) {
1572         g_slist_free(i);
1573     }
1575     static SPObject *object(Iterator i) {
1576         return reinterpret_cast<SPObject *>(i->data);
1577     }
1578     static Iterator next(Iterator i) { return i->next; }
1580 private:
1581     static GSList *make_list(SPObject *object, SPObject *limit) {
1582         GSList *list=NULL;
1583         while ( object != limit ) {
1584             list = g_slist_prepend(list, object);
1585             object = SP_OBJECT_NEXT(object);
1586         }
1587         return list;
1588     }
1589 };
1593 void
1594 sp_selection_item_next(void)
1596     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1597     g_return_if_fail(desktop != NULL);
1598     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1600     bool inlayer = prefs_get_int_attribute ("options.kbselection", "inlayer", 1);
1601     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1602     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1604     SPObject *root;
1605     if (inlayer) {
1606         root = desktop->currentLayer();
1607     } else {
1608         root = desktop->currentRoot();
1609     }
1611     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1613     if (item) {
1614         selection->set(item);
1615         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1616             scroll_to_show_item(desktop, item);
1617         }
1618     }
1621 void
1622 sp_selection_item_prev(void)
1624     SPDocument *document = SP_ACTIVE_DOCUMENT;
1625     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1626     g_return_if_fail(document != NULL);
1627     g_return_if_fail(desktop != NULL);
1628     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1630     bool inlayer = prefs_get_int_attribute ("options.kbselection", "inlayer", 1);
1631     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1632     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1634     SPObject *root;
1635     if (inlayer) {
1636         root = desktop->currentLayer();
1637     } else {
1638         root = desktop->currentRoot();
1639     }
1641     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1643     if (item) {
1644         selection->set(item);
1645         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1646             scroll_to_show_item(desktop, item);
1647         }
1648     }
1651 namespace {
1653 template <typename D>
1654 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1655                             SPObject *root, bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive)
1657     SPObject *current=root;
1658     while (items) {
1659         SPItem *item=SP_ITEM(items->data);
1660         if ( root->isAncestorOf(item) &&
1661              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1662         {
1663             current = item;
1664             break;
1665         }
1666         items = items->next;
1667     }
1669     GSList *path=NULL;
1670     while ( current != root ) {
1671         path = g_slist_prepend(path, current);
1672         current = SP_OBJECT_PARENT(current);
1673     }
1675     SPItem *next;
1676     // first, try from the current object
1677     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1678     g_slist_free(path);
1680     if (!next) { // if we ran out of objects, start over at the root
1681         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1682     }
1684     return next;
1687 template <typename D>
1688 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1689                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive)
1691     typename D::Iterator children;
1692     typename D::Iterator iter;
1694     SPItem *found=NULL;
1696     if (path) {
1697         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1698         g_assert(SP_OBJECT_PARENT(object) == root);
1699         if (desktop->isLayer(object)) {
1700             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1701         }
1702         iter = children = D::siblings_after(object);
1703     } else {
1704         iter = children = D::children(root);
1705     }
1707     while ( iter && !found ) {
1708         SPObject *object=D::object(iter);
1709         if (desktop->isLayer(object)) {
1710             if (!inlayer) { // recurse into sublayers
1711                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1712             }
1713         } else if ( SP_IS_ITEM(object) &&
1714                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1715                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1716                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1717                     !desktop->isLayer(SP_ITEM(object)) )
1718         {
1719             found = SP_ITEM(object);
1720         }
1721         iter = D::next(iter);
1722     }
1724     D::dispose(children);
1726     return found;
1731 /**
1732  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1733  * \a item.
1734  */
1735 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1737     NR::Rect dbox = desktop->get_display_area();
1738     NR::Rect sbox = sp_item_bbox_desktop(item);
1740     if (dbox.contains(sbox) == false) {
1741         NR::Point const s_dt = sbox.midpoint();
1742         NR::Point const s_w = desktop->d2w(s_dt);
1743         NR::Point const d_dt = dbox.midpoint();
1744         NR::Point const d_w = desktop->d2w(d_dt);
1745         NR::Point const moved_w( d_w - s_w );
1746         gint const dx = (gint) moved_w[X];
1747         gint const dy = (gint) moved_w[Y];
1748         desktop->scroll_world(dx, dy);
1749     }
1753 void
1754 sp_selection_clone()
1756     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1757     if (desktop == NULL)
1758         return;
1760     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1762     // check if something is selected
1763     if (selection->isEmpty()) {
1764         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1765         return;
1766     }
1768     // Check if more than one object is selected.
1769     if (g_slist_length((GSList *) selection->itemList()) > 1) {
1770         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("If you want to clone several objects, <b>group</b> them and <b>clone the group</b>."));
1771         return;
1772     }
1774     Inkscape::XML::Node *sel_repr = SP_OBJECT_REPR(selection->singleItem());
1775     Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1777     Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1778     clone->setAttribute("x", "0");
1779     clone->setAttribute("y", "0");
1780     clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1782     // add the new clone to the top of the original's parent
1783     parent->appendChild(clone);
1785     sp_document_done(SP_DT_DOCUMENT(desktop));
1787     selection->set(clone);
1788     Inkscape::GC::release(clone);
1791 void
1792 sp_selection_unlink()
1794     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1795     if (!desktop)
1796         return;
1798     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1800     if (selection->isEmpty()) {
1801         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
1802         return;
1803     }
1805     // Get a copy of current selection.
1806     GSList *new_select = NULL;
1807     bool unlinked = false;
1808     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1809          items != NULL;
1810          items = items->next)
1811     {
1812         SPItem *use = (SPItem *) items->data;
1814         if (!SP_IS_USE(use)) {
1815             // keep the non-yse item in the new selection
1816             new_select = g_slist_prepend(new_select, use);
1817             continue;
1818         }
1820         SPItem *unlink = sp_use_unlink(SP_USE(use));
1821         unlinked = true;
1822         // Add ungrouped items to the new selection.
1823         new_select = g_slist_prepend(new_select, unlink);
1824     }
1826     if (new_select) { // set new selection
1827         selection->clear();
1828         selection->setList(new_select);
1829         g_slist_free(new_select);
1830     }
1831     if (!unlinked) {
1832         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1833     }
1835     sp_document_done(SP_DT_DOCUMENT(desktop));
1838 void
1839 sp_select_clone_original()
1841     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1842     if (desktop == NULL)
1843         return;
1845     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1847     SPItem *item = selection->singleItem();
1849     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.");
1851     // Check if other than two objects are selected
1852     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
1853         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1854         return;
1855     }
1857     SPItem *original = NULL;
1858     if (SP_IS_USE(item)) {
1859         original = sp_use_get_original (SP_USE(item));
1860     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
1861         original = sp_offset_get_source (SP_OFFSET(item));
1862     } else if (SP_IS_TEXT_TEXTPATH(item)) {
1863         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
1864     } else if (SP_IS_FLOWTEXT(item)) {
1865         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
1866     } else { // it's an object that we don't know what to do with
1867         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1868         return;
1869     }
1871     if (!original) {
1872         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
1873         return;
1874     }
1876     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
1877         if (SP_IS_DEFS (o)) {
1878             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
1879             return;
1880         }
1881     }
1883     if (original) {
1884         selection->clear();
1885         selection->set(original);
1886         if (SP_CYCLING == SP_CYCLE_FOCUS) {
1887             scroll_to_show_item(desktop, original);
1888         }
1889     }
1892 void
1893 sp_selection_tile(bool apply)
1895     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1896     if (desktop == NULL)
1897         return;
1899     SPDocument *document = SP_DT_DOCUMENT(desktop);
1901     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1903     // check if something is selected
1904     if (selection->isEmpty()) {
1905         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
1906         return;
1907     }
1909     sp_document_ensure_up_to_date(document);
1910     NR::Rect r = selection->bounds();
1911     if (r.isEmpty()) {
1912         return;
1913     }
1915     // calculate the transform to be applied to objects to move them to 0,0
1916     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
1917     move_p[NR::Y] = -move_p[NR::Y];
1918     NR::Matrix move = NR::Matrix (NR::translate (move_p));
1920     GSList *items = g_slist_copy((GSList *) selection->itemList());
1922     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
1924     // bottommost object, after sorting
1925     SPObject *parent = SP_OBJECT_PARENT (items->data);
1927     // remember the position of the first item
1928     gint pos = SP_OBJECT_REPR (items->data)->position();
1930     // create a list of duplicates
1931     GSList *repr_copies = NULL;
1932     for (GSList *i = items; i != NULL; i = i->next) {
1933         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
1934         repr_copies = g_slist_prepend (repr_copies, dup);
1935     }
1937     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
1939     if (apply) {
1940         // delete objects so that their clones don't get alerted; this object will be restored shortly
1941         for (GSList *i = items; i != NULL; i = i->next) {
1942             SPObject *item = SP_OBJECT (i->data);
1943             item->deleteObject (false);
1944         }
1945     }
1947     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
1948     // without disturbing clones.
1949     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
1950     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1951     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1953     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
1954                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))), move);
1956     // restore compensation setting
1957     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
1959     if (apply) {
1960         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
1961         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
1962         sp_repr_set_svg_double(rect, "width", bounds.extent(NR::X));
1963         sp_repr_set_svg_double(rect, "height", bounds.extent(NR::Y));
1964         sp_repr_set_svg_double(rect, "x", bounds.min()[NR::X]);
1965         sp_repr_set_svg_double(rect, "y", bounds.min()[NR::Y]);
1967         // restore parent and position
1968         SP_OBJECT_REPR (parent)->appendChild(rect);
1969         rect->setPosition(pos > 0 ? pos : 0);
1970         SPItem *rectangle = (SPItem *) SP_DT_DOCUMENT (desktop)->getObjectByRepr(rect);
1972         Inkscape::GC::release(rect);
1974         selection->clear();
1975         selection->set(rectangle);
1976     }
1978     g_slist_free (items);
1980     sp_document_done (document);
1983 void
1984 sp_selection_untile()
1986     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1987     if (desktop == NULL)
1988         return;
1990     SPDocument *document = SP_DT_DOCUMENT(desktop);
1992     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1994     // check if something is selected
1995     if (selection->isEmpty()) {
1996         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
1997         return;
1998     }
2000     GSList *new_select = NULL;
2002     bool did = false;
2004     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2005          items != NULL;
2006          items = items->next) {
2008         SPItem *item = (SPItem *) items->data;
2010         SPStyle *style = SP_OBJECT_STYLE (item);
2012         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER) 
2013             continue;
2015         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2017         if (!SP_IS_PATTERN(server))
2018             continue;
2020         did = true;
2022         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2024         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2025         pat_transform *= item->transform;
2027         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2028             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2029             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2031            // FIXME: relink clones to the new canvas objects
2032            // use SPObject::setid when mental finishes it to steal ids of 
2034             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2035             sp_document_ensure_up_to_date (document);
2037             NR::Matrix transform( i->transform * pat_transform );
2038             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2040             new_select = g_slist_prepend(new_select, i);
2041         }
2043         SPCSSAttr *css = sp_repr_css_attr_new ();
2044         sp_repr_css_set_property (css, "fill", "none");
2045         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2046     }
2048     if (!did) {
2049         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2050     } else {
2051         sp_document_done(SP_DT_DOCUMENT(desktop));
2052         selection->setList(new_select);
2053     }
2056 void
2057 sp_selection_create_bitmap_copy ()
2059     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2060     if (desktop == NULL)
2061         return;
2063     SPDocument *document = SP_DT_DOCUMENT(desktop);
2065     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2067     // check if something is selected
2068     if (selection->isEmpty()) {
2069         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2070         return;
2071     }
2073     // Get the bounding box of the selection
2074     NRRect bbox;
2075     sp_document_ensure_up_to_date (document);
2076     selection->bounds(&bbox);
2077     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2078         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2079     }
2081     // List of the items to show; all others will be hidden
2082     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2084     // Sort items so that the topmost comes last
2085     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2087     // Generate a random value from the current time (you may create bitmap from the same object(s)
2088     // multiple times, and this is done so that they don't clash)
2089     GTimeVal cu;
2090     g_get_current_time (&cu);
2091     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024; 
2093     // Create the filename
2094     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2095     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2096     // digits, and a few other chars, with "_"
2097     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2098     // Build the complete path by adding document->base if set
2099     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2101     //g_print ("%s\n", filepath);
2103     // Remember parent and z-order of the topmost one
2104     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2105     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2106     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2108     // Calculate resolution
2109     double res;
2110     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2111     if (0 < prefs_res) {
2112         // If it's given explicitly in prefs, take it
2113         res = prefs_res;
2114     } else {
2115         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2116         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2117         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2118     }
2120     // The width and height of the bitmap in pixels
2121     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2122     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2124     // Find out if we have to run a filter
2125     const gchar *run = NULL;
2126     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2127     if (filter) {
2128         // filter command is given;
2129         // see if we have a parameter to pass to it
2130         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2131         if (param1) {
2132             if (param1[strlen(param1) - 1] == '%') {
2133                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2134                 gchar p1[256];
2135                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2136                 // the first param is always the image filename, the second is param1
2137                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2138             } else {
2139                 // otherwise pass the param1 unchanged
2140                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2141             }
2142         } else {
2143             // run without extra parameter
2144             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2145         }
2146     }
2148     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2149     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2150     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse(); 
2152     // Do the export
2153     sp_export_png_file(document, filepath,
2154                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2155                    width, height,
2156                    (guint32) 0xffffff00,
2157                    NULL, NULL,
2158                    true,  /*bool force_overwrite,*/
2159                    items);
2161     g_slist_free (items);
2163     // Run filter, if any
2164     if (run) {
2165         g_print ("Running external filter: %s\n", run);
2166         system (run);
2167     }
2169     // Import the image back
2170     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2171     if (pb) {
2172         // Create the repr for the image
2173         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2174         repr->setAttribute("xlink:href", filename);
2175         repr->setAttribute("sodipodi:absref", filepath);
2176         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2177         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2179         // Write transform
2180         gchar c[256];
2181         if (sp_svg_transform_write(c, 256, t)) {
2182             repr->setAttribute("transform", c);
2183         } 
2185         // add the new repr to the parent
2186         parent->appendChild(repr);
2188         // move to the saved position 
2189         repr->setPosition(pos > 0 ? pos + 1 : 1);
2191         // Set selection to the new image
2192         selection->clear();
2193         selection->add(repr);
2195         // Clean up
2196         Inkscape::GC::release(repr);
2197         gdk_pixbuf_unref (pb);
2199         // Complete undoable transaction
2200         sp_document_done (document);
2201     }
2203     g_free (filename);
2204     g_free (filepath);
2208 /*
2209   Local Variables:
2210   mode:c++
2211   c-file-style:"stroustrup"
2212   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2213   indent-tabs-mode:nil
2214   fill-column:99
2215   End:
2216 */
2217 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :