Code

turns out, all these synthesize_events were not necessary at all - they just fired...
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "sp-marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-flowtext.h"
39 #include "sp-flowregion.h"
40 #include "text-editing.h"
41 #include "text-context.h"
42 #include "dropper-context.h"
43 #include <glibmm/i18n.h>
44 #include "libnr/nr-matrix-rotate-ops.h"
45 #include "libnr/nr-matrix-translate-ops.h"
46 #include "libnr/nr-rotate-fns.h"
47 #include "libnr/nr-scale-ops.h"
48 #include "libnr/nr-scale-translate-ops.h"
49 #include "libnr/nr-translate-matrix-ops.h"
50 #include "libnr/nr-translate-scale-ops.h"
51 #include "xml/repr.h"
52 #include "style.h"
53 #include "document-private.h"
54 #include "sp-gradient.h"
55 #include "sp-gradient-reference.h"
56 #include "sp-linear-gradient-fns.h"
57 #include "sp-pattern.h"
58 #include "sp-radial-gradient-fns.h"
59 #include "sp-namedview.h"
60 #include "prefs-utils.h"
61 #include "sp-offset.h"
62 #include "sp-clippath.h"
63 #include "sp-mask.h"
64 #include "file.h"
65 #include "layer-fns.h"
66 #include "context-fns.h"
67 #include <map>
68 using NR::X;
69 using NR::Y;
71 #include "selection-chemistry.h"
73 /* fixme: find a better place */
74 GSList *clipboard = NULL;
75 GSList *defs_clipboard = NULL;
76 SPCSSAttr *style_clipboard = NULL;
77 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
79 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
81 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
82 {
83     Inkscape::XML::Node *copy = repr->duplicate();
85     // copy complete inherited style
86     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
87     sp_repr_css_set(copy, css, "style");
88     sp_repr_css_attr_unref(css);
90     // write the complete accummulated transform passed to us
91     // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
92     gchar affinestr[80];
93     if (sp_svg_transform_write(affinestr, 79, full_t)) {
94         copy->setAttribute("transform", affinestr);
95     } else {
96         copy->setAttribute("transform", NULL);
97     }
99     *clip = g_slist_prepend(*clip, copy);
102 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
105     // Copy stuff referenced by all items to defs_clip:
106     if (defs_clip) {
107         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
108             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
109         }
110         *defs_clip = g_slist_reverse(*defs_clip);
111     }
113     // Store style:
114     if (style_clip) {
115         SPItem *item = SP_ITEM (items->data); // take from the first selected item
116         *style_clip = take_style_from_item (item);
117     }
119     if (clip) {
120         // Sort items:
121         GSList *sorted_items = g_slist_copy ((GSList *) items);
122         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
124         // Copy item reprs:
125         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
126             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
127         }
129         *clip = g_slist_reverse(*clip);
130         g_slist_free ((GSList *) sorted_items);
131     }
134 /**
135 Add gradients/patterns/markers referenced by copied objects to defs
136 */
137 void
138 paste_defs (GSList **defs_clip, SPDocument *doc)
140     if (!defs_clip)
141         return;
143     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
144         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
145         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
146         gchar const *id = repr->attribute("id");
147         if (!id || !doc->getObjectById(id)) {
148             Inkscape::XML::Node *copy = repr->duplicate();
149             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
150             Inkscape::GC::release(copy);
151         }
152     }
155 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
157     paste_defs (defs_clip, document);
159     GSList *copied = NULL;
160     // add objects to document
161     for (GSList *l = *clip; l != NULL; l = l->next) {
162         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
163         Inkscape::XML::Node *copy = repr->duplicate();
165         // premultiply the item transform by the accumulated parent transform in the paste layer
166         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
167         if (!local.test_identity()) {
168             gchar const *t_str = copy->attribute("transform");
169             NR::Matrix item_t (NR::identity());
170             if (t_str)
171                 sp_svg_transform_read(t_str, &item_t);
172             item_t *= local.inverse();
173             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
174             gchar affinestr[80];
175             if (sp_svg_transform_write(affinestr, 79, item_t)) {
176                 copy->setAttribute("transform", affinestr);
177             } else {
178                 copy->setAttribute("transform", NULL);
179             }
180         }
182         parent->appendChildRepr(copy);
183         copied = g_slist_prepend(copied, copy);
184         Inkscape::GC::release(copy);
185     }
186     return copied;
189 void sp_selection_delete_impl(const GSList *items)
191     for (const GSList *i = items ; i ; i = i->next ) {
192         sp_object_ref((SPObject *)i->data, NULL);
193     }
194     for (const GSList *i = items; i != NULL; i = i->next) {
195         SPItem *item = (SPItem *) i->data;
196         SP_OBJECT(item)->deleteObject();
197         sp_object_unref((SPObject *)item, NULL);
198     }
202 void sp_selection_delete()
204     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
205     if (desktop == NULL) {
206         return;
207     }
209     if (tools_isactive (desktop, TOOLS_TEXT))
210         if (sp_text_delete_selection(desktop->event_context)) {
211             sp_document_done(SP_DT_DOCUMENT(desktop));
212             return;
213         }
215     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
217     // check if something is selected
218     if (selection->isEmpty()) {
219         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
220         return;
221     }
223     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
224     selection->clear();
225     sp_selection_delete_impl (selected);
226     g_slist_free ((GSList *) selected);
228     /* a tool may have set up private information in it's selection context
229      * that depends on desktop items.  I think the only sane way to deal with
230      * this currently is to reset the current tool, which will reset it's
231      * associated selection context.  For example: deleting an object
232      * while moving it around the canvas.
233      */
234     tools_switch ( desktop, tools_active ( desktop ) );
236     sp_document_done(SP_DT_DOCUMENT(desktop));
239 /* fixme: sequencing */
240 void sp_selection_duplicate()
242     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
243     if (desktop == NULL)
244         return;
246     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
248     // check if something is selected
249     if (selection->isEmpty()) {
250         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
251         return;
252     }
254     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
256     selection->clear();
258     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
259     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
261     GSList *newsel = NULL;
263     while (reprs) {
264         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
265         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
267         parent->appendChild(copy);
269         newsel = g_slist_prepend(newsel, copy);
270         reprs = g_slist_remove(reprs, reprs->data);
271         Inkscape::GC::release(copy);
272     }
274     sp_document_done(SP_DT_DOCUMENT(desktop));
276     selection->setReprList(newsel);
278     g_slist_free(newsel);
281 void sp_edit_clear_all()
283     SPDesktop *dt = SP_ACTIVE_DESKTOP;
284     if (!dt)
285         return;
287     SPDocument *doc = SP_DT_DOCUMENT(dt);
288     SP_DT_SELECTION(dt)->clear();
290     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
291     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
293     while (items) {
294         SP_OBJECT (items->data)->deleteObject();
295         items = g_slist_remove(items, items->data);
296     }
298     sp_document_done(doc);
301 GSList *
302 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
304     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
305         if (SP_IS_ITEM(child) &&
306             !desktop->isLayer(SP_ITEM(child)) &&
307             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
308             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
309             (!exclude || !g_slist_find ((GSList *) exclude, child))
310             )
311         {
312             list = g_slist_prepend (list, SP_ITEM(child));
313         }
315         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
316             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
317         }
318     }
320     return list;
323 void sp_edit_select_all_full (bool force_all_layers, bool invert)
325     SPDesktop *dt = SP_ACTIVE_DESKTOP;
326     if (!dt)
327         return;
329     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
331     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
333     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
334     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
335     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
337     GSList *items = NULL;
339     const GSList *exclude = NULL;
340     if (invert) {
341         exclude = selection->itemList();
342     }
344     if (force_all_layers)
345         inlayer = PREFS_SELECTION_ALL;
347     switch (inlayer) {
348         case PREFS_SELECTION_LAYER: {
349         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
350              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
351         return;
353         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
355         for (GSList *i = all_items; i; i = i->next) {
356             SPItem *item = SP_ITEM (i->data);
358             if (item && (!onlysensitive || !item->isLocked())) {
359                 if (!onlyvisible || !dt->itemIsHidden(item)) {
360                     if (!dt->isLayer(item)) {
361                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
362                             items = g_slist_prepend (items, item); // leave it in the list
363                         }
364                     }
365                 }
366             }
367         }
369         g_slist_free (all_items);
370             break;
371         }
372         case PREFS_SELECTION_LAYER_RECURSIVE: {
373             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
374             break;
375         }
376         default: {
377         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
378             break;
379     }
380     }
382     selection->setList (items);
384     if (items) {
385         g_slist_free (items);
386     }
389 void sp_edit_select_all ()
391     sp_edit_select_all_full (false, false);
394 void sp_edit_select_all_in_all_layers ()
396     sp_edit_select_all_full (true, false);
399 void sp_edit_invert ()
401     sp_edit_select_all_full (false, true);
404 void sp_edit_invert_in_all_layers ()
406     sp_edit_select_all_full (true, true);
409 void sp_selection_group()
411     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
412     if (desktop == NULL)
413         return;
415     SPDocument *document = SP_DT_DOCUMENT (desktop);
417     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
419     // Check if something is selected.
420     if (selection->isEmpty()) {
421         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
422         return;
423     }
425     GSList const *l = (GSList *) selection->reprList();
427     // Check if at least two objects are selected.
428     if (l->next == NULL) {
429         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
430         return;
431     }
433     GSList *p = g_slist_copy((GSList *) l);
435     selection->clear();
437     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
439     // Remember the position and parent of the topmost object.
440     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
441     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
443     Inkscape::XML::Node *group = sp_repr_new("svg:g");
445     while (p) {
446         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
448         if (current->parent() == topmost_parent) {
449             Inkscape::XML::Node *spnew = current->duplicate();
450             sp_repr_unparent(current);
451             group->appendChild(spnew);
452             Inkscape::GC::release(spnew);
453             topmost --; // only reduce count for those items deleted from topmost_parent
454         } else { // move it to topmost_parent first
455                 GSList *temp_clip = NULL;
457                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
458                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
459                 gchar const *t_str = current->attribute("transform");
460                 NR::Matrix item_t (NR::identity());
461                 if (t_str)
462                     sp_svg_transform_read(t_str, &item_t);
463                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
464                 //FIXME: when moving both clone and original from a transformed group (either by
465                 //grouping into another parent, or by cut/paste) the transform from the original's
466                 //parent becomes embedded into original itself, and this affects its clones. Fix
467                 //this by remembering the transform diffs we write to each item into an array and
468                 //then, if this is clone, looking up its original in that array and pre-multiplying
469                 //it by the inverse of that original's transform diff.
471                 sp_selection_copy_one (current, item_t, &temp_clip);
472                 sp_repr_unparent(current);
474                 // paste into topmost_parent (temporarily)
475                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
476                 if (temp_clip) g_slist_free (temp_clip);
477                 if (copied) { // if success,
478                     // take pasted object (now in topmost_parent)
479                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
480                     // make a copy
481                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
482                     // remove pasted
483                     sp_repr_unparent(in_topmost);
484                     // put its copy into group
485                     group->appendChild(spnew);
486                     Inkscape::GC::release(spnew);
487                     g_slist_free (copied);
488                 }
489         }
490         p = g_slist_remove(p, current);
491     }
493     // Add the new group to the topmost members' parent
494     topmost_parent->appendChild(group);
496     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
497     group->setPosition(topmost + 1);
499     sp_document_done(SP_DT_DOCUMENT(desktop));
501     selection->set(group);
502     Inkscape::GC::release(group);
505 void sp_selection_ungroup()
507     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
508     if (desktop == NULL)
509         return;
511     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
513     if (selection->isEmpty()) {
514         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
515         return;
516     }
518     GSList *items = g_slist_copy((GSList *) selection->itemList());
519     selection->clear();
521     // Get a copy of current selection.
522     GSList *new_select = NULL;
523     bool ungrouped = false;
524     for (GSList *i = items;
525          i != NULL;
526          i = i->next)
527     {
528         SPItem *group = (SPItem *) i->data;
530         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
531         if (!SP_IS_OBJECT(group)) {
532             continue;
533         }
535         /* We do not allow ungrouping <svg> etc. (lauris) */
536         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
537             // keep the non-group item in the new selection
538             selection->add(group);
539             continue;
540         }
542         GSList *children = NULL;
543         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
544         sp_item_group_ungroup(SP_GROUP(group), &children, false);
545         ungrouped = true;
546         // Add ungrouped items to the new selection.
547         new_select = g_slist_concat(new_select, children);
548     }
550     if (new_select) { // Set new selection.
551         selection->addList(new_select);
552         g_slist_free(new_select);
553     }
554     if (!ungrouped) {
555         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
556     }
558     g_slist_free(items);
560     sp_document_done(SP_DT_DOCUMENT(desktop));
563 static SPGroup *
564 sp_item_list_common_parent_group(const GSList *items)
566     if (!items) {
567         return NULL;
568     }
569     SPObject *parent = SP_OBJECT_PARENT(items->data);
570     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
571     if (!SP_IS_GROUP(parent)) {
572         return NULL;
573     }
574     for (items = items->next; items; items = items->next) {
575         if (SP_OBJECT_PARENT(items->data) != parent) {
576             return NULL;
577         }
578     }
580     return SP_GROUP(parent);
583 /** Finds out the minimum common bbox of the selected items
584  */
585 NR::Rect
586 enclose_items(const GSList *items)
588     g_assert(items != NULL);
590     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
592     for (GSList *i = items->next; i; i = i->next) {
593         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
594     }
596     return r;
599 SPObject *
600 prev_sibling(SPObject *child)
602     SPObject *parent = SP_OBJECT_PARENT(child);
603     if (!SP_IS_GROUP(parent)) {
604         return NULL;
605     }
606     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
607         if (i->next == child)
608             return i;
609     }
610     return NULL;
613 void
614 sp_selection_raise()
616     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
617     if (!desktop)
618         return;
620     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
622     GSList const *items = (GSList *) selection->itemList();
623     if (!items) {
624         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
625         return;
626     }
628     SPGroup const *group = sp_item_list_common_parent_group(items);
629     if (!group) {
630         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
631         return;
632     }
634     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
636     /* construct reverse-ordered list of selected children */
637     GSList *rev = g_slist_copy((GSList *) items);
638     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
640     // find out the common bbox of the selected items
641     NR::Rect selected = enclose_items(items);
643     // for all objects in the selection (starting from top)
644     while (rev) {
645         SPObject *child = SP_OBJECT(rev->data);
646         // for each selected object, find the next sibling
647         for (SPObject *newref = child->next; newref; newref = newref->next) {
648             // if the sibling is an item AND overlaps our selection,
649             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
650                 // AND if it's not one of our selected objects,
651                 if (!g_slist_find((GSList *) items, newref)) {
652                     // move the selected object after that sibling
653                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
654                 }
655                 break;
656             }
657         }
658         rev = g_slist_remove(rev, child);
659     }
661     sp_document_done(SP_DT_DOCUMENT(desktop));
664 void sp_selection_raise_to_top()
666     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
667     if (desktop == NULL)
668         return;
670     SPDocument *document = SP_DT_DOCUMENT(desktop);
671     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
673     if (selection->isEmpty()) {
674         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
675         return;
676     }
678     GSList const *items = (GSList *) selection->itemList();
680     SPGroup const *group = sp_item_list_common_parent_group(items);
681     if (!group) {
682         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
683         return;
684     }
686     GSList *rl = g_slist_copy((GSList *) selection->reprList());
687     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
689     for (GSList *l = rl; l != NULL; l = l->next) {
690         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
691         repr->setPosition(-1);
692     }
694     g_slist_free(rl);
696     sp_document_done(document);
699 void
700 sp_selection_lower()
702     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
703     if (desktop == NULL)
704         return;
706     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
708     GSList const *items = (GSList *) selection->itemList();
709     if (!items) {
710         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
711         return;
712     }
714     SPGroup const *group = sp_item_list_common_parent_group(items);
715     if (!group) {
716         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
717         return;
718     }
720     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
722     // find out the common bbox of the selected items
723     NR::Rect selected = enclose_items(items);
725     /* construct direct-ordered list of selected children */
726     GSList *rev = g_slist_copy((GSList *) items);
727     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
728     rev = g_slist_reverse(rev);
730     // for all objects in the selection (starting from top)
731     while (rev) {
732         SPObject *child = SP_OBJECT(rev->data);
733         // for each selected object, find the prev sibling
734         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
735             // if the sibling is an item AND overlaps our selection,
736             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
737                 // AND if it's not one of our selected objects,
738                 if (!g_slist_find((GSList *) items, newref)) {
739                     // move the selected object before that sibling
740                     SPObject *put_after = prev_sibling(newref);
741                     if (put_after)
742                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
743                     else
744                         SP_OBJECT_REPR(child)->setPosition(0);
745                 }
746                 break;
747             }
748         }
749         rev = g_slist_remove(rev, child);
750     }
752     sp_document_done(SP_DT_DOCUMENT(desktop));
756 void sp_selection_lower_to_bottom()
758     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
759     if (desktop == NULL)
760         return;
762     SPDocument *document = SP_DT_DOCUMENT(desktop);
763     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
765     if (selection->isEmpty()) {
766         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
767         return;
768     }
770     GSList const *items = (GSList *) selection->itemList();
772     SPGroup const *group = sp_item_list_common_parent_group(items);
773     if (!group) {
774         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
775         return;
776     }
778     GSList *rl;
779     rl = g_slist_copy((GSList *) selection->reprList());
780     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
781     rl = g_slist_reverse(rl);
783     for (GSList *l = rl; l != NULL; l = l->next) {
784         gint minpos;
785         SPObject *pp, *pc;
786         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
787         pp = document->getObjectByRepr(sp_repr_parent(repr));
788         minpos = 0;
789         g_assert(SP_IS_GROUP(pp));
790         pc = sp_object_first_child(pp);
791         while (!SP_IS_ITEM(pc)) {
792             minpos += 1;
793             pc = pc->next;
794         }
795         repr->setPosition(minpos);
796     }
798     g_slist_free(rl);
800     sp_document_done(document);
803 void
804 sp_undo(SPDesktop *desktop, SPDocument *)
806         if (!sp_document_undo(SP_DT_DOCUMENT(desktop)))
807             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
810 void
811 sp_redo(SPDesktop *desktop, SPDocument *)
813         if (!sp_document_redo(SP_DT_DOCUMENT(desktop)))
814             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
817 void sp_selection_cut()
819     sp_selection_copy();
820     sp_selection_delete();
823 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
825     SPGradient *ref = gradient;
827     while (ref) {
828         // climb up the refs, copying each one in the chain
829         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
830         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
832         ref = ref->ref->getObject();
833     }
836 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
838     SPPattern *ref = pattern;
840     while (ref) {
841         // climb up the refs, copying each one in the chain
842         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
843         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
845         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
846         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
847             if (!SP_IS_ITEM (child))
848                 continue;
849             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
850         }
852         ref = ref->ref->getObject();
853     }
856 void sp_copy_single (GSList **defs_clip, SPObject *thing)
858     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
859     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
863 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
865     SPItem *path = sp_textpath_get_path_item (tp);
866     if (!path)
867         return;
868     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
869         return;
870     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
871     *defs_clip = g_slist_prepend (*defs_clip, repr);
874 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
876     SPStyle *style = SP_OBJECT_STYLE (item);
878     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
879         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
880         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
881             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
882         if (SP_IS_PATTERN (server))
883             sp_copy_pattern (defs_clip, SP_PATTERN(server));
884     }
886     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
887         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
888         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
889             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
890         if (SP_IS_PATTERN (server))
891             sp_copy_pattern (defs_clip, SP_PATTERN(server));
892     }
894     if (SP_IS_SHAPE (item)) {
895         SPShape *shape = SP_SHAPE (item);
896         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
897             if (shape->marker[i]) {
898                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
899             }
900         }
901     }
903     if (SP_IS_TEXT_TEXTPATH (item)) {
904         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
905     }
907     if (item->clip_ref->getObject()) {
908         sp_copy_single (defs_clip, item->clip_ref->getObject());
909     }
911     if (item->mask_ref->getObject()) {
912         SPObject *mask = item->mask_ref->getObject();
913         sp_copy_single (defs_clip, mask);
914         // recurse into the mask for its gradients etc.
915         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
916             if (SP_IS_ITEM(o))
917                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
918         }
919     }
921     // recurse
922     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
923         if (SP_IS_ITEM(o))
924             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
925     }
928 /**
929  * \pre item != NULL
930  */
931 SPCSSAttr *
932 take_style_from_item (SPItem *item)
934     // write the complete cascaded style, context-free
935     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
936     if (css == NULL)
937         return NULL;
939     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
940         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
941         // if this is a text with exactly one tspan child, merge the style of that tspan as well
942         // If this is a group, merge the style of its topmost (last) child with style
943         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
944             if (SP_OBJECT_STYLE (last_element) != NULL) {
945                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
946                 if (temp) {
947                     sp_repr_css_merge (css, temp);
948                     sp_repr_css_attr_unref (temp);
949                 }
950                 break;
951             }
952         }
953     }
954     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
955         // do not copy text properties from non-text objects, it's confusing
956         css = sp_css_attr_unset_text (css);
957     }
959     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
960     double ex = NR::expansion(sp_item_i2doc_affine(item));
961     if (ex != 1.0) {
962         css = sp_css_attr_scale (css, ex);
963     }
965     return css;
969 void sp_selection_copy()
971     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
972     if (desktop == NULL)
973         return;
975     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
977     if (tools_isactive (desktop, TOOLS_DROPPER)) {
978         sp_dropper_context_copy(desktop->event_context);
979         return; // copied color under cursor, nothing else to do
980     }
982     // check if something is selected
983     if (selection->isEmpty()) {
984         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
985         return;
986     }
988     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
990     // 0. Copy text to system clipboard
991     // FIXME: for non-texts, put serialized XML as text to the clipboard;
992     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
993     Glib::ustring text;
994     if (tools_isactive (desktop, TOOLS_TEXT)) {
995         text = sp_text_get_selected_text(desktop->event_context);
996     }
998     if (text.empty()) {
999         guint texts = 0;
1000         for (GSList *i = (GSList *) items; i; i = i->next) {
1001             SPItem *item = SP_ITEM (i->data);
1002             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1003                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1004                     text += " ";
1005                 gchar *this_text = sp_te_get_string_multiline (item);
1006                 if (this_text) {
1007                     text += this_text;
1008                     g_free(this_text);
1009                 }
1010                 texts++;
1011             }
1012         }
1013     }
1014     if (!text.empty()) {
1015         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1016         refClipboard->set_text(text);
1017     }
1019     // clear old defs clipboard
1020     while (defs_clipboard) {
1021         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1022         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1023     }
1025     // clear style clipboard
1026     if (style_clipboard) {
1027         sp_repr_css_attr_unref (style_clipboard);
1028         style_clipboard = NULL;
1029     }
1031     //clear main clipboard
1032     while (clipboard) {
1033         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1034         clipboard = g_slist_remove(clipboard, clipboard->data);
1035     }
1037     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1039     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1040         SPStyle *const query = sp_style_new();
1041         if (sp_desktop_query_style_all (desktop, query)) {
1042             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1043             if (css != NULL) {
1044                 // clear style clipboard
1045                 if (style_clipboard) {
1046                     sp_repr_css_attr_unref (style_clipboard);
1047                     style_clipboard = NULL;
1048                 }
1049                 //sp_repr_css_print (css);
1050                 style_clipboard = css;
1051             }
1052         }
1053         g_free (query);
1054     }
1056     size_clipboard = selection->bounds();
1058     g_slist_free ((GSList *) items);
1061 void sp_selection_paste(bool in_place)
1063     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1065     if (desktop == NULL) {
1066         return;
1067     }
1069     SPDocument *document = SP_DT_DOCUMENT(desktop);
1071     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1072         return;
1073     }
1075     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1077     if (tools_isactive (desktop, TOOLS_TEXT)) {
1078         if (sp_text_paste_inline(desktop->event_context))
1079             return; // pasted from system clipboard into text, nothing else to do
1080     }
1082     // check if something is in the clipboard
1083     if (clipboard == NULL) {
1084         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1085         return;
1086     }
1088     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1089     // add pasted objects to selection
1090     selection->setReprList((GSList const *) copied);
1091     g_slist_free (copied);
1093     if (!in_place) {
1094         sp_document_ensure_up_to_date(document);
1096         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1098         /* Snap the offset of the new item(s) to the grid */
1099         /* FIXME: this gridsnap fiddling is a hack. */
1100         Inkscape::GridSnapper &s = desktop->namedview->grid_snapper;
1101         gdouble const curr_gridsnap = s.getDistance();
1102         s.setDistance(NR_HUGE);
1103         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1104         s.setDistance(curr_gridsnap);
1105         sp_selection_move_relative(selection, m);
1106     }
1108     sp_document_done(document);
1111 void sp_selection_paste_style()
1113     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1114     if (desktop == NULL) return;
1116     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1118     // check if something is in the clipboard
1119     if (clipboard == NULL) {
1120         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1121         return;
1122     }
1124     // check if something is selected
1125     if (selection->isEmpty()) {
1126         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1127         return;
1128     }
1130     paste_defs (&defs_clipboard, SP_DT_DOCUMENT(desktop));
1132     sp_desktop_set_style (desktop, style_clipboard);
1134     sp_document_done(SP_DT_DOCUMENT (desktop));
1137 void sp_selection_paste_size (bool apply_x, bool apply_y)
1139     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1140     if (desktop == NULL) return;
1142     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1144     // check if something is in the clipboard
1145     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1146         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1147         return;
1148     }
1150     // check if something is selected
1151     if (selection->isEmpty()) {
1152         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1153         return;
1154     }
1156     NR::Rect current = selection->bounds();
1157     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1158         return;
1159     }
1161     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1162     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1164     sp_selection_scale_relative (selection, current.midpoint(), 
1165                                  NR::scale(
1166                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1167                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1169     sp_document_done(SP_DT_DOCUMENT (desktop));
1172 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1174     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1175     if (desktop == NULL) return;
1177     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1179     // check if something is in the clipboard
1180     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1181         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1182         return;
1183     }
1185     // check if something is selected
1186     if (selection->isEmpty()) {
1187         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1188         return;
1189     }
1191     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1192         SPItem *item = SP_ITEM(l->data);
1194         NR::Rect current = sp_item_bbox_desktop(item);
1195         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1196             continue;
1197         }
1199         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1200         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1202         sp_item_scale_rel (item,
1203                                  NR::scale(
1204                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1205                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1207     }
1209     sp_document_done(SP_DT_DOCUMENT (desktop));
1212 void sp_selection_to_next_layer ()
1214     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1216     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
1218     // check if something is selected
1219     if (selection->isEmpty()) {
1220         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1221         return;
1222     }
1224     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1226     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1227     if (next) {
1228         GSList *temp_clip = NULL;
1229         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1230         sp_selection_delete_impl (items);
1231         GSList *copied = sp_selection_paste_impl (SP_DT_DOCUMENT (dt), next, &temp_clip, NULL);
1232         selection->setReprList((GSList const *) copied);
1233         g_slist_free (copied);
1234         if (temp_clip) g_slist_free (temp_clip);
1235         dt->setCurrentLayer(next);
1236         sp_document_done(SP_DT_DOCUMENT (dt));
1237     } else {
1238         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1239     }
1241     g_slist_free ((GSList *) items);
1244 void sp_selection_to_prev_layer ()
1246     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1248     Inkscape::Selection *selection = SP_DT_SELECTION(dt);
1250     // check if something is selected
1251     if (selection->isEmpty()) {
1252         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1253         return;
1254     }
1256     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1258     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1259     if (next) {
1260         GSList *temp_clip = NULL;
1261         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1262         sp_selection_delete_impl (items);
1263         GSList *copied = sp_selection_paste_impl (SP_DT_DOCUMENT (dt), next, &temp_clip, NULL);
1264         selection->setReprList((GSList const *) copied);
1265         g_slist_free (copied);
1266         if (temp_clip) g_slist_free (temp_clip);
1267         dt->setCurrentLayer(next);
1268         sp_document_done(SP_DT_DOCUMENT (dt));
1269     } else {
1270         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1271     }
1273     g_slist_free ((GSList *) items);
1276 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1277 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1278 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1279 that case, items are already in the new position, but the repr is in the old, and this function
1280 then simply updates the repr from item->transform.
1281  */
1282 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1284     if (selection->isEmpty())
1285         return;
1287     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1288         SPItem *item = SP_ITEM(l->data);
1290         NR::Point old_center(0,0);
1291         if (set_i2d && item->isCenterSet())
1292             old_center = item->getCenter();
1294 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1295          At the time of writing, this is the only place to re-enable. */
1296         sp_item_update_cns(*item, selection->desktop());
1297 #endif
1299         // we're moving both a clone and its original
1300         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1301         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)))) ));
1302         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // only the first frame so far
1303         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1305         // "clones are unmoved when original is moved" preference
1306         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1307         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1308         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1310         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1311         // transform of its original and respond to it itself. Without this, a clone is doubly
1312         // transformed, very unintuitive.
1313       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1314       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1315       // Same for linked offset if we are also moving its source: do not move it.
1316         if (transform_textpath_with_path || transform_offset_with_source) {
1317                 // restore item->transform field from the repr, in case it was changed by seltrans
1318             sp_object_read_attr (SP_OBJECT (item), "transform");
1320         } else if (transform_flowtext_with_frame) {
1321             // apply the inverse of the region's transform to the <use> so that the flow remains
1322             // the same (even though the output itself gets transformed)
1323             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1324                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1325                     continue;
1326                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1327                     if (!SP_IS_USE(use)) continue;
1328                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1329                 }
1330             }
1331         } else if (transform_clone_with_original) {
1332             // We are transforming a clone along with its original. The below matrix juggling is
1333             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1334             // transform and its move compensation are both cancelled out.
1336             // restore item->transform field from the repr, in case it was changed by seltrans
1337             sp_object_read_attr (SP_OBJECT (item), "transform");
1339             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1340             NR::Matrix t = matrix_to_desktop (matrix_from_desktop (affine, item), item);
1341             NR::Matrix t_inv = matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item);
1342             NR::Matrix result = t_inv * item->transform * t;
1344             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1345                 // we need to cancel out the move compensation, too
1347                 // find out the clone move, same as in sp_use_move_compensate
1348                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1349                 NR::Matrix clone_move = parent.inverse() * t * parent;
1351                 if (prefs_parallel) {
1352                     NR::Matrix move = result * clone_move * t_inv;
1353                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1355                 } else if (prefs_unmoved) {
1356                     if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1357                         clone_move = NR::identity();
1358                     NR::Matrix move = result * clone_move;
1359                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1360                 }
1362             } else {
1363                 // just apply the result
1364                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &result);
1365             }
1367         } else {
1368             if (set_i2d) {
1369                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1370             }
1371             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1372         }
1374         // if we're moving the actual object, not just updating the repr, we can transform the
1375         // center by the same matrix (only necessary for non-translations)
1376         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1377             item->setCenter(old_center * affine);
1378             SP_OBJECT(item)->updateRepr();
1379         }
1380     }
1383 void sp_selection_remove_transform()
1385     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1386     if (desktop == NULL)
1387         return;
1389     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1391     GSList const *l = (GSList *) selection->reprList();
1392     while (l != NULL) {
1393         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1394         l = l->next;
1395     }
1397     sp_document_done(SP_DT_DOCUMENT(desktop));
1400 void
1401 sp_selection_scale_absolute(Inkscape::Selection *selection,
1402                             double const x0, double const x1,
1403                             double const y0, double const y1)
1405     if (selection->isEmpty())
1406         return;
1408     NR::Rect const bbox(selection->bounds());
1409     if (bbox.isEmpty()) {
1410         return;
1411     }
1413     NR::translate const p2o(-bbox.min());
1415     NR::scale const newSize(x1 - x0,
1416                             y1 - y0);
1417     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1418     NR::translate const o2n(x0, y0);
1419     NR::Matrix const final( p2o * scale * o2n );
1421     sp_selection_apply_affine(selection, final);
1425 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1427     if (selection->isEmpty())
1428         return;
1430     NR::Rect const bbox(selection->bounds());
1432     if (bbox.isEmpty()) {
1433         return;
1434     }
1436     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1437     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1438          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1439     {
1440         return;
1441     }
1443     NR::translate const n2d(-align);
1444     NR::translate const d2n(align);
1445     NR::Matrix const final( n2d * scale * d2n );
1446     sp_selection_apply_affine(selection, final);
1449 void
1450 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1452     NR::translate const d2n(center);
1453     NR::translate const n2d(-center);
1454     NR::rotate const rotate(rotate_degrees(angle_degrees));
1455     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1456     sp_selection_apply_affine(selection, final);
1459 void
1460 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1462     NR::translate const d2n(align);
1463     NR::translate const n2d(-align);
1464     NR::Matrix const skew(1, dy,
1465                           dx, 1,
1466                           0, 0);
1467     NR::Matrix const final( n2d * skew * d2n );
1468     sp_selection_apply_affine(selection, final);
1471 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1473     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1476 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1478     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1482 /**
1483  * \brief sp_selection_rotate_90
1484  *
1485  * This function rotates selected objects 90 degrees clockwise.
1486  *
1487  */
1489 void sp_selection_rotate_90_cw()
1491     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1493     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1495     if (selection->isEmpty())
1496         return;
1498     GSList const *l = selection->itemList();
1499     NR::rotate const rot_neg_90(NR::Point(0, -1));
1500     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1501         SPItem *item = SP_ITEM(l2->data);
1502         sp_item_rotate_rel(item, rot_neg_90);
1503     }
1505     sp_document_done(SP_DT_DOCUMENT(desktop));
1509 /**
1510  * \brief sp_selection_rotate_90_ccw
1511  *
1512  * This function rotates selected objects 90 degrees counter-clockwise.
1513  *
1514  */
1516 void sp_selection_rotate_90_ccw()
1518     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1520     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1522     if (selection->isEmpty())
1523         return;
1525     GSList const *l = selection->itemList();
1526     NR::rotate const rot_neg_90(NR::Point(0, 1));
1527     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1528         SPItem *item = SP_ITEM(l2->data);
1529         sp_item_rotate_rel(item, rot_neg_90);
1530     }
1532     sp_document_done(SP_DT_DOCUMENT(desktop));
1535 void
1536 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1538     if (selection->isEmpty())
1539         return;
1541     NR::Point center = selection->center();
1543     sp_selection_rotate_relative(selection, center, angle_degrees);
1545     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1546                            ( ( angle_degrees > 0 )
1547                              ? "selector:rotate:ccw"
1548                              : "selector:rotate:cw" ));
1551 /**
1552 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1553 */
1554 void
1555 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1557     if (selection->isEmpty())
1558         return;
1560     NR::Rect const bbox(selection->bounds());
1562     NR::Point center = selection->center();
1564     gdouble const zoom = selection->desktop()->current_zoom();
1565     gdouble const zmove = angle / zoom;
1566     gdouble const r = NR::L2(bbox.max() - center);
1568     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1570     sp_selection_rotate_relative(selection, center, zangle);
1572     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1573                            ( (angle > 0)
1574                              ? "selector:rotate:ccw"
1575                              : "selector:rotate:cw" ));
1578 void
1579 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1581     if (selection->isEmpty())
1582         return;
1584     NR::Rect const bbox(selection->bounds());
1585     NR::Point const center(bbox.midpoint());
1586     double const max_len = bbox.maxExtent();
1588     // you can't scale "do nizhe pola" (below zero)
1589     if ( max_len + grow <= 1e-3 ) {
1590         return;
1591     }
1593     double const times = 1.0 + grow / max_len;
1594     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1596     sp_document_maybe_done(SP_DT_DOCUMENT(selection->desktop()),
1597                            ( (grow > 0)
1598                              ? "selector:scale:larger"
1599                              : "selector:scale:smaller" ));
1602 void
1603 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1605     sp_selection_scale(selection,
1606                        grow_pixels / selection->desktop()->current_zoom());
1609 void
1610 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1612     if (selection->isEmpty())
1613         return;
1615     NR::Point const center(selection->bounds().midpoint());
1616     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1617     sp_document_done(SP_DT_DOCUMENT(selection->desktop()));
1620 void
1621 sp_selection_move(gdouble dx, gdouble dy)
1623     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1624     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1625     if (selection->isEmpty()) {
1626         return;
1627     }
1629     sp_selection_move_relative(selection, dx, dy);
1631     if (dx == 0) {
1632         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1633     } else if (dy == 0) {
1634         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1635     } else {
1636         sp_document_done(SP_DT_DOCUMENT(desktop));
1637     }
1640 void
1641 sp_selection_move_screen(gdouble dx, gdouble dy)
1643     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1645     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1646     if (selection->isEmpty()) {
1647         return;
1648     }
1650     // same as sp_selection_move but divide deltas by zoom factor
1651     gdouble const zoom = desktop->current_zoom();
1652     gdouble const zdx = dx / zoom;
1653     gdouble const zdy = dy / zoom;
1654     sp_selection_move_relative(selection, zdx, zdy);
1656     if (dx == 0) {
1657         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:vertical");
1658     } else if (dy == 0) {
1659         sp_document_maybe_done(SP_DT_DOCUMENT(desktop), "selector:move:horizontal");
1660     } else {
1661         sp_document_done(SP_DT_DOCUMENT(desktop));
1662     }
1665 namespace {
1667 template <typename D>
1668 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1669                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1671 template <typename D>
1672 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1673                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1675 struct Forward {
1676     typedef SPObject *Iterator;
1678     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1679     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1680     static void dispose(Iterator i) {}
1682     static SPObject *object(Iterator i) { return i; }
1683     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1684 };
1686 struct Reverse {
1687     typedef GSList *Iterator;
1689     static Iterator children(SPObject *o) {
1690         return make_list(o->firstChild(), NULL);
1691     }
1692     static Iterator siblings_after(SPObject *o) {
1693         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1694     }
1695     static void dispose(Iterator i) {
1696         g_slist_free(i);
1697     }
1699     static SPObject *object(Iterator i) {
1700         return reinterpret_cast<SPObject *>(i->data);
1701     }
1702     static Iterator next(Iterator i) { return i->next; }
1704 private:
1705     static GSList *make_list(SPObject *object, SPObject *limit) {
1706         GSList *list=NULL;
1707         while ( object != limit ) {
1708             list = g_slist_prepend(list, object);
1709             object = SP_OBJECT_NEXT(object);
1710         }
1711         return list;
1712     }
1713 };
1717 void
1718 sp_selection_item_next(void)
1720     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1721     g_return_if_fail(desktop != NULL);
1722     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1724     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1725     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1726     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1728     SPObject *root;
1729     if (PREFS_SELECTION_ALL != inlayer) {
1730         root = selection->activeContext();
1731     } else {
1732         root = desktop->currentRoot();
1733     }
1735     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1737     if (item) {
1738         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1739         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1740             scroll_to_show_item(desktop, item);
1741         }
1742     }
1745 void
1746 sp_selection_item_prev(void)
1748     SPDocument *document = SP_ACTIVE_DOCUMENT;
1749     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1750     g_return_if_fail(document != NULL);
1751     g_return_if_fail(desktop != NULL);
1752     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1754     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1755     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1756     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1758     SPObject *root;
1759     if (PREFS_SELECTION_ALL != inlayer) {
1760         root = selection->activeContext();
1761     } else {
1762         root = desktop->currentRoot();
1763     }
1765     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1767     if (item) {
1768         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1769         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1770             scroll_to_show_item(desktop, item);
1771         }
1772     }
1775 namespace {
1777 template <typename D>
1778 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1779                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1781     SPObject *current=root;
1782     while (items) {
1783         SPItem *item=SP_ITEM(items->data);
1784         if ( root->isAncestorOf(item) &&
1785              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1786         {
1787             current = item;
1788             break;
1789         }
1790         items = items->next;
1791     }
1793     GSList *path=NULL;
1794     while ( current != root ) {
1795         path = g_slist_prepend(path, current);
1796         current = SP_OBJECT_PARENT(current);
1797     }
1799     SPItem *next;
1800     // first, try from the current object
1801     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1802     g_slist_free(path);
1804     if (!next) { // if we ran out of objects, start over at the root
1805         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1806     }
1808     return next;
1811 template <typename D>
1812 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1813                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1815     typename D::Iterator children;
1816     typename D::Iterator iter;
1818     SPItem *found=NULL;
1820     if (path) {
1821         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1822         g_assert(SP_OBJECT_PARENT(object) == root);
1823         if (desktop->isLayer(object)) {
1824             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1825         }
1826         iter = children = D::siblings_after(object);
1827     } else {
1828         iter = children = D::children(root);
1829     }
1831     while ( iter && !found ) {
1832         SPObject *object=D::object(iter);
1833         if (desktop->isLayer(object)) {
1834             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1835                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1836             }
1837         } else if ( SP_IS_ITEM(object) &&
1838                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1839                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1840                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1841                     !desktop->isLayer(SP_ITEM(object)) )
1842         {
1843             found = SP_ITEM(object);
1844         }
1845         iter = D::next(iter);
1846     }
1848     D::dispose(children);
1850     return found;
1855 /**
1856  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1857  * \a item.
1858  */
1859 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1861     NR::Rect dbox = desktop->get_display_area();
1862     NR::Rect sbox = sp_item_bbox_desktop(item);
1864     if (dbox.contains(sbox) == false) {
1865         NR::Point const s_dt = sbox.midpoint();
1866         NR::Point const s_w = desktop->d2w(s_dt);
1867         NR::Point const d_dt = dbox.midpoint();
1868         NR::Point const d_w = desktop->d2w(d_dt);
1869         NR::Point const moved_w( d_w - s_w );
1870         gint const dx = (gint) moved_w[X];
1871         gint const dy = (gint) moved_w[Y];
1872         desktop->scroll_world(dx, dy);
1873     }
1877 void
1878 sp_selection_clone()
1880     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1881     if (desktop == NULL)
1882         return;
1884     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1886     // check if something is selected
1887     if (selection->isEmpty()) {
1888         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1889         return;
1890     }
1892     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1893   
1894     selection->clear();
1895   
1896     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1897     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1899     GSList *newsel = NULL;
1900  
1901     while (reprs) {
1902         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1903         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1905         Inkscape::XML::Node *clone = sp_repr_new("svg:use");
1906         sp_repr_set_attr(clone, "x", "0");
1907         sp_repr_set_attr(clone, "y", "0");
1908         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
1910         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
1911         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
1912         
1913         // add the new clone to the top of the original's parent
1914         parent->appendChild(clone);
1916         newsel = g_slist_prepend(newsel, clone);
1917         reprs = g_slist_remove(reprs, sel_repr);
1918         Inkscape::GC::release(clone);
1919     }
1920     
1921     sp_document_done(SP_DT_DOCUMENT(desktop));
1923     selection->setReprList(newsel);
1924  
1925     g_slist_free(newsel);
1928 void
1929 sp_selection_unlink()
1931     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1932     if (!desktop)
1933         return;
1935     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1937     if (selection->isEmpty()) {
1938         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
1939         return;
1940     }
1942     // Get a copy of current selection.
1943     GSList *new_select = NULL;
1944     bool unlinked = false;
1945     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1946          items != NULL;
1947          items = items->next)
1948     {
1949         SPItem *use = (SPItem *) items->data;
1951         if (!SP_IS_USE(use)) {
1952             // keep the non-yse item in the new selection
1953             new_select = g_slist_prepend(new_select, use);
1954             continue;
1955         }
1957         SPItem *unlink = sp_use_unlink(SP_USE(use));
1958         unlinked = true;
1959         // Add ungrouped items to the new selection.
1960         new_select = g_slist_prepend(new_select, unlink);
1961     }
1963     if (new_select) { // set new selection
1964         selection->clear();
1965         selection->setList(new_select);
1966         g_slist_free(new_select);
1967     }
1968     if (!unlinked) {
1969         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1970     }
1972     sp_document_done(SP_DT_DOCUMENT(desktop));
1975 void
1976 sp_select_clone_original()
1978     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1979     if (desktop == NULL)
1980         return;
1982     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
1984     SPItem *item = selection->singleItem();
1986     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.");
1988     // Check if other than two objects are selected
1989     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
1990         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
1991         return;
1992     }
1994     SPItem *original = NULL;
1995     if (SP_IS_USE(item)) {
1996         original = sp_use_get_original (SP_USE(item));
1997     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
1998         original = sp_offset_get_source (SP_OFFSET(item));
1999     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2000         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2001     } else if (SP_IS_FLOWTEXT(item)) {
2002         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2003     } else { // it's an object that we don't know what to do with
2004         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2005         return;
2006     }
2008     if (!original) {
2009         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2010         return;
2011     }
2013     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2014         if (SP_IS_DEFS (o)) {
2015             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2016             return;
2017         }
2018     }
2020     if (original) {
2021         selection->clear();
2022         selection->set(original);
2023         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2024             scroll_to_show_item(desktop, original);
2025         }
2026     }
2029 void
2030 sp_selection_tile(bool apply)
2032     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2033     if (desktop == NULL)
2034         return;
2036     SPDocument *document = SP_DT_DOCUMENT(desktop);
2038     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2040     // check if something is selected
2041     if (selection->isEmpty()) {
2042         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2043         return;
2044     }
2046     sp_document_ensure_up_to_date(document);
2047     NR::Rect r = selection->bounds();
2048     if (r.isEmpty()) {
2049         return;
2050     }
2052     // calculate the transform to be applied to objects to move them to 0,0
2053     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2054     move_p[NR::Y] = -move_p[NR::Y];
2055     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2057     GSList *items = g_slist_copy((GSList *) selection->itemList());
2059     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2061     // bottommost object, after sorting
2062     SPObject *parent = SP_OBJECT_PARENT (items->data);
2064     // remember the position of the first item
2065     gint pos = SP_OBJECT_REPR (items->data)->position();
2067     // create a list of duplicates
2068     GSList *repr_copies = NULL;
2069     for (GSList *i = items; i != NULL; i = i->next) {
2070         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2071         repr_copies = g_slist_prepend (repr_copies, dup);
2072     }
2074     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2076     if (apply) {
2077         // delete objects so that their clones don't get alerted; this object will be restored shortly
2078         for (GSList *i = items; i != NULL; i = i->next) {
2079             SPObject *item = SP_OBJECT (i->data);
2080             item->deleteObject (false);
2081         }
2082     }
2084     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2085     // without disturbing clones.
2086     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2087     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2088     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2090     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2091                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))), move);
2093     // restore compensation setting
2094     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2096     if (apply) {
2097         Inkscape::XML::Node *rect = sp_repr_new ("svg:rect");
2098         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2099         sp_repr_set_svg_double(rect, "width", bounds.extent(NR::X));
2100         sp_repr_set_svg_double(rect, "height", bounds.extent(NR::Y));
2101         sp_repr_set_svg_double(rect, "x", bounds.min()[NR::X]);
2102         sp_repr_set_svg_double(rect, "y", bounds.min()[NR::Y]);
2104         // restore parent and position
2105         SP_OBJECT_REPR (parent)->appendChild(rect);
2106         rect->setPosition(pos > 0 ? pos : 0);
2107         SPItem *rectangle = (SPItem *) SP_DT_DOCUMENT (desktop)->getObjectByRepr(rect);
2109         Inkscape::GC::release(rect);
2111         selection->clear();
2112         selection->set(rectangle);
2113     }
2115     g_slist_free (items);
2117     sp_document_done (document);
2120 void
2121 sp_selection_untile()
2123     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2124     if (desktop == NULL)
2125         return;
2127     SPDocument *document = SP_DT_DOCUMENT(desktop);
2129     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2131     // check if something is selected
2132     if (selection->isEmpty()) {
2133         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2134         return;
2135     }
2137     GSList *new_select = NULL;
2139     bool did = false;
2141     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2142          items != NULL;
2143          items = items->next) {
2145         SPItem *item = (SPItem *) items->data;
2147         SPStyle *style = SP_OBJECT_STYLE (item);
2149         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2150             continue;
2152         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2154         if (!SP_IS_PATTERN(server))
2155             continue;
2157         did = true;
2159         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2161         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2162         pat_transform *= item->transform;
2164         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2165             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2166             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2168            // FIXME: relink clones to the new canvas objects
2169            // use SPObject::setid when mental finishes it to steal ids of
2171             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2172             sp_document_ensure_up_to_date (document);
2174             NR::Matrix transform( i->transform * pat_transform );
2175             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2177             new_select = g_slist_prepend(new_select, i);
2178         }
2180         SPCSSAttr *css = sp_repr_css_attr_new ();
2181         sp_repr_css_set_property (css, "fill", "none");
2182         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2183     }
2185     if (!did) {
2186         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2187     } else {
2188         sp_document_done(SP_DT_DOCUMENT(desktop));
2189         selection->setList(new_select);
2190     }
2193 void
2194 sp_selection_create_bitmap_copy ()
2196     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2197     if (desktop == NULL)
2198         return;
2200     SPDocument *document = SP_DT_DOCUMENT(desktop);
2202     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2204     // check if something is selected
2205     if (selection->isEmpty()) {
2206         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2207         return;
2208     }
2210     // Get the bounding box of the selection
2211     NRRect bbox;
2212     sp_document_ensure_up_to_date (document);
2213     selection->bounds(&bbox);
2214     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2215         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2216     }
2218     // List of the items to show; all others will be hidden
2219     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2221     // Sort items so that the topmost comes last
2222     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2224     // Generate a random value from the current time (you may create bitmap from the same object(s)
2225     // multiple times, and this is done so that they don't clash)
2226     GTimeVal cu;
2227     g_get_current_time (&cu);
2228     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2230     // Create the filename
2231     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2232     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2233     // digits, and a few other chars, with "_"
2234     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2235     // Build the complete path by adding document->base if set
2236     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2238     //g_print ("%s\n", filepath);
2240     // Remember parent and z-order of the topmost one
2241     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2242     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2243     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2245     // Calculate resolution
2246     double res;
2247     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2248     if (0 < prefs_res) {
2249         // If it's given explicitly in prefs, take it
2250         res = prefs_res;
2251     } else {
2252         // Otherwise look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2253         int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 250);
2254         res = prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2255     }
2257     // The width and height of the bitmap in pixels
2258     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res);
2259     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res);
2261     // Find out if we have to run a filter
2262     const gchar *run = NULL;
2263     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2264     if (filter) {
2265         // filter command is given;
2266         // see if we have a parameter to pass to it
2267         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2268         if (param1) {
2269             if (param1[strlen(param1) - 1] == '%') {
2270                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2271                 gchar p1[256];
2272                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2273                 // the first param is always the image filename, the second is param1
2274                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2275             } else {
2276                 // otherwise pass the param1 unchanged
2277                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2278             }
2279         } else {
2280             // run without extra parameter
2281             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2282         }
2283     }
2285     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2286     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2287     NR::Matrix t = NR::scale (1/res, -1/res) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2289     // Do the export
2290     sp_export_png_file(document, filepath,
2291                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2292                    width, height,
2293                    (guint32) 0xffffff00,
2294                    NULL, NULL,
2295                    true,  /*bool force_overwrite,*/
2296                    items);
2298     g_slist_free (items);
2300     // Run filter, if any
2301     if (run) {
2302         g_print ("Running external filter: %s\n", run);
2303         system (run);
2304     }
2306     // Import the image back
2307     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2308     if (pb) {
2309         // Create the repr for the image
2310         Inkscape::XML::Node * repr = sp_repr_new ("svg:image");
2311         repr->setAttribute("xlink:href", filename);
2312         repr->setAttribute("sodipodi:absref", filepath);
2313         sp_repr_set_svg_double(repr, "width", gdk_pixbuf_get_width(pb));
2314         sp_repr_set_svg_double(repr, "height", gdk_pixbuf_get_height(pb));
2316         // Write transform
2317         gchar c[256];
2318         if (sp_svg_transform_write(c, 256, t)) {
2319             repr->setAttribute("transform", c);
2320         }
2322         // add the new repr to the parent
2323         parent->appendChild(repr);
2325         // move to the saved position
2326         repr->setPosition(pos > 0 ? pos + 1 : 1);
2328         // Set selection to the new image
2329         selection->clear();
2330         selection->add(repr);
2332         // Clean up
2333         Inkscape::GC::release(repr);
2334         gdk_pixbuf_unref (pb);
2336         // Complete undoable transaction
2337         sp_document_done (document);
2338     }
2340     g_free (filename);
2341     g_free (filepath);
2344 /**
2345  * \brief sp_selection_set_mask
2346  *
2347  * This function creates a mask or clipPath from selection
2348  * Two different modes:
2349  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2350  *       and is applied to current layer
2351  *  otherwise, topmost object is used as mask for other objects
2352  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2353  * 
2354  */
2355 void
2356 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2358     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2359     if (desktop == NULL)
2360         return;
2362     SPDocument *document = SP_DT_DOCUMENT(desktop);
2363     
2364     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2366     // check if something is selected
2367     bool is_empty = selection->isEmpty();
2368     if ( apply_to_layer && is_empty) {
2369         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create mask from."));
2370         return;
2371     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2372         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply mask to."));
2373         return;
2374     }
2375     
2376     sp_document_ensure_up_to_date(document);
2378     GSList *items = g_slist_copy((GSList *) selection->itemList());
2379     
2380     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2382     // create a list of duplicates
2383     GSList *mask_items = NULL;
2384     GSList *apply_to_items = NULL;
2385     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2386     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2387     
2388     if (apply_to_layer) {
2389         // all selected items are used for mask, which is applied to a layer
2390         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2392         for (GSList *i = items; i != NULL; i = i->next) {
2393             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2394             mask_items = g_slist_prepend (mask_items, dup);
2396             if (remove_original) {
2397                 SPObject *item = SP_OBJECT (i->data);
2398                 item->deleteObject (false);
2399             }
2400         }
2401     } else if (!topmost) {
2402         // topmost item is used as a mask, which is applied to other items in a selection
2403         GSList *i = items;
2404         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2405         mask_items = g_slist_prepend (mask_items, dup);
2407         if (remove_original) {
2408             SPObject *item = SP_OBJECT (i->data);
2409             item->deleteObject (false);
2410         }
2411         
2412         for (i = i->next; i != NULL; i = i->next) {
2413             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2414         }
2415     } else {
2416         GSList *i = NULL;
2417         for (i = items; NULL != i->next; i = i->next) {
2418             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2419         }
2421         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2422         mask_items = g_slist_prepend (mask_items, dup);
2424         if (remove_original) {
2425             SPObject *item = SP_OBJECT (i->data);
2426             item->deleteObject (false);
2427         }
2428     }
2429     
2430     g_slist_free (items);
2431     items = NULL;
2432             
2433     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2434     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2435         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2436         // inverted object transform should be applied to a mask object,
2437         // as mask is calculated in user space (after applying transform)
2438         NR::Matrix maskTransform (item->transform.inverse());
2440         GSList *mask_items_dup = NULL;
2441         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2442             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2443             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2444         }
2446         const gchar *mask_id = NULL;
2447         if (apply_clip_path) {
2448             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2449         } else {
2450             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2451         }
2453         g_slist_free (mask_items_dup);
2454         mask_items_dup = NULL;
2456         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2457     }
2459     g_slist_free (mask_items);
2460     g_slist_free (apply_to_items);
2462     sp_document_done (document);
2465 void sp_selection_unset_mask(bool apply_clip_path) {
2466     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2467     if (desktop == NULL)
2468         return;
2469     
2470     SPDocument *document = SP_DT_DOCUMENT(desktop);    
2471     Inkscape::Selection *selection = SP_DT_SELECTION(desktop);
2473     // check if something is selected
2474     if (selection->isEmpty()) {
2475         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove mask from."));
2476         return;
2477     }
2478     
2479     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2480     sp_document_ensure_up_to_date(document);
2482     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2483     std::map<SPObject*,SPItem*> referenced_objects;
2484     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2485         if (remove_original) {
2486             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2487             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2488             Inkscape::URIReference *uri_ref = NULL;
2489         
2490             if (apply_clip_path) {
2491                 uri_ref = item->clip_ref;
2492             } else {
2493                 uri_ref = item->mask_ref;
2494             }
2496             // collect distinct mask object (and associate with item to apply transform)
2497             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2498                 referenced_objects[uri_ref->getObject()] = item;
2499             }
2500         }
2502         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2503     }
2505     // restore mask objects into a document
2506     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2507         SPObject *obj = (*it).first;
2508         GSList *items_to_move = NULL;
2509         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2510             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2511             items_to_move = g_slist_prepend (items_to_move, copy);
2512         }
2514         if (!obj->isReferenced()) {
2515             // delete from defs if no other object references this mask
2516             obj->deleteObject(false);
2517         }
2519         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2520             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr((Inkscape::XML::Node *)i->data));
2521             selection->add((Inkscape::XML::Node *)i->data);
2523             // transform mask, so it is moved the same spot there mask was applied
2524             NR::Matrix transform (item->transform);
2525             transform *= (*it).second->transform;
2526             sp_item_write_transform(item, SP_OBJECT_REPR(item), transform);
2527         }
2529         g_slist_free (items_to_move);
2530     }
2532     sp_document_done (document);
2535 /*
2536   Local Variables:
2537   mode:c++
2538   c-file-style:"stroustrup"
2539   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2540   indent-tabs-mode:nil
2541   fill-column:99
2542   End:
2543 */
2544 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :