Code

apply John Cliff's patch [ 1743843 ] Create Marker from Selection Menu Item
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-tref.h"
39 #include "sp-flowtext.h"
40 #include "sp-flowregion.h"
41 #include "text-editing.h"
42 #include "text-context.h"
43 #include "connector-context.h"
44 #include "sp-path.h"
45 #include "sp-conn-end.h"
46 #include "dropper-context.h"
47 #include <glibmm/i18n.h>
48 #include "libnr/nr-matrix-rotate-ops.h"
49 #include "libnr/nr-matrix-translate-ops.h"
50 #include "libnr/nr-rotate-fns.h"
51 #include "libnr/nr-scale-ops.h"
52 #include "libnr/nr-scale-translate-ops.h"
53 #include "libnr/nr-translate-matrix-ops.h"
54 #include "libnr/nr-translate-scale-ops.h"
55 #include "xml/repr.h"
56 #include "style.h"
57 #include "document-private.h"
58 #include "sp-gradient.h"
59 #include "sp-gradient-reference.h"
60 #include "sp-linear-gradient-fns.h"
61 #include "sp-pattern.h"
62 #include "sp-radial-gradient-fns.h"
63 #include "sp-namedview.h"
64 #include "prefs-utils.h"
65 #include "sp-offset.h"
66 #include "sp-clippath.h"
67 #include "sp-mask.h"
68 #include "file.h"
69 #include "helper/png-write.h"
70 #include "layer-fns.h"
71 #include "context-fns.h"
72 #include <map>
73 #include "helper/units.h"
74 #include "sp-item.h"
75 #include "unit-constants.h"
76 #include "xml/simple-document.h"
77 #include "sp-filter-reference.h"
79 using NR::X;
80 using NR::Y;
82 #include "selection-chemistry.h"
84 /* fixme: find a better place */
85 Inkscape::XML::Document *clipboard_document = NULL;
86 GSList *clipboard = NULL;
87 GSList *defs_clipboard = NULL;
88 SPCSSAttr *style_clipboard = NULL;
89 NR::Maybe<NR::Rect> size_clipboard;
91 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc);
93 /**
94  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
95  * then prepends the copy to 'clip'.
96  */
97 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
98 {
99     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
101     // copy complete inherited style
102     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
103     sp_repr_css_set(copy, css, "style");
104     sp_repr_css_attr_unref(css);
106     // write the complete accumulated transform passed to us
107     // (we're dealing with unattached repr, so we write to its attr 
108     // instead of using sp_item_set_transform)
109     gchar *affinestr=sp_svg_transform_write(full_t);
110     copy->setAttribute("transform", affinestr);
111     g_free(affinestr);
113     *clip = g_slist_prepend(*clip, copy);
116 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
119     // Copy stuff referenced by all items to defs_clip:
120     if (defs_clip) {
121         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
122             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
123         }
124         *defs_clip = g_slist_reverse(*defs_clip);
125     }
127     // Store style:
128     if (style_clip) {
129         SPItem *item = SP_ITEM (items->data); // take from the first selected item
130         *style_clip = take_style_from_item (item);
131     }
133     if (clip) {
134         // Sort items:
135         GSList *sorted_items = g_slist_copy ((GSList *) items);
136         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
138         // Copy item reprs:
139         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
140             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
141         }
143         *clip = g_slist_reverse(*clip);
144         g_slist_free ((GSList *) sorted_items);
145     }
148 /**
149  * Add gradients/patterns/markers referenced by copied objects to defs.
150  * Iterates through 'defs_clip', and for each item it adds the data
151  * repr into the global defs.
152  */
153 void
154 paste_defs (GSList **defs_clip, SPDocument *doc)
156     if (!defs_clip)
157         return;
159     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
160         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
161         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
162         gchar const *id = repr->attribute("id");
163         if (!id || !doc->getObjectById(id)) {
164             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
165             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
166             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
167             Inkscape::GC::release(copy);
168         }
169     }
172 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
174     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
175     paste_defs (defs_clip, doc);
177     GSList *copied = NULL;
178     // add objects to document
179     for (GSList *l = *clip; l != NULL; l = l->next) {
180         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
181         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
183         // premultiply the item transform by the accumulated parent transform in the paste layer
184         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
185         if (!local.test_identity()) {
186             gchar const *t_str = copy->attribute("transform");
187             NR::Matrix item_t (NR::identity());
188             if (t_str)
189                 sp_svg_transform_read(t_str, &item_t);
190             item_t *= local.inverse();
191             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
192             gchar *affinestr=sp_svg_transform_write(item_t);
193             copy->setAttribute("transform", affinestr);
194             g_free(affinestr);
195         }
197         parent->appendChildRepr(copy);
198         copied = g_slist_prepend(copied, copy);
199         Inkscape::GC::release(copy);
200     }
201     return copied;
204 void sp_selection_delete_impl(const GSList *items)
206     for (const GSList *i = items ; i ; i = i->next ) {
207         sp_object_ref((SPObject *)i->data, NULL);
208     }
209     for (const GSList *i = items; i != NULL; i = i->next) {
210         SPItem *item = (SPItem *) i->data;
211         SP_OBJECT(item)->deleteObject();
212         sp_object_unref((SPObject *)item, NULL);
213     }
217 void sp_selection_delete()
219     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
220     if (desktop == NULL) {
221         return;
222     }
224     if (tools_isactive (desktop, TOOLS_TEXT))
225         if (sp_text_delete_selection(desktop->event_context)) {
226             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
227                              _("Delete text"));
228             return;
229         }
231     Inkscape::Selection *selection = sp_desktop_selection(desktop);
233     // check if something is selected
234     if (selection->isEmpty()) {
235         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
236         return;
237     }
239     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
240     selection->clear();
241     sp_selection_delete_impl (selected);
242     g_slist_free ((GSList *) selected);
244     /* a tool may have set up private information in it's selection context
245      * that depends on desktop items.  I think the only sane way to deal with
246      * this currently is to reset the current tool, which will reset it's
247      * associated selection context.  For example: deleting an object
248      * while moving it around the canvas.
249      */
250     tools_switch ( desktop, tools_active ( desktop ) );
252     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
253                      _("Delete"));
256 /* fixme: sequencing */
257 void sp_selection_duplicate()
259     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
260     if (desktop == NULL)
261         return;
263     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
264     Inkscape::Selection *selection = sp_desktop_selection(desktop);
266     // check if something is selected
267     if (selection->isEmpty()) {
268         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
269         return;
270     }
272     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
274     selection->clear();
276     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
277     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
279     GSList *newsel = NULL;
281     while (reprs) {
282         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
283         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
285         parent->appendChild(copy);
287         newsel = g_slist_prepend(newsel, copy);
288         reprs = g_slist_remove(reprs, reprs->data);
289         Inkscape::GC::release(copy);
290     }
292     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
293                      _("Duplicate"));
295     selection->setReprList(newsel);
297     g_slist_free(newsel);
300 void sp_edit_clear_all()
302     SPDesktop *dt = SP_ACTIVE_DESKTOP;
303     if (!dt)
304         return;
306     SPDocument *doc = sp_desktop_document(dt);
307     sp_desktop_selection(dt)->clear();
309     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
310     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
312     while (items) {
313         SP_OBJECT (items->data)->deleteObject();
314         items = g_slist_remove(items, items->data);
315     }
317     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
318                      _("Delete all"));
321 GSList *
322 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
324     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
325         if (SP_IS_ITEM(child) &&
326             !desktop->isLayer(SP_ITEM(child)) &&
327             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
328             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
329             (!exclude || !g_slist_find ((GSList *) exclude, child))
330             )
331         {
332             list = g_slist_prepend (list, SP_ITEM(child));
333         }
335         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
336             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
337         }
338     }
340     return list;
343 void sp_edit_select_all_full (bool force_all_layers, bool invert)
345     SPDesktop *dt = SP_ACTIVE_DESKTOP;
346     if (!dt)
347         return;
349     Inkscape::Selection *selection = sp_desktop_selection(dt);
351     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
353     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
354     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
355     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
357     GSList *items = NULL;
359     const GSList *exclude = NULL;
360     if (invert) {
361         exclude = selection->itemList();
362     }
364     if (force_all_layers)
365         inlayer = PREFS_SELECTION_ALL;
367     switch (inlayer) {
368         case PREFS_SELECTION_LAYER: {
369         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
370              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
371         return;
373         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
375         for (GSList *i = all_items; i; i = i->next) {
376             SPItem *item = SP_ITEM (i->data);
378             if (item && (!onlysensitive || !item->isLocked())) {
379                 if (!onlyvisible || !dt->itemIsHidden(item)) {
380                     if (!dt->isLayer(item)) {
381                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
382                             items = g_slist_prepend (items, item); // leave it in the list
383                         }
384                     }
385                 }
386             }
387         }
389         g_slist_free (all_items);
390             break;
391         }
392         case PREFS_SELECTION_LAYER_RECURSIVE: {
393             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
394             break;
395         }
396         default: {
397         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
398             break;
399     }
400     }
402     selection->setList (items);
404     if (items) {
405         g_slist_free (items);
406     }
409 void sp_edit_select_all ()
411     sp_edit_select_all_full (false, false);
414 void sp_edit_select_all_in_all_layers ()
416     sp_edit_select_all_full (true, false);
419 void sp_edit_invert ()
421     sp_edit_select_all_full (false, true);
424 void sp_edit_invert_in_all_layers ()
426     sp_edit_select_all_full (true, true);
429 void sp_selection_group()
431     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
432     if (desktop == NULL)
433         return;
435     SPDocument *doc = sp_desktop_document (desktop);
436     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
438     Inkscape::Selection *selection = sp_desktop_selection(desktop);
440     // Check if something is selected.
441     if (selection->isEmpty()) {
442         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
443         return;
444     }
446     GSList const *l = (GSList *) selection->reprList();
448     GSList *p = g_slist_copy((GSList *) l);
450     selection->clear();
452     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
454     // Remember the position and parent of the topmost object.
455     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
456     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
458     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
460     while (p) {
461         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
463         if (current->parent() == topmost_parent) {
464             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
465             sp_repr_unparent(current);
466             group->appendChild(spnew);
467             Inkscape::GC::release(spnew);
468             topmost --; // only reduce count for those items deleted from topmost_parent
469         } else { // move it to topmost_parent first
470                 GSList *temp_clip = NULL;
472                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
473                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
474                 gchar const *t_str = current->attribute("transform");
475                 NR::Matrix item_t (NR::identity());
476                 if (t_str)
477                     sp_svg_transform_read(t_str, &item_t);
478                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
479                 //FIXME: when moving both clone and original from a transformed group (either by
480                 //grouping into another parent, or by cut/paste) the transform from the original's
481                 //parent becomes embedded into original itself, and this affects its clones. Fix
482                 //this by remembering the transform diffs we write to each item into an array and
483                 //then, if this is clone, looking up its original in that array and pre-multiplying
484                 //it by the inverse of that original's transform diff.
486                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
487                 sp_repr_unparent(current);
489                 // paste into topmost_parent (temporarily)
490                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
491                 if (temp_clip) g_slist_free (temp_clip);
492                 if (copied) { // if success,
493                     // take pasted object (now in topmost_parent)
494                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
495                     // make a copy
496                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
497                     // remove pasted
498                     sp_repr_unparent(in_topmost);
499                     // put its copy into group
500                     group->appendChild(spnew);
501                     Inkscape::GC::release(spnew);
502                     g_slist_free (copied);
503                 }
504         }
505         p = g_slist_remove(p, current);
506     }
508     // Add the new group to the topmost members' parent
509     topmost_parent->appendChild(group);
511     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
512     group->setPosition(topmost + 1);
514     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
515                      _("Group"));
517     selection->set(group);
518     Inkscape::GC::release(group);
521 void sp_selection_ungroup()
523     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
524     if (desktop == NULL)
525         return;
527     Inkscape::Selection *selection = sp_desktop_selection(desktop);
529     if (selection->isEmpty()) {
530         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
531         return;
532     }
534     GSList *items = g_slist_copy((GSList *) selection->itemList());
535     selection->clear();
537     // Get a copy of current selection.
538     GSList *new_select = NULL;
539     bool ungrouped = false;
540     for (GSList *i = items;
541          i != NULL;
542          i = i->next)
543     {
544         SPItem *group = (SPItem *) i->data;
546         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
547         if (!SP_IS_OBJECT(group)) {
548             continue;
549         }
551         /* We do not allow ungrouping <svg> etc. (lauris) */
552         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
553             // keep the non-group item in the new selection
554             selection->add(group);
555             continue;
556         }
558         GSList *children = NULL;
559         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
560         sp_item_group_ungroup(SP_GROUP(group), &children, false);
561         ungrouped = true;
562         // Add ungrouped items to the new selection.
563         new_select = g_slist_concat(new_select, children);
564     }
566     if (new_select) { // Set new selection.
567         selection->addList(new_select);
568         g_slist_free(new_select);
569     }
570     if (!ungrouped) {
571         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
572     }
574     g_slist_free(items);
576     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
577                      _("Ungroup"));
580 static SPGroup *
581 sp_item_list_common_parent_group(const GSList *items)
583     if (!items) {
584         return NULL;
585     }
586     SPObject *parent = SP_OBJECT_PARENT(items->data);
587     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
588     if (!SP_IS_GROUP(parent)) {
589         return NULL;
590     }
591     for (items = items->next; items; items = items->next) {
592         if (SP_OBJECT_PARENT(items->data) != parent) {
593             return NULL;
594         }
595     }
597     return SP_GROUP(parent);
600 /** Finds out the minimum common bbox of the selected items
601  */
602 static NR::Maybe<NR::Rect>
603 enclose_items(const GSList *items)
605     g_assert(items != NULL);
607     NR::Maybe<NR::Rect> r = NR::Nothing();
608     for (GSList const *i = items; i; i = i->next) {
609         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
610     }
611     return r;
614 SPObject *
615 prev_sibling(SPObject *child)
617     SPObject *parent = SP_OBJECT_PARENT(child);
618     if (!SP_IS_GROUP(parent)) {
619         return NULL;
620     }
621     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
622         if (i->next == child)
623             return i;
624     }
625     return NULL;
628 void
629 sp_selection_raise()
631     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
632     if (!desktop)
633         return;
635     Inkscape::Selection *selection = sp_desktop_selection(desktop);
637     GSList const *items = (GSList *) selection->itemList();
638     if (!items) {
639         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
640         return;
641     }
643     SPGroup const *group = sp_item_list_common_parent_group(items);
644     if (!group) {
645         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
646         return;
647     }
649     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
651     /* construct reverse-ordered list of selected children */
652     GSList *rev = g_slist_copy((GSList *) items);
653     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
655     // find out the common bbox of the selected items
656     NR::Maybe<NR::Rect> selected = enclose_items(items);
658     // for all objects in the selection (starting from top)
659     if (selected) {
660         while (rev) {
661             SPObject *child = SP_OBJECT(rev->data);
662             // for each selected object, find the next sibling
663             for (SPObject *newref = child->next; newref; newref = newref->next) {
664                 // if the sibling is an item AND overlaps our selection,
665                 if (SP_IS_ITEM(newref)) {
666                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
667                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
668                         // AND if it's not one of our selected objects,
669                         if (!g_slist_find((GSList *) items, newref)) {
670                             // move the selected object after that sibling
671                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
672                         }
673                         break;
674                     }
675                 }
676             }
677             rev = g_slist_remove(rev, child);
678         }
679     } else {
680         g_slist_free(rev);
681     }
683     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
684                      _("Raise"));
687 void sp_selection_raise_to_top()
689     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
690     if (desktop == NULL)
691         return;
693     SPDocument *document = sp_desktop_document(desktop);
694     Inkscape::Selection *selection = sp_desktop_selection(desktop);
696     if (selection->isEmpty()) {
697         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
698         return;
699     }
701     GSList const *items = (GSList *) selection->itemList();
703     SPGroup const *group = sp_item_list_common_parent_group(items);
704     if (!group) {
705         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
706         return;
707     }
709     GSList *rl = g_slist_copy((GSList *) selection->reprList());
710     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
712     for (GSList *l = rl; l != NULL; l = l->next) {
713         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
714         repr->setPosition(-1);
715     }
717     g_slist_free(rl);
719     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
720                      _("Raise to top"));
723 void
724 sp_selection_lower()
726     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
727     if (desktop == NULL)
728         return;
730     Inkscape::Selection *selection = sp_desktop_selection(desktop);
732     GSList const *items = (GSList *) selection->itemList();
733     if (!items) {
734         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
735         return;
736     }
738     SPGroup const *group = sp_item_list_common_parent_group(items);
739     if (!group) {
740         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
741         return;
742     }
744     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
746     // find out the common bbox of the selected items
747     NR::Maybe<NR::Rect> selected = enclose_items(items);
749     /* construct direct-ordered list of selected children */
750     GSList *rev = g_slist_copy((GSList *) items);
751     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
752     rev = g_slist_reverse(rev);
754     // for all objects in the selection (starting from top)
755     if (selected) {
756         while (rev) {
757             SPObject *child = SP_OBJECT(rev->data);
758             // for each selected object, find the prev sibling
759             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
760                 // if the sibling is an item AND overlaps our selection,
761                 if (SP_IS_ITEM(newref)) {
762                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
763                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
764                         // AND if it's not one of our selected objects,
765                         if (!g_slist_find((GSList *) items, newref)) {
766                             // move the selected object before that sibling
767                             SPObject *put_after = prev_sibling(newref);
768                             if (put_after)
769                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
770                             else
771                                 SP_OBJECT_REPR(child)->setPosition(0);
772                         }
773                         break;
774                     }
775                 }
776             }
777             rev = g_slist_remove(rev, child);
778         }
779     } else {
780         g_slist_free(rev);
781     }
783     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
784                      _("Lower"));
787 void sp_selection_lower_to_bottom()
789     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
790     if (desktop == NULL)
791         return;
793     SPDocument *document = sp_desktop_document(desktop);
794     Inkscape::Selection *selection = sp_desktop_selection(desktop);
796     if (selection->isEmpty()) {
797         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
798         return;
799     }
801     GSList const *items = (GSList *) selection->itemList();
803     SPGroup const *group = sp_item_list_common_parent_group(items);
804     if (!group) {
805         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
806         return;
807     }
809     GSList *rl;
810     rl = g_slist_copy((GSList *) selection->reprList());
811     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
812     rl = g_slist_reverse(rl);
814     for (GSList *l = rl; l != NULL; l = l->next) {
815         gint minpos;
816         SPObject *pp, *pc;
817         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
818         pp = document->getObjectByRepr(sp_repr_parent(repr));
819         minpos = 0;
820         g_assert(SP_IS_GROUP(pp));
821         pc = sp_object_first_child(pp);
822         while (!SP_IS_ITEM(pc)) {
823             minpos += 1;
824             pc = pc->next;
825         }
826         repr->setPosition(minpos);
827     }
829     g_slist_free(rl);
831     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
832                      _("Lower to bottom"));
835 void
836 sp_undo(SPDesktop *desktop, SPDocument *)
838         if (!sp_document_undo(sp_desktop_document(desktop)))
839             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
842 void
843 sp_redo(SPDesktop *desktop, SPDocument *)
845         if (!sp_document_redo(sp_desktop_document(desktop)))
846             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
849 void sp_selection_cut()
851     sp_selection_copy();
852     sp_selection_delete();
855 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
857     SPGradient *ref = gradient;
859     while (ref) {
860         // climb up the refs, copying each one in the chain
861         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
862         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
864         ref = ref->ref->getObject();
865     }
868 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
870     SPPattern *ref = pattern;
872     while (ref) {
873         // climb up the refs, copying each one in the chain
874         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
875         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
877         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
878         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
879             if (!SP_IS_ITEM (child))
880                 continue;
881             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
882         }
884         ref = ref->ref->getObject();
885     }
888 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
890     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
891     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
895 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items, Inkscape::XML::Document* xml_doc)
897     SPItem *path = sp_textpath_get_path_item (tp);
898     if (!path)
899         return;
900     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
901         return;
902     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
903     *defs_clip = g_slist_prepend (*defs_clip, repr);
906 /**
907  * Copies things like patterns, markers, gradients, etc.
908  */
909 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc)
911     SPStyle *style = SP_OBJECT_STYLE (item);
913     if (style && (style->fill.isPaintserver())) {
914         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
915         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
916             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
917         if (SP_IS_PATTERN (server))
918             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
919     }
921     if (style && (style->stroke.isPaintserver())) {
922         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
923         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
924             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
925         if (SP_IS_PATTERN (server))
926             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
927     }
929     // For shapes, copy all of the shape's markers into defs_clip
930     if (SP_IS_SHAPE (item)) {
931         SPShape *shape = SP_SHAPE (item);
932         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
933             if (shape->marker[i]) {
934                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
935             }
936         }
938         // For shapes, also copy liveeffect if applicable
939         if (sp_shape_has_path_effect(shape)) {
940             sp_copy_single (defs_clip, SP_OBJECT(sp_shape_get_livepatheffectobject(shape)), xml_doc);
941         }
942     }
944     if (SP_IS_TEXT_TEXTPATH (item)) {
945         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
946     }
948     if (item->clip_ref->getObject()) {
949         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
950     }
952     if (item->mask_ref->getObject()) {
953         SPObject *mask = item->mask_ref->getObject();
954         sp_copy_single (defs_clip, mask, xml_doc);
955         // recurse into the mask for its gradients etc.
956         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
957             if (SP_IS_ITEM(o))
958                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
959         }
960     }
962     if (style->getFilter()) {
963         SPObject *filter = style->getFilter();
964         if (SP_IS_FILTER(filter)) {
965             sp_copy_single (defs_clip, filter, xml_doc);
966         }
967     }
969     // recurse
970     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
971         if (SP_IS_ITEM(o))
972             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
973     }
976 /**
977  * \pre item != NULL
978  */
979 SPCSSAttr *
980 take_style_from_item (SPItem *item)
982     // write the complete cascaded style, context-free
983     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
984     if (css == NULL)
985         return NULL;
987     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
988         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
989         // if this is a text with exactly one tspan child, merge the style of that tspan as well
990         // If this is a group, merge the style of its topmost (last) child with style
991         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
992             if (SP_OBJECT_STYLE (last_element) != NULL) {
993                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
994                 if (temp) {
995                     sp_repr_css_merge (css, temp);
996                     sp_repr_css_attr_unref (temp);
997                 }
998                 break;
999             }
1000         }
1001     }
1002     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
1003         // do not copy text properties from non-text objects, it's confusing
1004         css = sp_css_attr_unset_text (css);
1005     }
1007     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1008     double ex = NR::expansion(sp_item_i2doc_affine(item));
1009     if (ex != 1.0) {
1010         css = sp_css_attr_scale (css, ex);
1011     }
1013     return css;
1017 void sp_selection_copy()
1019     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1020     if (desktop == NULL)
1021         return;
1023     if (!clipboard_document) {
1024         clipboard_document = new Inkscape::XML::SimpleDocument();
1025     }
1027     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1029     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1030         sp_dropper_context_copy(desktop->event_context);
1031         return; // copied color under cursor, nothing else to do
1032     }
1034     // check if something is selected
1035     if (selection->isEmpty()) {
1036         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1037         return;
1038     }
1040     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1042     // 0. Copy text to system clipboard
1043     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1044     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1045     Glib::ustring text;
1046     if (tools_isactive (desktop, TOOLS_TEXT)) {
1047         text = sp_text_get_selected_text(desktop->event_context);
1048     }
1050     if (text.empty()) {
1051         guint texts = 0;
1052         for (GSList *i = (GSList *) items; i; i = i->next) {
1053             SPItem *item = SP_ITEM (i->data);
1054             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1055                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1056                     text += " ";
1057                 gchar *this_text = sp_te_get_string_multiline (item);
1058                 if (this_text) {
1059                     text += this_text;
1060                     g_free(this_text);
1061                 }
1062                 texts++;
1063             }
1064         }
1065     }
1066     if (!text.empty()) {
1067         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1068         refClipboard->set_text(text);
1069     }
1071     // clear old defs clipboard
1072     while (defs_clipboard) {
1073         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1074         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1075     }
1077     // clear style clipboard
1078     if (style_clipboard) {
1079         sp_repr_css_attr_unref (style_clipboard);
1080         style_clipboard = NULL;
1081     }
1083     //clear main clipboard
1084     while (clipboard) {
1085         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1086         clipboard = g_slist_remove(clipboard, clipboard->data);
1087     }
1089     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1091     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1092         SPStyle *const query = sp_style_new(SP_ACTIVE_DOCUMENT);
1093         if (sp_desktop_query_style_all (desktop, query)) {
1094             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1095             if (css != NULL) {
1096                 // clear style clipboard
1097                 if (style_clipboard) {
1098                     sp_repr_css_attr_unref (style_clipboard);
1099                     style_clipboard = NULL;
1100                 }
1101                 //sp_repr_css_print (css);
1102                 style_clipboard = css;
1103             }
1104         }
1105         sp_style_unref(query);
1106     }
1108     size_clipboard = selection->bounds();
1110     g_slist_free ((GSList *) items);
1113 void sp_selection_paste(bool in_place)
1115     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1117     if (desktop == NULL) {
1118         return;
1119     }
1121     SPDocument *document = sp_desktop_document(desktop);
1123     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1124         return;
1125     }
1127     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1129     if (tools_isactive (desktop, TOOLS_TEXT)) {
1130         if (sp_text_paste_inline(desktop->event_context))
1131             return; // pasted from system clipboard into text, nothing else to do
1132     }
1134     // check if something is in the clipboard
1135     if (clipboard == NULL) {
1136         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1137         return;
1138     }
1140     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1141     // add pasted objects to selection
1142     selection->setReprList((GSList const *) copied);
1143     g_slist_free (copied);
1145     if (!in_place) {
1146         sp_document_ensure_up_to_date(document);
1148         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1149         NR::Point m( desktop->point() );
1150         if (sel_bbox) {
1151             m -= sel_bbox->midpoint();
1152         }
1154         /* Snap the offset of the new item(s) to the grid */
1155         SnapManager &sm = desktop->namedview->snap_manager;
1156         SnapManager::SnapperList gs = sm.getGridSnappers();
1157         m = sm.freeSnapAlways(Inkscape::Snapper::SNAPPOINT_NODE, m, NULL, gs).getPoint();
1158         sp_selection_move_relative(selection, m);
1159     }
1161     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1162                      _("Paste"));
1165 void sp_selection_paste_style()
1167     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1168     if (desktop == NULL) return;
1170     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1172     // check if something is in the clipboard
1173     if (clipboard == NULL) {
1174         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1175         return;
1176     }
1178     // check if something is selected
1179     if (selection->isEmpty()) {
1180         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1181         return;
1182     }
1184     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1186     sp_desktop_set_style (desktop, style_clipboard);
1188     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1189                      _("Paste style"));
1192 void sp_selection_paste_livepatheffect()
1194     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1195     if (desktop == NULL) return;
1197     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1199     // check if something is in the clipboard
1200     if (clipboard == NULL) {
1201         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1202         return;
1203     }
1205     // check if something is selected
1206     if (selection->isEmpty()) {
1207         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste live path effect to."));
1208         return;
1209     }
1211     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1213     Inkscape::XML::Node *repr = (Inkscape::XML::Node *) clipboard->data;
1214     const char * effectstr = repr->attribute("inkscape:path-effect");
1215     if (!effectstr) {
1216         SP_ACTIVE_DESKTOP->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Clipboard does not contain a live path effect."));
1217         return;
1218     }
1220     for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1221         SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1222         if ( item && SP_IS_SHAPE(item) ) {
1223             Inkscape::XML::Node *selrepr = (Inkscape::XML::Node *) SP_OBJECT_REPR(item);
1224             selrepr->setAttribute("inkscape:path-effect", effectstr);
1226             // set inkscape:original-d for paths. the other shapes don't need this.
1227             if ( SP_IS_PATH(item) ) {
1228                 Inkscape::XML::Node *pathrepr = SP_OBJECT_REPR(item);
1229                 if ( ! pathrepr->attribute("inkscape:original-d") ) {
1230                     pathrepr->setAttribute("inkscape:original-d", pathrepr->attribute("d"));
1231                 }
1232             }
1233         }
1234     }
1236     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1237                      _("Paste live path effect"));
1240 void sp_selection_paste_size (bool apply_x, bool apply_y)
1242     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1243     if (desktop == NULL) return;
1245     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1247     // check if something is in the clipboard
1248     if (!size_clipboard) {
1249         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1250         return;
1251     }
1253     // check if something is selected
1254     if (selection->isEmpty()) {
1255         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1256         return;
1257     }
1259     NR::Maybe<NR::Rect> current = selection->bounds();
1260     if ( !current || current->isEmpty() ) {
1261         return;
1262     }
1264     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1265     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1267     sp_selection_scale_relative (selection, current->midpoint(),
1268                                  NR::scale(
1269                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1270                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1272     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1273                      _("Paste size"));
1276 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1278     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1279     if (desktop == NULL) return;
1281     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1283     // check if something is in the clipboard
1284     if ( !size_clipboard ) {
1285         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1286         return;
1287     }
1289     // check if something is selected
1290     if (selection->isEmpty()) {
1291         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1292         return;
1293     }
1295     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1296         SPItem *item = SP_ITEM(l->data);
1298         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1299         if ( !current || current->isEmpty() ) {
1300             continue;
1301         }
1303         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1304         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1306         sp_item_scale_rel (item,
1307                                  NR::scale(
1308                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1309                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1311     }
1313     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1314                      _("Paste size separately"));
1317 void sp_selection_to_next_layer ()
1319     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1321     Inkscape::Selection *selection = sp_desktop_selection(dt);
1323     // check if something is selected
1324     if (selection->isEmpty()) {
1325         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1326         return;
1327     }
1329     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1331     bool no_more = false; // Set to true, if no more layers above
1332     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1333     if (next) {
1334         GSList *temp_clip = NULL;
1335         sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1336         sp_selection_delete_impl (items);
1337         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1338         GSList *copied;
1339         if(next) {
1340             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1341         } else {
1342             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1343             no_more = true;
1344         }
1345         selection->setReprList((GSList const *) copied);
1346         g_slist_free (copied);
1347         if (temp_clip) g_slist_free (temp_clip);
1348         if (next) dt->setCurrentLayer(next);
1349         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1350                          _("Raise to next layer"));
1351     } else {
1352         no_more = true;
1353     }
1355     if (no_more) {
1356         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1357     }
1359     g_slist_free ((GSList *) items);
1362 void sp_selection_to_prev_layer ()
1364     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1366     Inkscape::Selection *selection = sp_desktop_selection(dt);
1368     // check if something is selected
1369     if (selection->isEmpty()) {
1370         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1371         return;
1372     }
1374     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1376     bool no_more = false; // Set to true, if no more layers below
1377     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1378     if (next) {
1379         GSList *temp_clip = NULL;
1380         sp_selection_copy_impl (items, &temp_clip, NULL, NULL, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1381         sp_selection_delete_impl (items);
1382         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1383         GSList *copied;
1384         if(next) {
1385             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1386         } else {
1387             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1388             no_more = true;
1389         }
1390         selection->setReprList((GSList const *) copied);
1391         g_slist_free (copied);
1392         if (temp_clip) g_slist_free (temp_clip);
1393         if (next) dt->setCurrentLayer(next);
1394         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1395                          _("Lower to previous layer"));
1396     } else {
1397         no_more = true;
1398     }
1400     if (no_more) {
1401         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1402     }
1404     g_slist_free ((GSList *) items);
1407 bool
1408 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1410     bool contains_original = false;
1411     
1412     bool is_use = SP_IS_USE(item);
1413     SPItem *item_use = item;
1414     SPItem *item_use_first = item;
1415     while (is_use && item_use && !contains_original)
1416     {
1417         item_use = sp_use_get_original (SP_USE(item_use));
1418         contains_original |= selection->includes(item_use);
1419         if (item_use == item_use_first)
1420             break;
1421         is_use = SP_IS_USE(item_use);
1422     }
1423     
1424     // If it's a tref, check whether the object containing the character
1425     // data is part of the selection
1426     if (!contains_original && SP_IS_TREF(item)) {
1427         contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1428     }
1429        
1430     return contains_original;
1434 bool
1435 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1437     bool clone_with_original = false;
1438     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1439         SPItem *item = SP_ITEM(l->data);
1440         clone_with_original |= selection_contains_original(item, selection);
1441         if (clone_with_original) 
1442             break;
1443     }
1444     return clone_with_original;
1448 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1449 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1450 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1451 that case, items are already in the new position, but the repr is in the old, and this function
1452 then simply updates the repr from item->transform.
1453  */
1454 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1456     if (selection->isEmpty())
1457         return;
1459     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1460         SPItem *item = SP_ITEM(l->data);
1462         NR::Point old_center(0,0);
1463         if (set_i2d && item->isCenterSet())
1464             old_center = item->getCenter();
1466 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1467          At the time of writing, this is the only place to re-enable. */
1468         sp_item_update_cns(*item, selection->desktop());
1469 #endif
1471         // we're moving both a clone and its original or any ancestor in clone chain?
1472         bool transform_clone_with_original = selection_contains_original(item, selection);
1473         // ...both a text-on-path and its path?
1474         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)))) ));
1475         // ...both a flowtext and its frame?
1476         bool transform_flowtext_with_frame = (SP_IS_FLOWTEXT(item) && selection->includes( SP_FLOWTEXT(item)->get_frame (NULL))); // (only the first frame is checked so far)
1477         // ...both an offset and its source?
1478         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1479        
1480         // If we're moving a connector, we want to detach it
1481         // from shapes that aren't part of the selection, but
1482         // leave it attached if they are
1483         if (cc_item_is_connector(item)) {
1484             SPItem *attItem[2];
1485             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1486             
1487             for (int n = 0; n < 2; ++n) {
1488                 if (!selection->includes(attItem[n])) {
1489                     sp_conn_end_detach(item, n);
1490                 }
1491             }
1492         }
1493         
1494         // "clones are unmoved when original is moved" preference
1495         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1496         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1497         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1499         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1500         // transform of its original and respond to it itself. Without this, a clone is doubly
1501         // transformed, very unintuitive.
1502       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1503       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1504       // Same for linked offset if we are also moving its source: do not move it.
1505         if (transform_textpath_with_path || transform_offset_with_source) {
1506                 // restore item->transform field from the repr, in case it was changed by seltrans
1507             sp_object_read_attr (SP_OBJECT (item), "transform");
1509         } else if (transform_flowtext_with_frame) {
1510             // apply the inverse of the region's transform to the <use> so that the flow remains
1511             // the same (even though the output itself gets transformed)
1512             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1513                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1514                     continue;
1515                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1516                     if (!SP_IS_USE(use)) continue;
1517                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1518                 }
1519             }
1520         } else if (transform_clone_with_original) {
1521             // We are transforming a clone along with its original. The below matrix juggling is
1522             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1523             // transform and its move compensation are both cancelled out.
1525             // restore item->transform field from the repr, in case it was changed by seltrans
1526             sp_object_read_attr (SP_OBJECT (item), "transform");
1528             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1529             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1530             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1531             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1532             NR::Matrix result = t_inv * item->transform * t;
1534             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1535                 // we need to cancel out the move compensation, too
1537                 // find out the clone move, same as in sp_use_move_compensate
1538                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1539                 NR::Matrix clone_move = parent.inverse() * t * parent;
1541                 if (prefs_parallel) {
1542                     NR::Matrix move = result * clone_move * t_inv;
1543                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1545                 } else if (prefs_unmoved) {
1546                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1547                     //    clone_move = NR::identity();
1548                     NR::Matrix move = result * clone_move;
1549                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1550                 }
1552             } else {
1553                 // just apply the result
1554                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1555             }
1557         } else {
1558             if (set_i2d) {
1559                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1560             }
1561             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1562         }
1564         // if we're moving the actual object, not just updating the repr, we can transform the
1565         // center by the same matrix (only necessary for non-translations)
1566         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1567             item->setCenter(old_center * affine);
1568             SP_OBJECT(item)->updateRepr();
1569         }
1570     }
1573 void sp_selection_remove_transform()
1575     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1576     if (desktop == NULL)
1577         return;
1579     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1581     GSList const *l = (GSList *) selection->reprList();
1582     while (l != NULL) {
1583         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1584         l = l->next;
1585     }
1587     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1588                      _("Remove transform"));
1591 void
1592 sp_selection_scale_absolute(Inkscape::Selection *selection,
1593                             double const x0, double const x1,
1594                             double const y0, double const y1)
1596     if (selection->isEmpty())
1597         return;
1599     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1600     if ( !bbox || bbox->isEmpty() ) {
1601         return;
1602     }
1604     NR::translate const p2o(-bbox->min());
1606     NR::scale const newSize(x1 - x0,
1607                             y1 - y0);
1608     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1609     NR::translate const o2n(x0, y0);
1610     NR::Matrix const final( p2o * scale * o2n );
1612     sp_selection_apply_affine(selection, final);
1616 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1618     if (selection->isEmpty())
1619         return;
1621     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1623     if ( !bbox || bbox->isEmpty() ) {
1624         return;
1625     }
1627     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1628     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1629          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1630     {
1631         return;
1632     }
1634     NR::translate const n2d(-align);
1635     NR::translate const d2n(align);
1636     NR::Matrix const final( n2d * scale * d2n );
1637     sp_selection_apply_affine(selection, final);
1640 void
1641 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1643     NR::translate const d2n(center);
1644     NR::translate const n2d(-center);
1645     NR::rotate const rotate(rotate_degrees(angle_degrees));
1646     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1647     sp_selection_apply_affine(selection, final);
1650 void
1651 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1653     NR::translate const d2n(align);
1654     NR::translate const n2d(-align);
1655     NR::Matrix const skew(1, dy,
1656                           dx, 1,
1657                           0, 0);
1658     NR::Matrix const final( n2d * skew * d2n );
1659     sp_selection_apply_affine(selection, final);
1662 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1664     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1667 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1669     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1673 /**
1674  * \brief sp_selection_rotate_90
1675  *
1676  * This function rotates selected objects 90 degrees clockwise.
1677  *
1678  */
1680 void sp_selection_rotate_90_cw()
1682     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1684     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1686     if (selection->isEmpty())
1687         return;
1689     GSList const *l = selection->itemList();
1690     NR::rotate const rot_neg_90(NR::Point(0, -1));
1691     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1692         SPItem *item = SP_ITEM(l2->data);
1693         sp_item_rotate_rel(item, rot_neg_90);
1694     }
1696     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1697                      _("Rotate 90&#176; CW"));
1701 /**
1702  * \brief sp_selection_rotate_90_ccw
1703  *
1704  * This function rotates selected objects 90 degrees counter-clockwise.
1705  *
1706  */
1708 void sp_selection_rotate_90_ccw()
1710     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1712     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1714     if (selection->isEmpty())
1715         return;
1717     GSList const *l = selection->itemList();
1718     NR::rotate const rot_neg_90(NR::Point(0, 1));
1719     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1720         SPItem *item = SP_ITEM(l2->data);
1721         sp_item_rotate_rel(item, rot_neg_90);
1722     }
1724     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1725                      _("Rotate 90&#176; CCW"));
1728 void
1729 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1731     if (selection->isEmpty())
1732         return;
1734     NR::Maybe<NR::Point> center = selection->center();
1735     if (!center) {
1736         return;
1737     }
1739     sp_selection_rotate_relative(selection, *center, angle_degrees);
1741     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1742                            ( ( angle_degrees > 0 )
1743                              ? "selector:rotate:ccw"
1744                              : "selector:rotate:cw" ), 
1745                            SP_VERB_CONTEXT_SELECT, 
1746                            _("Rotate"));
1749 /**
1750 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1751 */
1752 void
1753 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1755     if (selection->isEmpty())
1756         return;
1758     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1759     NR::Maybe<NR::Point> center = selection->center();
1761     if ( !bbox || !center ) {
1762         return;
1763     }
1765     gdouble const zoom = selection->desktop()->current_zoom();
1766     gdouble const zmove = angle / zoom;
1767     gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1769     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1771     sp_selection_rotate_relative(selection, *center, zangle);
1773     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1774                            ( (angle > 0)
1775                              ? "selector:rotate:ccw"
1776                              : "selector:rotate:cw" ),
1777                            SP_VERB_CONTEXT_SELECT, 
1778                            _("Rotate by pixels"));
1781 void
1782 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1784     if (selection->isEmpty())
1785         return;
1787     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1788     if (!bbox) {
1789         return;
1790     }
1792     NR::Point const center(bbox->midpoint());
1794     // you can't scale "do nizhe pola" (below zero)
1795     double const max_len = bbox->maxExtent();
1796     if ( max_len + grow <= 1e-3 ) {
1797         return;
1798     }
1800     double const times = 1.0 + grow / max_len;
1801     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1803     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1804                            ( (grow > 0)
1805                              ? "selector:scale:larger"
1806                              : "selector:scale:smaller" ),
1807                            SP_VERB_CONTEXT_SELECT,
1808                            _("Scale"));
1811 void
1812 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1814     sp_selection_scale(selection,
1815                        grow_pixels / selection->desktop()->current_zoom());
1818 void
1819 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1821     if (selection->isEmpty())
1822         return;
1824     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1826     if (!sel_bbox) {
1827         return;
1828     }
1830     NR::Point const center(sel_bbox->midpoint());
1831     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1832     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1833                      _("Scale by whole factor"));
1836 void
1837 sp_selection_move(gdouble dx, gdouble dy)
1839     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1840     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1841     if (selection->isEmpty()) {
1842         return;
1843     }
1845     sp_selection_move_relative(selection, dx, dy);
1847     if (dx == 0) {
1848         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1849                                _("Move vertically"));
1850     } else if (dy == 0) {
1851         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1852                                _("Move horizontally"));
1853     } else {
1854         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1855                          _("Move"));
1856     }
1859 void
1860 sp_selection_move_screen(gdouble dx, gdouble dy)
1862     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1864     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1865     if (selection->isEmpty()) {
1866         return;
1867     }
1869     // same as sp_selection_move but divide deltas by zoom factor
1870     gdouble const zoom = desktop->current_zoom();
1871     gdouble const zdx = dx / zoom;
1872     gdouble const zdy = dy / zoom;
1873     sp_selection_move_relative(selection, zdx, zdy);
1875     if (dx == 0) {
1876         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1877                                _("Move vertically by pixels"));
1878     } else if (dy == 0) {
1879         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1880                                _("Move horizontally by pixels"));
1881     } else {
1882         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1883                          _("Move"));
1884     }
1887 namespace {
1889 template <typename D>
1890 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1891                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1893 template <typename D>
1894 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1895                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1897 struct Forward {
1898     typedef SPObject *Iterator;
1900     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1901     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1902     static void dispose(Iterator i) {}
1904     static SPObject *object(Iterator i) { return i; }
1905     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1906 };
1908 struct Reverse {
1909     typedef GSList *Iterator;
1911     static Iterator children(SPObject *o) {
1912         return make_list(o->firstChild(), NULL);
1913     }
1914     static Iterator siblings_after(SPObject *o) {
1915         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1916     }
1917     static void dispose(Iterator i) {
1918         g_slist_free(i);
1919     }
1921     static SPObject *object(Iterator i) {
1922         return reinterpret_cast<SPObject *>(i->data);
1923     }
1924     static Iterator next(Iterator i) { return i->next; }
1926 private:
1927     static GSList *make_list(SPObject *object, SPObject *limit) {
1928         GSList *list=NULL;
1929         while ( object != limit ) {
1930             list = g_slist_prepend(list, object);
1931             object = SP_OBJECT_NEXT(object);
1932         }
1933         return list;
1934     }
1935 };
1939 void
1940 sp_selection_item_next(void)
1942     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1943     g_return_if_fail(desktop != NULL);
1944     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1946     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1947     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1948     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1950     SPObject *root;
1951     if (PREFS_SELECTION_ALL != inlayer) {
1952         root = selection->activeContext();
1953     } else {
1954         root = desktop->currentRoot();
1955     }
1957     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1959     if (item) {
1960         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1961         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1962             scroll_to_show_item(desktop, item);
1963         }
1964     }
1967 void
1968 sp_selection_item_prev(void)
1970     SPDocument *document = SP_ACTIVE_DOCUMENT;
1971     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1972     g_return_if_fail(document != NULL);
1973     g_return_if_fail(desktop != NULL);
1974     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1976     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1977     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1978     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1980     SPObject *root;
1981     if (PREFS_SELECTION_ALL != inlayer) {
1982         root = selection->activeContext();
1983     } else {
1984         root = desktop->currentRoot();
1985     }
1987     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1989     if (item) {
1990         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1991         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1992             scroll_to_show_item(desktop, item);
1993         }
1994     }
1997 namespace {
1999 template <typename D>
2000 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
2001                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2003     SPObject *current=root;
2004     while (items) {
2005         SPItem *item=SP_ITEM(items->data);
2006         if ( root->isAncestorOf(item) &&
2007              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
2008         {
2009             current = item;
2010             break;
2011         }
2012         items = items->next;
2013     }
2015     GSList *path=NULL;
2016     while ( current != root ) {
2017         path = g_slist_prepend(path, current);
2018         current = SP_OBJECT_PARENT(current);
2019     }
2021     SPItem *next;
2022     // first, try from the current object
2023     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2024     g_slist_free(path);
2026     if (!next) { // if we ran out of objects, start over at the root
2027         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2028     }
2030     return next;
2033 template <typename D>
2034 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
2035                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
2037     typename D::Iterator children;
2038     typename D::Iterator iter;
2040     SPItem *found=NULL;
2042     if (path) {
2043         SPObject *object=reinterpret_cast<SPObject *>(path->data);
2044         g_assert(SP_OBJECT_PARENT(object) == root);
2045         if (desktop->isLayer(object)) {
2046             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2047         }
2048         iter = children = D::siblings_after(object);
2049     } else {
2050         iter = children = D::children(root);
2051     }
2053     while ( iter && !found ) {
2054         SPObject *object=D::object(iter);
2055         if (desktop->isLayer(object)) {
2056             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
2057                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
2058             }
2059         } else if ( SP_IS_ITEM(object) &&
2060                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2061                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2062                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2063                     !desktop->isLayer(SP_ITEM(object)) )
2064         {
2065             found = SP_ITEM(object);
2066         }
2067         iter = D::next(iter);
2068     }
2070     D::dispose(children);
2072     return found;
2077 /**
2078  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2079  * \a item.
2080  */
2081 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2083     NR::Rect dbox = desktop->get_display_area();
2084     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2086     if ( sbox && dbox.contains(*sbox) == false ) {
2087         NR::Point const s_dt = sbox->midpoint();
2088         NR::Point const s_w = desktop->d2w(s_dt);
2089         NR::Point const d_dt = dbox.midpoint();
2090         NR::Point const d_w = desktop->d2w(d_dt);
2091         NR::Point const moved_w( d_w - s_w );
2092         gint const dx = (gint) moved_w[X];
2093         gint const dy = (gint) moved_w[Y];
2094         desktop->scroll_world(dx, dy);
2095     }
2099 void
2100 sp_selection_clone()
2102     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2103     if (desktop == NULL)
2104         return;
2106     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2108     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2110     // check if something is selected
2111     if (selection->isEmpty()) {
2112         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2113         return;
2114     }
2116     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2117   
2118     selection->clear();
2119   
2120     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2121     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2123     GSList *newsel = NULL;
2124  
2125     while (reprs) {
2126         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2127         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2129         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2130         sp_repr_set_attr(clone, "x", "0");
2131         sp_repr_set_attr(clone, "y", "0");
2132         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2134         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2135         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2136         
2137         // add the new clone to the top of the original's parent
2138         parent->appendChild(clone);
2140         newsel = g_slist_prepend(newsel, clone);
2141         reprs = g_slist_remove(reprs, sel_repr);
2142         Inkscape::GC::release(clone);
2143     }
2144     
2145     // TRANSLATORS: only translate "string" in "context|string".
2146     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2147     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2148                      Q_("action|Clone"));
2150     selection->setReprList(newsel);
2151  
2152     g_slist_free(newsel);
2155 void
2156 sp_selection_unlink()
2158     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2159     if (!desktop)
2160         return;
2162     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2164     if (selection->isEmpty()) {
2165         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2166         return;
2167     }
2169     // Get a copy of current selection.
2170     GSList *new_select = NULL;
2171     bool unlinked = false;
2172     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2173          items != NULL;
2174          items = items->next)
2175     {
2176         SPItem *item = (SPItem *) items->data;
2178         if (SP_IS_TEXT(item)) {
2179             SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2180             
2181             if (tspan) {            
2182                 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2183             }
2184             
2185             // Set unlink to true, and fall into the next if which
2186             // will include this text item in the new selection
2187             unlinked = true;
2188         }
2190         if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2191             // keep the non-use item in the new selection
2192             new_select = g_slist_prepend(new_select, item);
2193             continue;
2194         }
2196         SPItem *unlink;
2197         if (SP_IS_USE(item)) { 
2198             unlink = sp_use_unlink(SP_USE(item));
2199         } else /*if (SP_IS_TREF(use))*/ {
2200             unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2201         }
2202         
2203         unlinked = true;
2204         // Add ungrouped items to the new selection.
2205         new_select = g_slist_prepend(new_select, unlink);
2206     }
2208     if (new_select) { // set new selection
2209         selection->clear();
2210         selection->setList(new_select);
2211         g_slist_free(new_select);
2212     }
2213     if (!unlinked) {
2214         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2215     }
2217     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2218                      _("Unlink clone"));
2221 void
2222 sp_select_clone_original()
2224     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2225     if (desktop == NULL)
2226         return;
2228     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2230     SPItem *item = selection->singleItem();
2232     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.");
2234     // Check if other than two objects are selected
2235     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2236         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2237         return;
2238     }
2240     SPItem *original = NULL;
2241     if (SP_IS_USE(item)) {
2242         original = sp_use_get_original (SP_USE(item));
2243     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2244         original = sp_offset_get_source (SP_OFFSET(item));
2245     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2246         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2247     } else if (SP_IS_FLOWTEXT(item)) {
2248         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2249     } else { // it's an object that we don't know what to do with
2250         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2251         return;
2252     }
2254     if (!original) {
2255         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2256         return;
2257     }
2259     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2260         if (SP_IS_DEFS (o)) {
2261             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2262             return;
2263         }
2264     }
2266     if (original) {
2267         selection->clear();
2268         selection->set(original);
2269         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2270             scroll_to_show_item(desktop, original);
2271         }
2272     }
2276 void sp_selection_to_marker(bool apply)
2278     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2279     if (desktop == NULL)
2280         return;
2282     SPDocument *doc = sp_desktop_document(desktop);
2283     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2285     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2287     // check if something is selected
2288     if (selection->isEmpty()) {
2289         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2290         return;
2291     }
2293     sp_document_ensure_up_to_date(doc);
2294     NR::Maybe<NR::Rect> r = selection->bounds();
2295     if ( !r || r->isEmpty() ) {
2296         return;
2297     }
2299     // calculate the transform to be applied to objects to move them to 0,0
2300     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point ((r->extent(NR::X))/2, (r->extent(NR::Y))/2));
2301     move_p[NR::Y] = -move_p[NR::Y];
2302     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2304     GSList *items = g_slist_copy((GSList *) selection->itemList());
2306     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2308     // bottommost object, after sorting
2309     SPObject *parent = SP_OBJECT_PARENT (items->data);
2311     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2313     // remember the position of the first item
2314     gint pos = SP_OBJECT_REPR (items->data)->position();
2316     // create a list of duplicates
2317     GSList *repr_copies = NULL;
2318     for (GSList *i = items; i != NULL; i = i->next) {
2319         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2320         repr_copies = g_slist_prepend (repr_copies, dup);
2321     }
2323     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2325     if (apply) {
2326         // delete objects so that their clones don't get alerted; this object will be restored shortly
2327         for (GSList *i = items; i != NULL; i = i->next) {
2328             SPObject *item = SP_OBJECT (i->data);
2329             item->deleteObject (false);
2330         }
2331     }
2333     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2334     // without disturbing clones.
2335     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2336     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2337     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2339     const gchar *mark_id = generate_marker (repr_copies, bounds, doc,
2340                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X], r->max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2342     // restore compensation setting
2343     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2346     g_slist_free (items);
2348     sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2349                       _("Objects to marker"));
2352 void
2353 sp_selection_tile(bool apply)
2355     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2356     if (desktop == NULL)
2357         return;
2359     SPDocument *doc = sp_desktop_document(desktop);
2360     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2362     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2364     // check if something is selected
2365     if (selection->isEmpty()) {
2366         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2367         return;
2368     }
2370     sp_document_ensure_up_to_date(doc);
2371     NR::Maybe<NR::Rect> r = selection->bounds();
2372     if ( !r || r->isEmpty() ) {
2373         return;
2374     }
2376     // calculate the transform to be applied to objects to move them to 0,0
2377     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2378     move_p[NR::Y] = -move_p[NR::Y];
2379     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2381     GSList *items = g_slist_copy((GSList *) selection->itemList());
2383     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2385     // bottommost object, after sorting
2386     SPObject *parent = SP_OBJECT_PARENT (items->data);
2388     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2390     // remember the position of the first item
2391     gint pos = SP_OBJECT_REPR (items->data)->position();
2393     // create a list of duplicates
2394     GSList *repr_copies = NULL;
2395     for (GSList *i = items; i != NULL; i = i->next) {
2396         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2397         repr_copies = g_slist_prepend (repr_copies, dup);
2398     }
2400     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2402     if (apply) {
2403         // delete objects so that their clones don't get alerted; this object will be restored shortly
2404         for (GSList *i = items; i != NULL; i = i->next) {
2405             SPObject *item = SP_OBJECT (i->data);
2406             item->deleteObject (false);
2407         }
2408     }
2410     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2411     // without disturbing clones.
2412     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2413     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2414     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2416     const gchar *pat_id = pattern_tile (repr_copies, bounds, doc,
2417                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X], r->max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2419     // restore compensation setting
2420     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2422     if (apply) {
2423         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2424         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2426         NR::Point min = bounds.min() * parent_transform.inverse();
2427         NR::Point max = bounds.max() * parent_transform.inverse();
2429         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2430         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2431         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2432         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2434         // restore parent and position
2435         SP_OBJECT_REPR (parent)->appendChild(rect);
2436         rect->setPosition(pos > 0 ? pos : 0);
2437         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2439         Inkscape::GC::release(rect);
2441         selection->clear();
2442         selection->set(rectangle);
2443     }
2445     g_slist_free (items);
2447     sp_document_done (doc, SP_VERB_EDIT_TILE, 
2448                       _("Objects to pattern"));
2451 void
2452 sp_selection_untile()
2454     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2455     if (desktop == NULL)
2456         return;
2458     SPDocument *doc = sp_desktop_document(desktop);
2459     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2461     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2463     // check if something is selected
2464     if (selection->isEmpty()) {
2465         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2466         return;
2467     }
2469     GSList *new_select = NULL;
2471     bool did = false;
2473     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2474          items != NULL;
2475          items = items->next) {
2477         SPItem *item = (SPItem *) items->data;
2479         SPStyle *style = SP_OBJECT_STYLE (item);
2481         if (!style || !style->fill.isPaintserver())
2482             continue;
2484         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2486         if (!SP_IS_PATTERN(server))
2487             continue;
2489         did = true;
2491         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2493         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2494         pat_transform *= item->transform;
2496         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2497             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2498             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2500            // FIXME: relink clones to the new canvas objects
2501            // use SPObject::setid when mental finishes it to steal ids of
2503             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2504             sp_document_ensure_up_to_date (doc);
2506             NR::Matrix transform( i->transform * pat_transform );
2507             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2509             new_select = g_slist_prepend(new_select, i);
2510         }
2512         SPCSSAttr *css = sp_repr_css_attr_new ();
2513         sp_repr_css_set_property (css, "fill", "none");
2514         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2515     }
2517     if (!did) {
2518         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2519     } else {
2520         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2521                          _("Pattern to objects"));
2522         selection->setList(new_select);
2523     }
2526 void
2527 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2529     if (selection->isEmpty()) {
2530         return;
2531     }
2533     const GSList * reprlst = selection->reprList();
2534     bool filename_search = TRUE;
2535     bool xdpi_search = TRUE;
2536     bool ydpi_search = TRUE;
2538     for(; reprlst != NULL &&
2539             filename_search &&
2540             xdpi_search &&
2541             ydpi_search;
2542         reprlst = reprlst->next) {
2543         const gchar * dpi_string;
2544         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2546         if (filename_search) {
2547             *filename = repr->attribute("inkscape:export-filename");
2548             if (*filename != NULL)
2549                 filename_search = FALSE;
2550         }
2552         if (xdpi_search) {
2553             dpi_string = NULL;
2554             dpi_string = repr->attribute("inkscape:export-xdpi");
2555             if (dpi_string != NULL) {
2556                 *xdpi = atof(dpi_string);
2557                 xdpi_search = FALSE;
2558             }
2559         }
2561         if (ydpi_search) {
2562             dpi_string = NULL;
2563             dpi_string = repr->attribute("inkscape:export-ydpi");
2564             if (dpi_string != NULL) {
2565                 *ydpi = atof(dpi_string);
2566                 ydpi_search = FALSE;
2567             }
2568         }
2569     }
2572 void
2573 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2575     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2576     const gchar * dpi_string;
2578     *filename = repr->attribute("inkscape:export-filename");
2580     dpi_string = NULL;
2581     dpi_string = repr->attribute("inkscape:export-xdpi");
2582     if (dpi_string != NULL) {
2583         *xdpi = atof(dpi_string);
2584     }
2586     dpi_string = NULL;
2587     dpi_string = repr->attribute("inkscape:export-ydpi");
2588     if (dpi_string != NULL) {
2589         *ydpi = atof(dpi_string);
2590     }
2593 void
2594 sp_selection_create_bitmap_copy ()
2596     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2597     if (desktop == NULL)
2598         return;
2600     SPDocument *document = sp_desktop_document(desktop);
2601     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2603     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2605     // check if something is selected
2606     if (selection->isEmpty()) {
2607         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2608         return;
2609     }
2611     // Get the bounding box of the selection
2612     NRRect bbox;
2613     sp_document_ensure_up_to_date (document);
2614     selection->bounds(&bbox);
2615     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2616         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2617     }
2619     // List of the items to show; all others will be hidden
2620     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2622     // Sort items so that the topmost comes last
2623     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2625     // Generate a random value from the current time (you may create bitmap from the same object(s)
2626     // multiple times, and this is done so that they don't clash)
2627     GTimeVal cu;
2628     g_get_current_time (&cu);
2629     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2631     // Create the filename
2632     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2633     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2634     // digits, and a few other chars, with "_"
2635     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2636     // Build the complete path by adding document->base if set
2637     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2639     //g_print ("%s\n", filepath);
2641     // Remember parent and z-order of the topmost one
2642     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2643     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2644     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2646     // Calculate resolution
2647     double res;
2648     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2649     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2650     if (0 < prefs_res) {
2651         // If it's given explicitly in prefs, take it
2652         res = prefs_res;
2653     } else if (0 < prefs_min) {
2654         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2655         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2656     } else {
2657         float hint_xdpi = 0, hint_ydpi = 0;
2658         const char *hint_filename;
2659         // take resolution hint from the selected objects
2660         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2661         if (hint_xdpi != 0) {
2662             res = hint_xdpi;
2663         } else {
2664             // take resolution hint from the document
2665             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2666             if (hint_xdpi != 0) {
2667                 res = hint_xdpi;
2668             } else {
2669                 // if all else fails, take the default 90 dpi
2670                 res = PX_PER_IN;
2671             }
2672         }
2673     }
2675     // The width and height of the bitmap in pixels
2676     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2677     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2679     // Find out if we have to run a filter
2680     const gchar *run = NULL;
2681     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2682     if (filter) {
2683         // filter command is given;
2684         // see if we have a parameter to pass to it
2685         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2686         if (param1) {
2687             if (param1[strlen(param1) - 1] == '%') {
2688                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2689                 gchar p1[256];
2690                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2691                 // the first param is always the image filename, the second is param1
2692                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2693             } else {
2694                 // otherwise pass the param1 unchanged
2695                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2696             }
2697         } else {
2698             // run without extra parameter
2699             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2700         }
2701     }
2703     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2704     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2705     NR::Matrix t;
2707     double shift_x = bbox.x0;
2708     double shift_y = bbox.y1; 
2709     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2710         shift_x = round (shift_x);
2711         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2712     }
2713     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2715     // Do the export
2716     sp_export_png_file(document, filepath,
2717                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2718                    width, height, res, res,
2719                    (guint32) 0xffffff00,
2720                    NULL, NULL,
2721                    true,  /*bool force_overwrite,*/
2722                    items);
2724     g_slist_free (items);
2726     // Run filter, if any
2727     if (run) {
2728         g_print ("Running external filter: %s\n", run);
2729         system (run);
2730     }
2732     // Import the image back
2733     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2734     if (pb) {
2735         // Create the repr for the image
2736         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2737         repr->setAttribute("xlink:href", filename);
2738         repr->setAttribute("sodipodi:absref", filepath);
2739         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2740             sp_repr_set_svg_double(repr, "width", width);
2741             sp_repr_set_svg_double(repr, "height", height);
2742         } else {
2743             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2744             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2745         }
2747         // Write transform
2748         gchar *c=sp_svg_transform_write(t);
2749         repr->setAttribute("transform", c);
2750         g_free(c);
2752         // add the new repr to the parent
2753         parent->appendChild(repr);
2755         // move to the saved position
2756         repr->setPosition(pos > 0 ? pos + 1 : 1);
2758         // Set selection to the new image
2759         selection->clear();
2760         selection->add(repr);
2762         // Clean up
2763         Inkscape::GC::release(repr);
2764         gdk_pixbuf_unref (pb);
2766         // Complete undoable transaction
2767         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2768                           _("Create bitmap"));
2769     }
2771     g_free (filename);
2772     g_free (filepath);
2775 /**
2776  * \brief sp_selection_set_mask
2777  *
2778  * This function creates a mask or clipPath from selection
2779  * Two different modes:
2780  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2781  *       and is applied to current layer
2782  *  otherwise, topmost object is used as mask for other objects
2783  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2784  * 
2785  */
2786 void
2787 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2789     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2790     if (desktop == NULL)
2791         return;
2793     SPDocument *doc = sp_desktop_document(desktop);
2794     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2795     
2796     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2798     // check if something is selected
2799     bool is_empty = selection->isEmpty();
2800     if ( apply_to_layer && is_empty) {
2801         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2802         return;
2803     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2804         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2805         return;
2806     }
2808     // FIXME: temporary patch to prevent crash! 
2809     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2810     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2811     if (clone_with_original) {
2812         return; // in this version, you cannot clip/mask an object with its own clone
2813     }
2814     // /END FIXME
2815     
2816     sp_document_ensure_up_to_date(doc);
2818     GSList *items = g_slist_copy((GSList *) selection->itemList());
2819     
2820     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2822     // create a list of duplicates
2823     GSList *mask_items = NULL;
2824     GSList *apply_to_items = NULL;
2825     GSList *items_to_delete = NULL;
2826     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2827     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2828     
2829     if (apply_to_layer) {
2830         // all selected items are used for mask, which is applied to a layer
2831         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2833         for (GSList *i = items; i != NULL; i = i->next) {
2834             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2835             mask_items = g_slist_prepend (mask_items, dup);
2837             if (remove_original) {
2838                 SPObject *item = SP_OBJECT (i->data);
2839                 items_to_delete = g_slist_prepend (items_to_delete, item);
2840             }
2841         }
2842     } else if (!topmost) {
2843         // topmost item is used as a mask, which is applied to other items in a selection
2844         GSList *i = items;
2845         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2846         mask_items = g_slist_prepend (mask_items, dup);
2848         if (remove_original) {
2849             SPObject *item = SP_OBJECT (i->data);
2850             items_to_delete = g_slist_prepend (items_to_delete, item);
2851         }
2852         
2853         for (i = i->next; i != NULL; i = i->next) {
2854             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2855         }
2856     } else {
2857         GSList *i = NULL;
2858         for (i = items; NULL != i->next; i = i->next) {
2859             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2860         }
2862         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2863         mask_items = g_slist_prepend (mask_items, dup);
2865         if (remove_original) {
2866             SPObject *item = SP_OBJECT (i->data);
2867             items_to_delete = g_slist_prepend (items_to_delete, item);
2868         }
2869     }
2870     
2871     g_slist_free (items);
2872     items = NULL;
2873             
2874     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2875     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2876         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2877         // inverted object transform should be applied to a mask object,
2878         // as mask is calculated in user space (after applying transform)
2879         NR::Matrix maskTransform (item->transform.inverse());
2881         GSList *mask_items_dup = NULL;
2882         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2883             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2884             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2885         }
2887         const gchar *mask_id = NULL;
2888         if (apply_clip_path) {
2889             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2890         } else {
2891             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2892         }
2894         g_slist_free (mask_items_dup);
2895         mask_items_dup = NULL;
2897         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2898     }
2900     g_slist_free (mask_items);
2901     g_slist_free (apply_to_items);
2903     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2904         SPObject *item = SP_OBJECT (i->data);
2905         item->deleteObject (false);
2906     }
2907     g_slist_free (items_to_delete);
2909     if (apply_clip_path) 
2910         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2911     else 
2912         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2915 void sp_selection_unset_mask(bool apply_clip_path) {
2916     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2917     if (desktop == NULL)
2918         return;
2919     
2920     SPDocument *doc = sp_desktop_document(desktop);    
2921     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2922     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2924     // check if something is selected
2925     if (selection->isEmpty()) {
2926         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2927         return;
2928     }
2929     
2930     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2931     sp_document_ensure_up_to_date(doc);
2933     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2934     std::map<SPObject*,SPItem*> referenced_objects;
2935     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2936         if (remove_original) {
2937             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2938             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2939             Inkscape::URIReference *uri_ref = NULL;
2940         
2941             if (apply_clip_path) {
2942                 uri_ref = item->clip_ref;
2943             } else {
2944                 uri_ref = item->mask_ref;
2945             }
2947             // collect distinct mask object (and associate with item to apply transform)
2948             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2949                 referenced_objects[uri_ref->getObject()] = item;
2950             }
2951         }
2953         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2954     }
2956     // restore mask objects into a document
2957     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2958         SPObject *obj = (*it).first;
2959         GSList *items_to_move = NULL;
2960         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2961             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2962             items_to_move = g_slist_prepend (items_to_move, copy);
2963         }
2965         if (!obj->isReferenced()) {
2966             // delete from defs if no other object references this mask
2967             obj->deleteObject(false);
2968         }
2970         // remember parent and position of the item to which the clippath/mask was applied
2971         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2972         gint pos = SP_OBJECT_REPR((*it).second)->position();
2974         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2975             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2977             // insert into parent, restore pos
2978             parent->appendChild(repr);
2979             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2981             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2982             selection->add(repr);
2984             // transform mask, so it is moved the same spot where mask was applied
2985             NR::Matrix transform (mask_item->transform);
2986             transform *= (*it).second->transform;
2987             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2988         }
2990         g_slist_free (items_to_move);
2991     }
2993     if (apply_clip_path) 
2994         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2995     else 
2996         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2999 void fit_canvas_to_selection(SPDesktop *desktop) {
3000     g_return_if_fail(desktop != NULL);
3001     SPDocument *doc = sp_desktop_document(desktop);
3003     g_return_if_fail(doc != NULL);
3004     g_return_if_fail(desktop->selection != NULL);
3005     g_return_if_fail(!desktop->selection->isEmpty());
3007     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
3008     if (bbox && !bbox->isEmpty()) {
3009         doc->fitToRect(*bbox);
3010     }
3011 };
3013 void fit_canvas_to_drawing(SPDocument *doc) {
3014     g_return_if_fail(doc != NULL);
3016     sp_document_ensure_up_to_date(doc);
3017     SPItem const *const root = SP_ITEM(doc->root);
3018     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
3019     if (bbox && !bbox->isEmpty()) {
3020         doc->fitToRect(*bbox);
3021     }
3022 };
3024 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3025     g_return_if_fail(desktop != NULL);
3026     SPDocument *doc = sp_desktop_document(desktop);
3028     g_return_if_fail(doc != NULL);
3029     g_return_if_fail(desktop->selection != NULL);
3031     if (desktop->selection->isEmpty()) {
3032         fit_canvas_to_drawing(doc);
3033     } else {
3034         fit_canvas_to_selection(desktop);
3035     }
3037     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
3038                      _("Fit page to selection"));
3039 };
3041 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3042     // don't operate on layers
3043     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3044         f(SP_ITEM(root), desktop);
3045     }
3046     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3047         //don't recurse into locked layers
3048         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3049             itemtree_map(f, iter, desktop);
3050         }
3051     }
3054 static void unlock(SPItem *item, SPDesktop *desktop) {
3055     if (item->isLocked()) {
3056         item->setLocked(FALSE);
3057     }
3060 static void unhide(SPItem *item, SPDesktop *desktop) {
3061     if (desktop->itemIsHidden(item)) {
3062         item->setExplicitlyHidden(FALSE);
3063     }
3066 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3067     if (!dt) return;
3068         
3069     SPObject *root;
3070     if (layer_only) {
3071         root = dt->currentLayer();
3072     } else {
3073         root = dt->currentRoot();
3074     }
3075     
3076     itemtree_map(f, root, dt);
3079 void unlock_all(SPDesktop *dt) {
3080     process_all(&unlock, dt, true);
3083 void unlock_all_in_all_layers(SPDesktop *dt) {
3084     process_all(&unlock, dt, false);
3087 void unhide_all(SPDesktop *dt) {
3088     process_all(&unhide, dt, true);
3091 void unhide_all_in_all_layers(SPDesktop *dt) {
3092     process_all(&unhide, dt, false);
3096 GSList * sp_selection_get_clipboard() {
3097     return clipboard;
3100 /*
3101   Local Variables:
3102   mode:c++
3103   c-file-style:"stroustrup"
3104   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3105   indent-tabs-mode:nil
3106   fill-column:99
3107   End:
3108 */
3109 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :