Code

bulk trailing spaces removal. consistency through MD5 of binary
[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     }
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;
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 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1171 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1172 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1173 that case, items are already in the new position, but the repr is in the old, and this function
1174 then simply updates the repr from item->transform.
1175  */
1176 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1178     if (selection->isEmpty())
1179         return;
1181     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1182         SPItem *item = SP_ITEM(l->data);
1184         NR::Point old_center(0,0);
1185         if (set_i2d && item->isCenterSet())
1186             old_center = item->getCenter();
1188 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1189          At the time of writing, this is the only place to re-enable. */
1190         sp_item_update_cns(*item, selection->desktop());
1191 #endif
1193         // we're moving both a clone and its original
1194         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1195         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)))) ));
1196         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1197         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1199         // "clones are unmoved when original is moved" preference
1200         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1201         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1202         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1204         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1205         // transform of its original and respond to it itself. Without this, a clone is doubly
1206         // transformed, very unintuitive.
1207       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1208       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1209       // Same for linked offset if we are also moving its source: do not move it.
1210         if (transform_textpath_with_path || transform_offset_with_source) {
1211                 // restore item->transform field from the repr, in case it was changed by seltrans
1212             sp_object_read_attr (SP_OBJECT (item), "transform");
1214         } else if (transform_flowtext_with_frame) {
1215             // apply the inverse of the region's transform to the <use> so that the flow remains
1216             // the same (even though the output itself gets transformed)
1217             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1218                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1219                     continue;
1220                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1221                     if (!SP_IS_USE(use)) continue;
1222                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1223                 }
1224             }
1225         } else if (transform_clone_with_original) {
1226             // We are transforming a clone along with its original. The below matrix juggling is
1227             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1228             // transform and its move compensation are both cancelled out.
1230             // restore item->transform field from the repr, in case it was changed by seltrans
1231             sp_object_read_attr (SP_OBJECT (item), "transform");
1233             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1234             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1235             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1236             NR::Matrix result = t_inv * item->transform * t;
1238             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1239                 // we need to cancel out the move compensation, too
1241                 // find out the clone move, same as in sp_use_move_compensate
1242                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1243                 NR::Matrix clone_move = parent.inverse() * t * parent;
1245                 if (prefs_parallel) {
1246                     NR::Matrix move = result * clone_move * t_inv;
1247                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1249                 } else if (prefs_unmoved) {
1250                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1251                         clone_move = NR::identity();
1252                     NR::Matrix move = result * clone_move;
1253                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1254                 }
1256             } else {
1257                 // just apply the result
1258                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1259             }
1261         } else {
1262             if (set_i2d) {
1263                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1264             }
1265             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1266         }
1268         // if we're moving the actual object, not just updating the repr, we can transform the
1269         // center by the same matrix (only necessary for non-translations)
1270         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1271             item->setCenter(old_center * affine);
1272             SP_OBJECT(item)->updateRepr();
1273         }
1274     }
1277 void sp_selection_remove_transform()
1279     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1280     if (desktop == NULL)
1281         return;
1283     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1285     GSList const *l = (GSList *) selection->reprList();
1286     while (l != NULL) {
1287         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1288         l = l->next;
1289     }
1291     sp_document_done(SP_DT_DOCUMENT(desktop));
1294 void
1295 sp_selection_scale_absolute(Inkscape::Selection *selection,
1296                             double const x0, double const x1,
1297                             double const y0, double const y1)
1299     if (selection->isEmpty())
1300         return;
1302     NR::Rect const bbox(selection->bounds());
1303     if (bbox.isEmpty()) {
1304         return;
1305     }
1307     NR::translate const p2o(-bbox.min());
1309     NR::scale const newSize(x1 - x0,
1310                             y1 - y0);
1311     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1312     NR::translate const o2n(x0, y0);
1313     NR::Matrix const final( p2o * scale * o2n );
1315     sp_selection_apply_affine(selection, final);
1319 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1321     if (selection->isEmpty())
1322         return;
1324     NR::Rect const bbox(selection->bounds());
1326     if (bbox.isEmpty()) {
1327         return;
1328     }
1330     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1331     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1332          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1333     {
1334         return;
1335     }
1337     NR::translate const n2d(-align);
1338     NR::translate const d2n(align);
1339     NR::Matrix const final( n2d * scale * d2n );
1340     sp_selection_apply_affine(selection, final);
1343 void
1344 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1346     NR::translate const d2n(center);
1347     NR::translate const n2d(-center);
1348     NR::rotate const rotate(rotate_degrees(angle_degrees));
1349     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1350     sp_selection_apply_affine(selection, final);
1353 void
1354 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1356     NR::translate const d2n(align);
1357     NR::translate const n2d(-align);
1358     NR::Matrix const skew(1, dy,
1359                           dx, 1,
1360                           0, 0);
1361     NR::Matrix const final( n2d * skew * d2n );
1362     sp_selection_apply_affine(selection, final);
1365 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1367     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1370 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1372     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1376 /**
1377  * \brief sp_selection_rotate_90
1378  *
1379  * This function rotates selected objects 90 degrees clockwise.
1380  *
1381  */
1383 void sp_selection_rotate_90_cw()
1385     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1387     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1389     if (selection->isEmpty())
1390         return;
1392     GSList const *l = selection->itemList();
1393     NR::rotate const rot_neg_90(NR::Point(0, -1));
1394     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1395         SPItem *item = SP_ITEM(l2->data);
1396         sp_item_rotate_rel(item, rot_neg_90);
1397     }
1399     sp_document_done(SP_DT_DOCUMENT(desktop));
1403 /**
1404  * \brief sp_selection_rotate_90_ccw
1405  *
1406  * This function rotates selected objects 90 degrees counter-clockwise.
1407  *
1408  */
1410 void sp_selection_rotate_90_ccw()
1412     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1414     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1416     if (selection->isEmpty())
1417         return;
1419     GSList const *l = selection->itemList();
1420     NR::rotate const rot_neg_90(NR::Point(0, 1));
1421     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1422         SPItem *item = SP_ITEM(l2->data);
1423         sp_item_rotate_rel(item, rot_neg_90);
1424     }
1426     sp_document_done(SP_DT_DOCUMENT(desktop));
1429 void
1430 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1432     if (selection->isEmpty())
1433         return;
1435     NR::Point const center(selection->bounds().midpoint());
1437     sp_selection_rotate_relative(selection, center, angle_degrees);
1439     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1440                            ( ( angle_degrees > 0 )
1441                              ? "selector:rotate:ccw"
1442                              : "selector:rotate:cw" ));
1445 /**
1446 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1447 */
1448 void
1449 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1451     if (selection->isEmpty())
1452         return;
1454     NR::Rect const bbox(selection->bounds());
1455     NR::Point const center(bbox.midpoint());
1457     gdouble const zoom = selection->desktop()->current_zoom();
1458     gdouble const zmove = angle / zoom;
1459     gdouble const r = NR::L2(bbox.max() - center);
1461     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1463     sp_selection_rotate_relative(selection, center, zangle);
1465     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1466                            ( (angle > 0)
1467                              ? "selector:rotate:ccw"
1468                              : "selector:rotate:cw" ));
1471 void
1472 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1474     if (selection->isEmpty())
1475         return;
1477     NR::Rect const bbox(selection->bounds());
1478     NR::Point const center(bbox.midpoint());
1479     double const max_len = bbox.maxExtent();
1481     // you can't scale "do nizhe pola" (below zero)
1482     if ( max_len + grow <= 1e-3 ) {
1483         return;
1484     }
1486     double const times = 1.0 + grow / max_len;
1487     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1489     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1490                            ( (grow > 0)
1491                              ? "selector:scale:larger"
1492                              : "selector:scale:smaller" ));
1495 void
1496 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1498     sp_selection_scale(selection,
1499                        grow_pixels / selection->desktop()->current_zoom());
1502 void
1503 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1505     if (selection->isEmpty())
1506         return;
1508     NR::Point const center(selection->bounds().midpoint());
1509     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1510     sp_document_done(SP_DT_DOCUMENT(selection->desktop()));
1513 void
1514 sp_selection_move(gdouble dx, gdouble dy)
1516     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1517     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1518     if (selection->isEmpty()) {
1519         return;
1520     }
1522     sp_selection_move_relative(selection, dx, dy);
1524     if (dx == 0) {
1525         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1526     } else if (dy == 0) {
1527         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1528     } else {
1529         sp_document_done(SP_DT_DOCUMENT(desktop));
1530     }
1533 void
1534 sp_selection_move_screen(gdouble dx, gdouble dy)
1536     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1538     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1539     if (selection->isEmpty()) {
1540         return;
1541     }
1543     // same as sp_selection_move but divide deltas by zoom factor
1544     gdouble const zoom = desktop->current_zoom();
1545     gdouble const zdx = dx / zoom;
1546     gdouble const zdy = dy / zoom;
1547     sp_selection_move_relative(selection, zdx, zdy);
1549     if (dx == 0) {
1550         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1551     } else if (dy == 0) {
1552         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1553     } else {
1554         sp_document_done(SP_DT_DOCUMENT(desktop));
1555     }
1558 namespace {
1560 template <typename D>
1561 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1562                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive);
1564 template <typename D>
1565 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1566                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive);
1568 struct Forward {
1569     typedef SPObject *Iterator;
1571     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1572     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1573     static void dispose(Iterator i) {}
1575     static SPObject *object(Iterator i) { return i; }
1576     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1577 };
1579 struct Reverse {
1580     typedef GSList *Iterator;
1582     static Iterator children(SPObject *o) {
1583         return make_list(o->firstChild(), NULL);
1584     }
1585     static Iterator siblings_after(SPObject *o) {
1586         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1587     }
1588     static void dispose(Iterator i) {
1589         g_slist_free(i);
1590     }
1592     static SPObject *object(Iterator i) {
1593         return reinterpret_cast<SPObject *>(i->data);
1594     }
1595     static Iterator next(Iterator i) { return i->next; }
1597 private:
1598     static GSList *make_list(SPObject *object, SPObject *limit) {
1599         GSList *list=NULL;
1600         while ( object != limit ) {
1601             list = g_slist_prepend(list, object);
1602             object = SP_OBJECT_NEXT(object);
1603         }
1604         return list;
1605     }
1606 };
1610 void
1611 sp_selection_item_next(void)
1613     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1614     g_return_if_fail(desktop != NULL);
1615     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1617     bool inlayer = prefs_get_int_attribute ("options.kbselection", "inlayer", 1);
1618     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1619     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1621     SPObject *root;
1622     if (inlayer) {
1623         root = desktop->currentLayer();
1624     } else {
1625         root = desktop->currentRoot();
1626     }
1628     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1630     if (item) {
1631         selection->set(item);
1632         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1633             scroll_to_show_item(desktop, item);
1634         }
1635     }
1638 void
1639 sp_selection_item_prev(void)
1641     SPDocument *document = SP_ACTIVE_DOCUMENT;
1642     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1643     g_return_if_fail(document != NULL);
1644     g_return_if_fail(desktop != NULL);
1645     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1647     bool inlayer = prefs_get_int_attribute ("options.kbselection", "inlayer", 1);
1648     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1649     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1651     SPObject *root;
1652     if (inlayer) {
1653         root = desktop->currentLayer();
1654     } else {
1655         root = desktop->currentRoot();
1656     }
1658     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1660     if (item) {
1661         selection->set(item);
1662         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1663             scroll_to_show_item(desktop, item);
1664         }
1665     }
1668 namespace {
1670 template <typename D>
1671 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1672                             SPObject *root, bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive)
1674     SPObject *current=root;
1675     while (items) {
1676         SPItem *item=SP_ITEM(items->data);
1677         if ( root->isAncestorOf(item) &&
1678              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1679         {
1680             current = item;
1681             break;
1682         }
1683         items = items->next;
1684     }
1686     GSList *path=NULL;
1687     while ( current != root ) {
1688         path = g_slist_prepend(path, current);
1689         current = SP_OBJECT_PARENT(current);
1690     }
1692     SPItem *next;
1693     // first, try from the current object
1694     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1695     g_slist_free(path);
1697     if (!next) { // if we ran out of objects, start over at the root
1698         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1699     }
1701     return next;
1704 template <typename D>
1705 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1706                   bool only_in_viewport, bool inlayer, bool onlyvisible, bool onlysensitive)
1708     typename D::Iterator children;
1709     typename D::Iterator iter;
1711     SPItem *found=NULL;
1713     if (path) {
1714         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1715         g_assert(SP_OBJECT_PARENT(object) == root);
1716         if (desktop->isLayer(object)) {
1717             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1718         }
1719         iter = children = D::siblings_after(object);
1720     } else {
1721         iter = children = D::children(root);
1722     }
1724     while ( iter && !found ) {
1725         SPObject *object=D::object(iter);
1726         if (desktop->isLayer(object)) {
1727             if (!inlayer) { // recurse into sublayers
1728                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1729             }
1730         } else if ( SP_IS_ITEM(object) &&
1731                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1732                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1733                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1734                     !desktop->isLayer(SP_ITEM(object)) )
1735         {
1736             found = SP_ITEM(object);
1737         }
1738         iter = D::next(iter);
1739     }
1741     D::dispose(children);
1743     return found;
1748 /**
1749  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1750  * \a item.
1751  */
1752 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1754     NR::Rect dbox = desktop->get_display_area();
1755     NR::Rect sbox = sp_item_bbox_desktop(item);
1757     if (dbox.contains(sbox) == false) {
1758         NR::Point const s_dt = sbox.midpoint();
1759         NR::Point const s_w = desktop->d2w(s_dt);
1760         NR::Point const d_dt = dbox.midpoint();
1761         NR::Point const d_w = desktop->d2w(d_dt);
1762         NR::Point const moved_w( d_w - s_w );
1763         gint const dx = (gint) moved_w[X];
1764         gint const dy = (gint) moved_w[Y];
1765         desktop->scroll_world(dx, dy);
1766     }
1770 void
1771 sp_selection_clone()
1773     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1774     if (desktop == NULL)
1775         return;
1777     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1779     // check if something is selected
1780     if (selection->isEmpty()) {
1781         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1782         return;
1783     }
1785     // Check if more than one object is selected.
1786     if (g_slist_length((GSList *) selection->itemList()) > 1) {
1787         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("If you want to clone several objects, <b>group</b> them and <b>clone the group</b>."));
1788         return;
1789     }
1791     Inkscape::XML::Node *sel_repr = SP_OBJECT_REPR(selection->singleItem());
1792     Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1794     Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1795     clone->setAttribute("x", "0");
1796     clone->setAttribute("y", "0");
1797     clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1799     // add the new clone to the top of the original's parent
1800     parent->appendChild(clone);
1802     sp_document_done(SP_DT_DOCUMENT(desktop));
1804     selection->set(clone);
1805     Inkscape::GC::release(clone);
1808 void
1809 sp_selection_unlink()
1811     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1812     if (!desktop)
1813         return;
1815     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1817     if (selection->isEmpty()) {
1818         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
1819         return;
1820     }
1822     // Get a copy of current selection.
1823     GSList *new_select = NULL;
1824     bool unlinked = false;
1825     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1826          items != NULL;
1827          items = items->next)
1828     {
1829         SPItem *use = (SPItem *) items->data;
1831         if (!SP_IS_USE(use)) {
1832             // keep the non-yse item in the new selection
1833             new_select = g_slist_prepend(new_select, use);
1834             continue;
1835         }
1837         SPItem *unlink = sp_use_unlink(SP_USE(use));
1838         unlinked = true;
1839         // Add ungrouped items to the new selection.
1840         new_select = g_slist_prepend(new_select, unlink);
1841     }
1843     if (new_select) { // set new selection
1844         selection->clear();
1845         selection->setList(new_select);
1846         g_slist_free(new_select);
1847     }
1848     if (!unlinked) {
1849         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1850     }
1852     sp_document_done(SP_DT_DOCUMENT(desktop));
1855 void
1856 sp_select_clone_original()
1858     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1859     if (desktop == NULL)
1860         return;
1862     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1864     SPItem *item = selection->singleItem();
1866     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.");
1868     // Check if other than two objects are selected
1869     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
1870         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1871         return;
1872     }
1874     SPItem *original = NULL;
1875     if (SP_IS_USE(item)) {
1876         original = sp_use_get_original (SP_USE(item));
1877     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
1878         original = sp_offset_get_source (SP_OFFSET(item));
1879     } else if (SP_IS_TEXT_TEXTPATH(item)) {
1880         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
1881     } else if (SP_IS_FLOWTEXT(item)) {
1882         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
1883     } else { // it's an object that we don't know what to do with
1884         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1885         return;
1886     }
1888     if (!original) {
1889         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
1890         return;
1891     }
1893     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
1894         if (SP_IS_DEFS (o)) {
1895             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
1896             return;
1897         }
1898     }
1900     if (original) {
1901         selection->clear();
1902         selection->set(original);
1903         if (SP_CYCLING == SP_CYCLE_FOCUS) {
1904             scroll_to_show_item(desktop, original);
1905         }
1906     }
1909 void
1910 sp_selection_tile(bool apply)
1912     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1913     if (desktop == NULL)
1914         return;
1916     SPDocument *document = SP_DT_DOCUMENT(desktop);
1918     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1920     // check if something is selected
1921     if (selection->isEmpty()) {
1922         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
1923         return;
1924     }
1926     sp_document_ensure_up_to_date(document);
1927     NR::Rect r = selection->bounds();
1928     if (r.isEmpty()) {
1929         return;
1930     }
1932     // calculate the transform to be applied to objects to move them to 0,0
1933     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
1934     move_p[NR::Y] = -move_p[NR::Y];
1935     NR::Matrix move = NR::Matrix (NR::translate (move_p));
1937     GSList *items = g_slist_copy((GSList *) selection->itemList());
1939     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
1941     // bottommost object, after sorting
1942     SPObject *parent = SP_OBJECT_PARENT (items->data);
1944     // remember the position of the first item
1945     gint pos = SP_OBJECT_REPR (items->data)->position();
1947     // create a list of duplicates
1948     GSList *repr_copies = NULL;
1949     for (GSList *i = items; i != NULL; i = i->next) {
1950         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
1951         repr_copies = g_slist_prepend (repr_copies, dup);
1952     }
1954     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
1956     if (apply) {
1957         // delete objects so that their clones don't get alerted; this object will be restored shortly
1958         for (GSList *i = items; i != NULL; i = i->next) {
1959             SPObject *item = SP_OBJECT (i->data);
1960             item->deleteObject (false);
1961         }
1962     }
1964     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
1965     // without disturbing clones.
1966     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
1967     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1968     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1970     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
1971                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))), move);
1973     // restore compensation setting
1974     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
1976     if (apply) {
1977         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
1978         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
1979         sp_repr_set_svg_double(rect, "width", bounds.extent(NR::X));
1980         sp_repr_set_svg_double(rect, "height", bounds.extent(NR::Y));
1981         sp_repr_set_svg_double(rect, "x", bounds.min()[NR::X]);
1982         sp_repr_set_svg_double(rect, "y", bounds.min()[NR::Y]);
1984         // restore parent and position
1985         SP_OBJECT_REPR (parent)->appendChild(rect);
1986         rect->setPosition(pos > 0 ? pos : 0);
1987         SPItem *rectangle = (SPItem *) SP_DT_DOCUMENT (desktop)->getObjectByRepr(rect);
1989         Inkscape::GC::release(rect);
1991         selection->clear();
1992         selection->set(rectangle);
1993     }
1995     g_slist_free (items);
1997     sp_document_done (document);
2000 void
2001 sp_selection_untile()
2003     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2004     if (desktop == NULL)
2005         return;
2007     SPDocument *document = SP_DT_DOCUMENT(desktop);
2009     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2011     // check if something is selected
2012     if (selection->isEmpty()) {
2013         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2014         return;
2015     }
2017     GSList *new_select = NULL;
2019     bool did = false;
2021     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2022          items != NULL;
2023          items = items->next) {
2025         SPItem *item = (SPItem *) items->data;
2027         SPStyle *style = SP_OBJECT_STYLE (item);
2029         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2030             continue;
2032         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2034         if (!SP_IS_PATTERN(server))
2035             continue;
2037         did = true;
2039         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2041         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2042         pat_transform *= item->transform;
2044         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2045             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2046             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2048            // FIXME: relink clones to the new canvas objects
2049            // use SPObject::setid when mental finishes it to steal ids of
2051             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2052             sp_document_ensure_up_to_date (document);
2054             NR::Matrix transform( i->transform * pat_transform );
2055             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2057             new_select = g_slist_prepend(new_select, i);
2058         }
2060         SPCSSAttr *css = sp_repr_css_attr_new ();
2061         sp_repr_css_set_property (css, "fill", "none");
2062         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2063     }
2065     if (!did) {
2066         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2067     } else {
2068         sp_document_done(SP_DT_DOCUMENT(desktop));
2069         selection->setList(new_select);
2070     }
2073 void
2074 sp_selection_create_bitmap_copy ()
2076     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2077     if (desktop == NULL)
2078         return;
2080     SPDocument *document = SP_DT_DOCUMENT(desktop);
2082     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2084     // check if something is selected
2085     if (selection->isEmpty()) {
2086         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2087         return;
2088     }
2090     // Get the bounding box of the selection
2091     NRRect bbox;
2092     sp_document_ensure_up_to_date (document);
2093     selection->bounds(&bbox);
2094     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2095         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2096     }
2098     // List of the items to show; all others will be hidden
2099     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2101     // Sort items so that the topmost comes last
2102     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2104     // Generate a random value from the current time (you may create bitmap from the same object(s)
2105     // multiple times, and this is done so that they don't clash)
2106     GTimeVal cu;
2107     g_get_current_time (&cu);
2108     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2110     // Create the filename
2111     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2112     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2113     // digits, and a few other chars, with "_"
2114     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2115     // Build the complete path by adding document->base if set
2116     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2118     //g_print ("%s\n", filepath);
2120     // Remember parent and z-order of the topmost one
2121     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2122     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2123     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2125     // Calculate resolution
2126     double res;
2127     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2128     if (0 < prefs_res) {
2129         // If it's given explicitly in prefs, take it
2130         res = prefs_res;
2131     } else {
2132         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2133         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2134         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2135     }
2137     // The width and height of the bitmap in pixels
2138     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2139     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2141     // Find out if we have to run a filter
2142     const gchar *run = NULL;
2143     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2144     if (filter) {
2145         // filter command is given;
2146         // see if we have a parameter to pass to it
2147         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2148         if (param1) {
2149             if (param1[strlen(param1) - 1] == '%') {
2150                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2151                 gchar p1[256];
2152                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2153                 // the first param is always the image filename, the second is param1
2154                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2155             } else {
2156                 // otherwise pass the param1 unchanged
2157                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2158             }
2159         } else {
2160             // run without extra parameter
2161             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2162         }
2163     }
2165     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2166     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2167     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2169     // Do the export
2170     sp_export_png_file(document, filepath,
2171                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2172                    width, height,
2173                    (guint32) 0xffffff00,
2174                    NULL, NULL,
2175                    true,  /*bool force_overwrite,*/
2176                    items);
2178     g_slist_free (items);
2180     // Run filter, if any
2181     if (run) {
2182         g_print ("Running external filter: %s\n", run);
2183         system (run);
2184     }
2186     // Import the image back
2187     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2188     if (pb) {
2189         // Create the repr for the image
2190         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2191         repr->setAttribute("xlink:href", filename);
2192         repr->setAttribute("sodipodi:absref", filepath);
2193         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2194         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2196         // Write transform
2197         gchar c[256];
2198         if (sp_svg_transform_write(c, 256, t)) {
2199             repr->setAttribute("transform", c);
2200         }
2202         // add the new repr to the parent
2203         parent->appendChild(repr);
2205         // move to the saved position
2206         repr->setPosition(pos > 0 ? pos + 1 : 1);
2208         // Set selection to the new image
2209         selection->clear();
2210         selection->add(repr);
2212         // Clean up
2213         Inkscape::GC::release(repr);
2214         gdk_pixbuf_unref (pb);
2216         // Complete undoable transaction
2217         sp_document_done (document);
2218     }
2220     g_free (filename);
2221     g_free (filepath);
2225 /*
2226   Local Variables:
2227   mode:c++
2228   c-file-style:"stroustrup"
2229   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2230   indent-tabs-mode:nil
2231   fill-column:99
2232   End:
2233 */
2234 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :