Code

27c04f1ddd4e9f10b9015edb930873335b852f63
[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-flowtext.h"
39 #include "sp-flowregion.h"
40 #include "text-editing.h"
41 #include "text-context.h"
42 #include "connector-context.h"
43 #include "sp-path.h"
44 #include "sp-conn-end.h"
45 #include "dropper-context.h"
46 #include <glibmm/i18n.h>
47 #include "libnr/nr-matrix-rotate-ops.h"
48 #include "libnr/nr-matrix-translate-ops.h"
49 #include "libnr/nr-rotate-fns.h"
50 #include "libnr/nr-scale-ops.h"
51 #include "libnr/nr-scale-translate-ops.h"
52 #include "libnr/nr-translate-matrix-ops.h"
53 #include "libnr/nr-translate-scale-ops.h"
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "prefs-utils.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include "helper/units.h"
73 #include "sp-item.h"
74 #include "unit-constants.h"
75 #include "xml/simple-document.h"
76 #include "sp-filter-reference.h"
78 using NR::X;
79 using NR::Y;
81 #include "selection-chemistry.h"
83 /* fixme: find a better place */
84 Inkscape::XML::Document *clipboard_document = NULL;
85 GSList *clipboard = NULL;
86 GSList *defs_clipboard = NULL;
87 SPCSSAttr *style_clipboard = NULL;
88 NR::Maybe<NR::Rect> size_clipboard;
90 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc);
92 /**
93  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
94  * then prepends the copy to 'clip'.
95  */
96 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
97 {
98     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
100     // copy complete inherited style
101     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
102     sp_repr_css_set(copy, css, "style");
103     sp_repr_css_attr_unref(css);
105     // write the complete accumulated transform passed to us
106     // (we're dealing with unattached repr, so we write to its attr 
107     // instead of using sp_item_set_transform)
108     gchar *affinestr=sp_svg_transform_write(full_t);
109     copy->setAttribute("transform", affinestr);
110     g_free(affinestr);
112     *clip = g_slist_prepend(*clip, copy);
115 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
118     // Copy stuff referenced by all items to defs_clip:
119     if (defs_clip) {
120         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
121             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
122         }
123         *defs_clip = g_slist_reverse(*defs_clip);
124     }
126     // Store style:
127     if (style_clip) {
128         SPItem *item = SP_ITEM (items->data); // take from the first selected item
129         *style_clip = take_style_from_item (item);
130     }
132     if (clip) {
133         // Sort items:
134         GSList *sorted_items = g_slist_copy ((GSList *) items);
135         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
137         // Copy item reprs:
138         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
139             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
140         }
142         *clip = g_slist_reverse(*clip);
143         g_slist_free ((GSList *) sorted_items);
144     }
147 /**
148  * Add gradients/patterns/markers referenced by copied objects to defs.
149  * Iterates through 'defs_clip', and for each item it adds the data
150  * repr into the global defs.
151  */
152 void
153 paste_defs (GSList **defs_clip, SPDocument *doc)
155     if (!defs_clip)
156         return;
158     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
159         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
160         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
161         gchar const *id = repr->attribute("id");
162         if (!id || !doc->getObjectById(id)) {
163             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
164             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
165             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
166             Inkscape::GC::release(copy);
167         }
168     }
171 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
173     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
174     paste_defs (defs_clip, doc);
176     GSList *copied = NULL;
177     // add objects to document
178     for (GSList *l = *clip; l != NULL; l = l->next) {
179         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
180         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
182         // premultiply the item transform by the accumulated parent transform in the paste layer
183         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
184         if (!local.test_identity()) {
185             gchar const *t_str = copy->attribute("transform");
186             NR::Matrix item_t (NR::identity());
187             if (t_str)
188                 sp_svg_transform_read(t_str, &item_t);
189             item_t *= local.inverse();
190             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
191             gchar *affinestr=sp_svg_transform_write(item_t);
192             copy->setAttribute("transform", affinestr);
193             g_free(affinestr);
194         }
196         parent->appendChildRepr(copy);
197         copied = g_slist_prepend(copied, copy);
198         Inkscape::GC::release(copy);
199     }
200     return copied;
203 void sp_selection_delete_impl(const GSList *items)
205     for (const GSList *i = items ; i ; i = i->next ) {
206         sp_object_ref((SPObject *)i->data, NULL);
207     }
208     for (const GSList *i = items; i != NULL; i = i->next) {
209         SPItem *item = (SPItem *) i->data;
210         SP_OBJECT(item)->deleteObject();
211         sp_object_unref((SPObject *)item, NULL);
212     }
216 void sp_selection_delete()
218     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
219     if (desktop == NULL) {
220         return;
221     }
223     if (tools_isactive (desktop, TOOLS_TEXT))
224         if (sp_text_delete_selection(desktop->event_context)) {
225             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
226                              _("Delete text"));
227             return;
228         }
230     Inkscape::Selection *selection = sp_desktop_selection(desktop);
232     // check if something is selected
233     if (selection->isEmpty()) {
234         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
235         return;
236     }
238     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
239     selection->clear();
240     sp_selection_delete_impl (selected);
241     g_slist_free ((GSList *) selected);
243     /* a tool may have set up private information in it's selection context
244      * that depends on desktop items.  I think the only sane way to deal with
245      * this currently is to reset the current tool, which will reset it's
246      * associated selection context.  For example: deleting an object
247      * while moving it around the canvas.
248      */
249     tools_switch ( desktop, tools_active ( desktop ) );
251     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
252                      _("Delete"));
255 /* fixme: sequencing */
256 void sp_selection_duplicate()
258     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
259     if (desktop == NULL)
260         return;
262     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
263     Inkscape::Selection *selection = sp_desktop_selection(desktop);
265     // check if something is selected
266     if (selection->isEmpty()) {
267         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
268         return;
269     }
271     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
273     selection->clear();
275     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
276     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
278     GSList *newsel = NULL;
280     while (reprs) {
281         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
282         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
284         parent->appendChild(copy);
286         newsel = g_slist_prepend(newsel, copy);
287         reprs = g_slist_remove(reprs, reprs->data);
288         Inkscape::GC::release(copy);
289     }
291     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
292                      _("Duplicate"));
294     selection->setReprList(newsel);
296     g_slist_free(newsel);
299 void sp_edit_clear_all()
301     SPDesktop *dt = SP_ACTIVE_DESKTOP;
302     if (!dt)
303         return;
305     SPDocument *doc = sp_desktop_document(dt);
306     sp_desktop_selection(dt)->clear();
308     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
309     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
311     while (items) {
312         SP_OBJECT (items->data)->deleteObject();
313         items = g_slist_remove(items, items->data);
314     }
316     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
317                      _("Delete all"));
320 GSList *
321 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
323     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
324         if (SP_IS_ITEM(child) &&
325             !desktop->isLayer(SP_ITEM(child)) &&
326             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
327             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
328             (!exclude || !g_slist_find ((GSList *) exclude, child))
329             )
330         {
331             list = g_slist_prepend (list, SP_ITEM(child));
332         }
334         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
335             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
336         }
337     }
339     return list;
342 void sp_edit_select_all_full (bool force_all_layers, bool invert)
344     SPDesktop *dt = SP_ACTIVE_DESKTOP;
345     if (!dt)
346         return;
348     Inkscape::Selection *selection = sp_desktop_selection(dt);
350     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
352     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
353     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
354     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
356     GSList *items = NULL;
358     const GSList *exclude = NULL;
359     if (invert) {
360         exclude = selection->itemList();
361     }
363     if (force_all_layers)
364         inlayer = PREFS_SELECTION_ALL;
366     switch (inlayer) {
367         case PREFS_SELECTION_LAYER: {
368         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
369              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
370         return;
372         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
374         for (GSList *i = all_items; i; i = i->next) {
375             SPItem *item = SP_ITEM (i->data);
377             if (item && (!onlysensitive || !item->isLocked())) {
378                 if (!onlyvisible || !dt->itemIsHidden(item)) {
379                     if (!dt->isLayer(item)) {
380                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
381                             items = g_slist_prepend (items, item); // leave it in the list
382                         }
383                     }
384                 }
385             }
386         }
388         g_slist_free (all_items);
389             break;
390         }
391         case PREFS_SELECTION_LAYER_RECURSIVE: {
392             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
393             break;
394         }
395         default: {
396         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
397             break;
398     }
399     }
401     selection->setList (items);
403     if (items) {
404         g_slist_free (items);
405     }
408 void sp_edit_select_all ()
410     sp_edit_select_all_full (false, false);
413 void sp_edit_select_all_in_all_layers ()
415     sp_edit_select_all_full (true, false);
418 void sp_edit_invert ()
420     sp_edit_select_all_full (false, true);
423 void sp_edit_invert_in_all_layers ()
425     sp_edit_select_all_full (true, true);
428 void sp_selection_group()
430     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
431     if (desktop == NULL)
432         return;
434     SPDocument *doc = sp_desktop_document (desktop);
435     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
437     Inkscape::Selection *selection = sp_desktop_selection(desktop);
439     // Check if something is selected.
440     if (selection->isEmpty()) {
441         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
442         return;
443     }
445     GSList const *l = (GSList *) selection->reprList();
447     GSList *p = g_slist_copy((GSList *) l);
449     selection->clear();
451     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
453     // Remember the position and parent of the topmost object.
454     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
455     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
457     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
459     while (p) {
460         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
462         if (current->parent() == topmost_parent) {
463             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
464             sp_repr_unparent(current);
465             group->appendChild(spnew);
466             Inkscape::GC::release(spnew);
467             topmost --; // only reduce count for those items deleted from topmost_parent
468         } else { // move it to topmost_parent first
469                 GSList *temp_clip = NULL;
471                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
472                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
473                 gchar const *t_str = current->attribute("transform");
474                 NR::Matrix item_t (NR::identity());
475                 if (t_str)
476                     sp_svg_transform_read(t_str, &item_t);
477                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
478                 //FIXME: when moving both clone and original from a transformed group (either by
479                 //grouping into another parent, or by cut/paste) the transform from the original's
480                 //parent becomes embedded into original itself, and this affects its clones. Fix
481                 //this by remembering the transform diffs we write to each item into an array and
482                 //then, if this is clone, looking up its original in that array and pre-multiplying
483                 //it by the inverse of that original's transform diff.
485                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
486                 sp_repr_unparent(current);
488                 // paste into topmost_parent (temporarily)
489                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
490                 if (temp_clip) g_slist_free (temp_clip);
491                 if (copied) { // if success,
492                     // take pasted object (now in topmost_parent)
493                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
494                     // make a copy
495                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
496                     // remove pasted
497                     sp_repr_unparent(in_topmost);
498                     // put its copy into group
499                     group->appendChild(spnew);
500                     Inkscape::GC::release(spnew);
501                     g_slist_free (copied);
502                 }
503         }
504         p = g_slist_remove(p, current);
505     }
507     // Add the new group to the topmost members' parent
508     topmost_parent->appendChild(group);
510     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
511     group->setPosition(topmost + 1);
513     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
514                      _("Group"));
516     selection->set(group);
517     Inkscape::GC::release(group);
520 void sp_selection_ungroup()
522     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
523     if (desktop == NULL)
524         return;
526     Inkscape::Selection *selection = sp_desktop_selection(desktop);
528     if (selection->isEmpty()) {
529         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
530         return;
531     }
533     GSList *items = g_slist_copy((GSList *) selection->itemList());
534     selection->clear();
536     // Get a copy of current selection.
537     GSList *new_select = NULL;
538     bool ungrouped = false;
539     for (GSList *i = items;
540          i != NULL;
541          i = i->next)
542     {
543         SPItem *group = (SPItem *) i->data;
545         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
546         if (!SP_IS_OBJECT(group)) {
547             continue;
548         }
550         /* We do not allow ungrouping <svg> etc. (lauris) */
551         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
552             // keep the non-group item in the new selection
553             selection->add(group);
554             continue;
555         }
557         GSList *children = NULL;
558         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
559         sp_item_group_ungroup(SP_GROUP(group), &children, false);
560         ungrouped = true;
561         // Add ungrouped items to the new selection.
562         new_select = g_slist_concat(new_select, children);
563     }
565     if (new_select) { // Set new selection.
566         selection->addList(new_select);
567         g_slist_free(new_select);
568     }
569     if (!ungrouped) {
570         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
571     }
573     g_slist_free(items);
575     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
576                      _("Ungroup"));
579 static SPGroup *
580 sp_item_list_common_parent_group(const GSList *items)
582     if (!items) {
583         return NULL;
584     }
585     SPObject *parent = SP_OBJECT_PARENT(items->data);
586     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
587     if (!SP_IS_GROUP(parent)) {
588         return NULL;
589     }
590     for (items = items->next; items; items = items->next) {
591         if (SP_OBJECT_PARENT(items->data) != parent) {
592             return NULL;
593         }
594     }
596     return SP_GROUP(parent);
599 /** Finds out the minimum common bbox of the selected items
600  */
601 static NR::Maybe<NR::Rect>
602 enclose_items(const GSList *items)
604     g_assert(items != NULL);
606     NR::Maybe<NR::Rect> r = NR::Nothing();
607     for (GSList const *i = items; i; i = i->next) {
608         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
609     }
610     return r;
613 SPObject *
614 prev_sibling(SPObject *child)
616     SPObject *parent = SP_OBJECT_PARENT(child);
617     if (!SP_IS_GROUP(parent)) {
618         return NULL;
619     }
620     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
621         if (i->next == child)
622             return i;
623     }
624     return NULL;
627 void
628 sp_selection_raise()
630     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
631     if (!desktop)
632         return;
634     Inkscape::Selection *selection = sp_desktop_selection(desktop);
636     GSList const *items = (GSList *) selection->itemList();
637     if (!items) {
638         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
639         return;
640     }
642     SPGroup const *group = sp_item_list_common_parent_group(items);
643     if (!group) {
644         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
645         return;
646     }
648     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
650     /* construct reverse-ordered list of selected children */
651     GSList *rev = g_slist_copy((GSList *) items);
652     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
654     // find out the common bbox of the selected items
655     NR::Maybe<NR::Rect> selected = enclose_items(items);
657     // for all objects in the selection (starting from top)
658     if (selected) {
659         while (rev) {
660             SPObject *child = SP_OBJECT(rev->data);
661             // for each selected object, find the next sibling
662             for (SPObject *newref = child->next; newref; newref = newref->next) {
663                 // if the sibling is an item AND overlaps our selection,
664                 if (SP_IS_ITEM(newref)) {
665                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
666                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
667                         // AND if it's not one of our selected objects,
668                         if (!g_slist_find((GSList *) items, newref)) {
669                             // move the selected object after that sibling
670                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
671                         }
672                         break;
673                     }
674                 }
675             }
676             rev = g_slist_remove(rev, child);
677         }
678     } else {
679         g_slist_free(rev);
680     }
682     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
683                      _("Raise"));
686 void sp_selection_raise_to_top()
688     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
689     if (desktop == NULL)
690         return;
692     SPDocument *document = sp_desktop_document(desktop);
693     Inkscape::Selection *selection = sp_desktop_selection(desktop);
695     if (selection->isEmpty()) {
696         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
697         return;
698     }
700     GSList const *items = (GSList *) selection->itemList();
702     SPGroup const *group = sp_item_list_common_parent_group(items);
703     if (!group) {
704         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
705         return;
706     }
708     GSList *rl = g_slist_copy((GSList *) selection->reprList());
709     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
711     for (GSList *l = rl; l != NULL; l = l->next) {
712         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
713         repr->setPosition(-1);
714     }
716     g_slist_free(rl);
718     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
719                      _("Raise to top"));
722 void
723 sp_selection_lower()
725     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
726     if (desktop == NULL)
727         return;
729     Inkscape::Selection *selection = sp_desktop_selection(desktop);
731     GSList const *items = (GSList *) selection->itemList();
732     if (!items) {
733         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
734         return;
735     }
737     SPGroup const *group = sp_item_list_common_parent_group(items);
738     if (!group) {
739         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
740         return;
741     }
743     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
745     // find out the common bbox of the selected items
746     NR::Maybe<NR::Rect> selected = enclose_items(items);
748     /* construct direct-ordered list of selected children */
749     GSList *rev = g_slist_copy((GSList *) items);
750     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
751     rev = g_slist_reverse(rev);
753     // for all objects in the selection (starting from top)
754     if (selected) {
755         while (rev) {
756             SPObject *child = SP_OBJECT(rev->data);
757             // for each selected object, find the prev sibling
758             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
759                 // if the sibling is an item AND overlaps our selection,
760                 if (SP_IS_ITEM(newref)) {
761                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
762                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
763                         // AND if it's not one of our selected objects,
764                         if (!g_slist_find((GSList *) items, newref)) {
765                             // move the selected object before that sibling
766                             SPObject *put_after = prev_sibling(newref);
767                             if (put_after)
768                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
769                             else
770                                 SP_OBJECT_REPR(child)->setPosition(0);
771                         }
772                         break;
773                     }
774                 }
775             }
776             rev = g_slist_remove(rev, child);
777         }
778     } else {
779         g_slist_free(rev);
780     }
782     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
783                      _("Lower"));
786 void sp_selection_lower_to_bottom()
788     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
789     if (desktop == NULL)
790         return;
792     SPDocument *document = sp_desktop_document(desktop);
793     Inkscape::Selection *selection = sp_desktop_selection(desktop);
795     if (selection->isEmpty()) {
796         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
797         return;
798     }
800     GSList const *items = (GSList *) selection->itemList();
802     SPGroup const *group = sp_item_list_common_parent_group(items);
803     if (!group) {
804         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
805         return;
806     }
808     GSList *rl;
809     rl = g_slist_copy((GSList *) selection->reprList());
810     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
811     rl = g_slist_reverse(rl);
813     for (GSList *l = rl; l != NULL; l = l->next) {
814         gint minpos;
815         SPObject *pp, *pc;
816         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
817         pp = document->getObjectByRepr(sp_repr_parent(repr));
818         minpos = 0;
819         g_assert(SP_IS_GROUP(pp));
820         pc = sp_object_first_child(pp);
821         while (!SP_IS_ITEM(pc)) {
822             minpos += 1;
823             pc = pc->next;
824         }
825         repr->setPosition(minpos);
826     }
828     g_slist_free(rl);
830     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
831                      _("Lower to bottom"));
834 void
835 sp_undo(SPDesktop *desktop, SPDocument *)
837         if (!sp_document_undo(sp_desktop_document(desktop)))
838             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
841 void
842 sp_redo(SPDesktop *desktop, SPDocument *)
844         if (!sp_document_redo(sp_desktop_document(desktop)))
845             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
848 void sp_selection_cut()
850     sp_selection_copy();
851     sp_selection_delete();
854 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
856     SPGradient *ref = gradient;
858     while (ref) {
859         // climb up the refs, copying each one in the chain
860         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
861         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
863         ref = ref->ref->getObject();
864     }
867 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
869     SPPattern *ref = pattern;
871     while (ref) {
872         // climb up the refs, copying each one in the chain
873         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
874         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
876         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
877         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
878             if (!SP_IS_ITEM (child))
879                 continue;
880             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
881         }
883         ref = ref->ref->getObject();
884     }
887 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
889     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
890     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
894 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items, Inkscape::XML::Document* xml_doc)
896     SPItem *path = sp_textpath_get_path_item (tp);
897     if (!path)
898         return;
899     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
900         return;
901     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
902     *defs_clip = g_slist_prepend (*defs_clip, repr);
905 /**
906  * Copies things like patterns, markers, gradients, etc.
907  */
908 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc)
910     SPStyle *style = SP_OBJECT_STYLE (item);
912     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
913         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
914         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
915             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
916         if (SP_IS_PATTERN (server))
917             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
918     }
920     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
921         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
922         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
923             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
924         if (SP_IS_PATTERN (server))
925             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
926     }
928     // For shapes, copy all of the shape's markers into defs_clip
929     if (SP_IS_SHAPE (item)) {
930         SPShape *shape = SP_SHAPE (item);
931         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
932             if (shape->marker[i]) {
933                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
934             }
935         }
936     }
938     if (SP_IS_TEXT_TEXTPATH (item)) {
939         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
940     }
942     if (item->clip_ref->getObject()) {
943         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
944     }
946     if (item->mask_ref->getObject()) {
947         SPObject *mask = item->mask_ref->getObject();
948         sp_copy_single (defs_clip, mask, xml_doc);
949         // recurse into the mask for its gradients etc.
950         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
951             if (SP_IS_ITEM(o))
952                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
953         }
954     }
956     if (style->filter.href->getObject()) {
957         SPObject *filter = style->filter.href->getObject();
958         if (SP_IS_FILTER(filter)) {
959             sp_copy_single (defs_clip, filter, xml_doc);
960         }
961     }
963     // recurse
964     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
965         if (SP_IS_ITEM(o))
966             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
967     }
970 /**
971  * \pre item != NULL
972  */
973 SPCSSAttr *
974 take_style_from_item (SPItem *item)
976     // write the complete cascaded style, context-free
977     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
978     if (css == NULL)
979         return NULL;
981     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
982         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
983         // if this is a text with exactly one tspan child, merge the style of that tspan as well
984         // If this is a group, merge the style of its topmost (last) child with style
985         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
986             if (SP_OBJECT_STYLE (last_element) != NULL) {
987                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
988                 if (temp) {
989                     sp_repr_css_merge (css, temp);
990                     sp_repr_css_attr_unref (temp);
991                 }
992                 break;
993             }
994         }
995     }
996     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
997         // do not copy text properties from non-text objects, it's confusing
998         css = sp_css_attr_unset_text (css);
999     }
1001     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1002     double ex = NR::expansion(sp_item_i2doc_affine(item));
1003     if (ex != 1.0) {
1004         css = sp_css_attr_scale (css, ex);
1005     }
1007     return css;
1011 void sp_selection_copy()
1013     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1014     if (desktop == NULL)
1015         return;
1017     if (!clipboard_document) {
1018         clipboard_document = new Inkscape::XML::SimpleDocument();
1019     }
1021     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1023     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1024         sp_dropper_context_copy(desktop->event_context);
1025         return; // copied color under cursor, nothing else to do
1026     }
1028     // check if something is selected
1029     if (selection->isEmpty()) {
1030         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1031         return;
1032     }
1034     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1036     // 0. Copy text to system clipboard
1037     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1038     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1039     Glib::ustring text;
1040     if (tools_isactive (desktop, TOOLS_TEXT)) {
1041         text = sp_text_get_selected_text(desktop->event_context);
1042     }
1044     if (text.empty()) {
1045         guint texts = 0;
1046         for (GSList *i = (GSList *) items; i; i = i->next) {
1047             SPItem *item = SP_ITEM (i->data);
1048             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1049                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1050                     text += " ";
1051                 gchar *this_text = sp_te_get_string_multiline (item);
1052                 if (this_text) {
1053                     text += this_text;
1054                     g_free(this_text);
1055                 }
1056                 texts++;
1057             }
1058         }
1059     }
1060     if (!text.empty()) {
1061         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1062         refClipboard->set_text(text);
1063     }
1065     // clear old defs clipboard
1066     while (defs_clipboard) {
1067         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1068         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1069     }
1071     // clear style clipboard
1072     if (style_clipboard) {
1073         sp_repr_css_attr_unref (style_clipboard);
1074         style_clipboard = NULL;
1075     }
1077     //clear main clipboard
1078     while (clipboard) {
1079         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1080         clipboard = g_slist_remove(clipboard, clipboard->data);
1081     }
1083     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1085     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1086         SPStyle *const query = sp_style_new(SP_ACTIVE_DOCUMENT);
1087         if (sp_desktop_query_style_all (desktop, query)) {
1088             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1089             if (css != NULL) {
1090                 // clear style clipboard
1091                 if (style_clipboard) {
1092                     sp_repr_css_attr_unref (style_clipboard);
1093                     style_clipboard = NULL;
1094                 }
1095                 //sp_repr_css_print (css);
1096                 style_clipboard = css;
1097             }
1098         }
1099         sp_style_unref(query);
1100     }
1102     size_clipboard = selection->bounds();
1104     g_slist_free ((GSList *) items);
1107 void sp_selection_paste(bool in_place)
1109     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1111     if (desktop == NULL) {
1112         return;
1113     }
1115     SPDocument *document = sp_desktop_document(desktop);
1117     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1118         return;
1119     }
1121     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1123     if (tools_isactive (desktop, TOOLS_TEXT)) {
1124         if (sp_text_paste_inline(desktop->event_context))
1125             return; // pasted from system clipboard into text, nothing else to do
1126     }
1128     // check if something is in the clipboard
1129     if (clipboard == NULL) {
1130         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1131         return;
1132     }
1134     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1135     // add pasted objects to selection
1136     selection->setReprList((GSList const *) copied);
1137     g_slist_free (copied);
1139     if (!in_place) {
1140         sp_document_ensure_up_to_date(document);
1142         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1143         NR::Point m( desktop->point() );
1144         if (sel_bbox) {
1145             m -= sel_bbox->midpoint();
1146         }
1148         /* Snap the offset of the new item(s) to the grid */
1149         SnapManager &sm = desktop->namedview->snap_manager;
1150         SnapManager::SnapperList gs = sm.getGridSnappers();
1151         m = sm.freeSnapAlways(Inkscape::Snapper::SNAP_POINT, m, NULL, gs).getPoint();
1152         sp_selection_move_relative(selection, m);
1153     }
1155     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1156                      _("Paste"));
1159 void sp_selection_paste_style()
1161     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1162     if (desktop == NULL) return;
1164     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1166     // check if something is in the clipboard
1167     if (clipboard == NULL) {
1168         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1169         return;
1170     }
1172     // check if something is selected
1173     if (selection->isEmpty()) {
1174         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1175         return;
1176     }
1178     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1180     sp_desktop_set_style (desktop, style_clipboard);
1182     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1183                      _("Paste style"));
1186 void sp_selection_paste_size (bool apply_x, bool apply_y)
1188     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1189     if (desktop == NULL) return;
1191     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1193     // check if something is in the clipboard
1194     if (!size_clipboard) {
1195         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1196         return;
1197     }
1199     // check if something is selected
1200     if (selection->isEmpty()) {
1201         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1202         return;
1203     }
1205     NR::Maybe<NR::Rect> current = selection->bounds();
1206     if ( !current || current->isEmpty() ) {
1207         return;
1208     }
1210     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1211     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1213     sp_selection_scale_relative (selection, current->midpoint(),
1214                                  NR::scale(
1215                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1216                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1218     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1219                      _("Paste size"));
1222 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1224     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1225     if (desktop == NULL) return;
1227     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1229     // check if something is in the clipboard
1230     if ( !size_clipboard ) {
1231         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1232         return;
1233     }
1235     // check if something is selected
1236     if (selection->isEmpty()) {
1237         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1238         return;
1239     }
1241     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1242         SPItem *item = SP_ITEM(l->data);
1244         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1245         if ( !current || current->isEmpty() ) {
1246             continue;
1247         }
1249         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1250         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1252         sp_item_scale_rel (item,
1253                                  NR::scale(
1254                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1255                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1257     }
1259     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1260                      _("Paste size separately"));
1263 void sp_selection_to_next_layer ()
1265     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1267     Inkscape::Selection *selection = sp_desktop_selection(dt);
1269     // check if something is selected
1270     if (selection->isEmpty()) {
1271         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1272         return;
1273     }
1275     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1277     bool no_more = false; // Set to true, if no more layers above
1278     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1279     if (next) {
1280         GSList *temp_clip = NULL;
1281         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
1282         sp_selection_delete_impl (items);
1283         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1284         GSList *copied;
1285         if(next) {
1286             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1287         } else {
1288             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1289             no_more = true;
1290         }
1291         selection->setReprList((GSList const *) copied);
1292         g_slist_free (copied);
1293         if (temp_clip) g_slist_free (temp_clip);
1294         if (next) dt->setCurrentLayer(next);
1295         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1296                          _("Raise to next layer"));
1297     } else {
1298         no_more = true;
1299     }
1301     if (no_more) {
1302         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1303     }
1305     g_slist_free ((GSList *) items);
1308 void sp_selection_to_prev_layer ()
1310     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1312     Inkscape::Selection *selection = sp_desktop_selection(dt);
1314     // check if something is selected
1315     if (selection->isEmpty()) {
1316         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1317         return;
1318     }
1320     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1322     bool no_more = false; // Set to true, if no more layers below
1323     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1324     if (next) {
1325         GSList *temp_clip = NULL;
1326         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
1327         sp_selection_delete_impl (items);
1328         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1329         GSList *copied;
1330         if(next) {
1331             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1332         } else {
1333             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1334             no_more = true;
1335         }
1336         selection->setReprList((GSList const *) copied);
1337         g_slist_free (copied);
1338         if (temp_clip) g_slist_free (temp_clip);
1339         if (next) dt->setCurrentLayer(next);
1340         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1341                          _("Lower to previous layer"));
1342     } else {
1343         no_more = true;
1344     }
1346     if (no_more) {
1347         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1348     }
1350     g_slist_free ((GSList *) items);
1353 bool
1354 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1356     bool contains_original = false;
1357     bool is_use = SP_IS_USE(item);
1358     SPItem *item_use = item;
1359     SPItem *item_use_first = item;
1360     while (is_use && item_use && !contains_original)
1361     {
1362         item_use = sp_use_get_original (SP_USE(item_use));
1363         contains_original |= selection->includes(item_use);
1364         if (item_use == item_use_first)
1365             break;
1366         is_use = SP_IS_USE(item_use);
1367     }   
1368     return contains_original;
1372 bool
1373 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1375     bool clone_with_original = false;
1376     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1377         SPItem *item = SP_ITEM(l->data);
1378         clone_with_original |= selection_contains_original(item, selection);
1379         if (clone_with_original) 
1380             break;
1381     }
1382     return clone_with_original;
1386 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1387 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1388 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1389 that case, items are already in the new position, but the repr is in the old, and this function
1390 then simply updates the repr from item->transform.
1391  */
1392 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1394     if (selection->isEmpty())
1395         return;
1397     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1398         SPItem *item = SP_ITEM(l->data);
1400         NR::Point old_center(0,0);
1401         if (set_i2d && item->isCenterSet())
1402             old_center = item->getCenter();
1404 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1405          At the time of writing, this is the only place to re-enable. */
1406         sp_item_update_cns(*item, selection->desktop());
1407 #endif
1409         // we're moving both a clone and its original or any ancestor in clone chain?
1410         bool transform_clone_with_original = selection_contains_original(item, selection);
1411         // ...both a text-on-path and its path?
1412         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)))) ));
1413         // ...both a flowtext and its frame?
1414         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)
1415         // ...both an offset and its source?
1416         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1417        
1418         // If we're moving a connector, we want to detach it
1419         // from shapes that aren't part of the selection, but
1420         // leave it attached if they are
1421         if (cc_item_is_connector(item)) {
1422             SPItem *attItem[2];
1423             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1424             
1425             for (int n = 0; n < 2; ++n) {
1426                 if (!selection->includes(attItem[n])) {
1427                     sp_conn_end_detach(item, n);
1428                 }
1429             }
1430         }
1431         
1432         // "clones are unmoved when original is moved" preference
1433         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1434         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1435         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1437         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1438         // transform of its original and respond to it itself. Without this, a clone is doubly
1439         // transformed, very unintuitive.
1440       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1441       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1442       // Same for linked offset if we are also moving its source: do not move it.
1443         if (transform_textpath_with_path || transform_offset_with_source) {
1444                 // restore item->transform field from the repr, in case it was changed by seltrans
1445             sp_object_read_attr (SP_OBJECT (item), "transform");
1447         } else if (transform_flowtext_with_frame) {
1448             // apply the inverse of the region's transform to the <use> so that the flow remains
1449             // the same (even though the output itself gets transformed)
1450             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1451                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1452                     continue;
1453                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1454                     if (!SP_IS_USE(use)) continue;
1455                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1456                 }
1457             }
1458         } else if (transform_clone_with_original) {
1459             // We are transforming a clone along with its original. The below matrix juggling is
1460             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1461             // transform and its move compensation are both cancelled out.
1463             // restore item->transform field from the repr, in case it was changed by seltrans
1464             sp_object_read_attr (SP_OBJECT (item), "transform");
1466             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1467             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1468             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1469             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1470             NR::Matrix result = t_inv * item->transform * t;
1472             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1473                 // we need to cancel out the move compensation, too
1475                 // find out the clone move, same as in sp_use_move_compensate
1476                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1477                 NR::Matrix clone_move = parent.inverse() * t * parent;
1479                 if (prefs_parallel) {
1480                     NR::Matrix move = result * clone_move * t_inv;
1481                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1483                 } else if (prefs_unmoved) {
1484                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1485                     //    clone_move = NR::identity();
1486                     NR::Matrix move = result * clone_move;
1487                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1488                 }
1490             } else {
1491                 // just apply the result
1492                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1493             }
1495         } else {
1496             if (set_i2d) {
1497                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1498             }
1499             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1500         }
1502         // if we're moving the actual object, not just updating the repr, we can transform the
1503         // center by the same matrix (only necessary for non-translations)
1504         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1505             item->setCenter(old_center * affine);
1506             SP_OBJECT(item)->updateRepr();
1507         }
1508     }
1511 void sp_selection_remove_transform()
1513     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1514     if (desktop == NULL)
1515         return;
1517     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1519     GSList const *l = (GSList *) selection->reprList();
1520     while (l != NULL) {
1521         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1522         l = l->next;
1523     }
1525     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1526                      _("Remove transform"));
1529 void
1530 sp_selection_scale_absolute(Inkscape::Selection *selection,
1531                             double const x0, double const x1,
1532                             double const y0, double const y1)
1534     if (selection->isEmpty())
1535         return;
1537     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1538     if ( !bbox || bbox->isEmpty() ) {
1539         return;
1540     }
1542     NR::translate const p2o(-bbox->min());
1544     NR::scale const newSize(x1 - x0,
1545                             y1 - y0);
1546     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1547     NR::translate const o2n(x0, y0);
1548     NR::Matrix const final( p2o * scale * o2n );
1550     sp_selection_apply_affine(selection, final);
1554 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1556     if (selection->isEmpty())
1557         return;
1559     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1561     if ( !bbox || bbox->isEmpty() ) {
1562         return;
1563     }
1565     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1566     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1567          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1568     {
1569         return;
1570     }
1572     NR::translate const n2d(-align);
1573     NR::translate const d2n(align);
1574     NR::Matrix const final( n2d * scale * d2n );
1575     sp_selection_apply_affine(selection, final);
1578 void
1579 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1581     NR::translate const d2n(center);
1582     NR::translate const n2d(-center);
1583     NR::rotate const rotate(rotate_degrees(angle_degrees));
1584     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1585     sp_selection_apply_affine(selection, final);
1588 void
1589 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1591     NR::translate const d2n(align);
1592     NR::translate const n2d(-align);
1593     NR::Matrix const skew(1, dy,
1594                           dx, 1,
1595                           0, 0);
1596     NR::Matrix const final( n2d * skew * d2n );
1597     sp_selection_apply_affine(selection, final);
1600 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1602     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1605 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1607     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1611 /**
1612  * \brief sp_selection_rotate_90
1613  *
1614  * This function rotates selected objects 90 degrees clockwise.
1615  *
1616  */
1618 void sp_selection_rotate_90_cw()
1620     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1622     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1624     if (selection->isEmpty())
1625         return;
1627     GSList const *l = selection->itemList();
1628     NR::rotate const rot_neg_90(NR::Point(0, -1));
1629     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1630         SPItem *item = SP_ITEM(l2->data);
1631         sp_item_rotate_rel(item, rot_neg_90);
1632     }
1634     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1635                      _("Rotate 90&#176; CW"));
1639 /**
1640  * \brief sp_selection_rotate_90_ccw
1641  *
1642  * This function rotates selected objects 90 degrees counter-clockwise.
1643  *
1644  */
1646 void sp_selection_rotate_90_ccw()
1648     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1650     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1652     if (selection->isEmpty())
1653         return;
1655     GSList const *l = selection->itemList();
1656     NR::rotate const rot_neg_90(NR::Point(0, 1));
1657     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1658         SPItem *item = SP_ITEM(l2->data);
1659         sp_item_rotate_rel(item, rot_neg_90);
1660     }
1662     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1663                      _("Rotate 90&#176; CCW"));
1666 void
1667 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1669     if (selection->isEmpty())
1670         return;
1672     NR::Maybe<NR::Point> center = selection->center();
1673     if (!center) {
1674         return;
1675     }
1677     sp_selection_rotate_relative(selection, *center, angle_degrees);
1679     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1680                            ( ( angle_degrees > 0 )
1681                              ? "selector:rotate:ccw"
1682                              : "selector:rotate:cw" ), 
1683                            SP_VERB_CONTEXT_SELECT, 
1684                            _("Rotate"));
1687 /**
1688 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1689 */
1690 void
1691 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1693     if (selection->isEmpty())
1694         return;
1696     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1697     NR::Maybe<NR::Point> center = selection->center();
1699     if ( !bbox || !center ) {
1700         return;
1701     }
1703     gdouble const zoom = selection->desktop()->current_zoom();
1704     gdouble const zmove = angle / zoom;
1705     gdouble const r = NR::L2(bbox->max() - *center);
1707     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1709     sp_selection_rotate_relative(selection, *center, zangle);
1711     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1712                            ( (angle > 0)
1713                              ? "selector:rotate:ccw"
1714                              : "selector:rotate:cw" ),
1715                            SP_VERB_CONTEXT_SELECT, 
1716                            _("Rotate by pixels"));
1719 void
1720 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1722     if (selection->isEmpty())
1723         return;
1725     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1726     if (!bbox) {
1727         return;
1728     }
1730     NR::Point const center(bbox->midpoint());
1732     // you can't scale "do nizhe pola" (below zero)
1733     double const max_len = bbox->maxExtent();
1734     if ( max_len + grow <= 1e-3 ) {
1735         return;
1736     }
1738     double const times = 1.0 + grow / max_len;
1739     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1741     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1742                            ( (grow > 0)
1743                              ? "selector:scale:larger"
1744                              : "selector:scale:smaller" ),
1745                            SP_VERB_CONTEXT_SELECT,
1746                            _("Scale"));
1749 void
1750 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1752     sp_selection_scale(selection,
1753                        grow_pixels / selection->desktop()->current_zoom());
1756 void
1757 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1759     if (selection->isEmpty())
1760         return;
1762     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1764     if (!sel_bbox) {
1765         return;
1766     }
1768     NR::Point const center(sel_bbox->midpoint());
1769     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1770     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1771                      _("Scale by whole factor"));
1774 void
1775 sp_selection_move(gdouble dx, gdouble dy)
1777     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1778     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1779     if (selection->isEmpty()) {
1780         return;
1781     }
1783     sp_selection_move_relative(selection, dx, dy);
1785     if (dx == 0) {
1786         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1787                                _("Move vertically"));
1788     } else if (dy == 0) {
1789         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1790                                _("Move horizontally"));
1791     } else {
1792         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1793                          _("Move"));
1794     }
1797 void
1798 sp_selection_move_screen(gdouble dx, gdouble dy)
1800     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1802     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1803     if (selection->isEmpty()) {
1804         return;
1805     }
1807     // same as sp_selection_move but divide deltas by zoom factor
1808     gdouble const zoom = desktop->current_zoom();
1809     gdouble const zdx = dx / zoom;
1810     gdouble const zdy = dy / zoom;
1811     sp_selection_move_relative(selection, zdx, zdy);
1813     if (dx == 0) {
1814         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1815                                _("Move vertically by pixels"));
1816     } else if (dy == 0) {
1817         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1818                                _("Move horizontally by pixels"));
1819     } else {
1820         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1821                          _("Move"));
1822     }
1825 namespace {
1827 template <typename D>
1828 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1829                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1831 template <typename D>
1832 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1833                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1835 struct Forward {
1836     typedef SPObject *Iterator;
1838     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1839     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1840     static void dispose(Iterator i) {}
1842     static SPObject *object(Iterator i) { return i; }
1843     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1844 };
1846 struct Reverse {
1847     typedef GSList *Iterator;
1849     static Iterator children(SPObject *o) {
1850         return make_list(o->firstChild(), NULL);
1851     }
1852     static Iterator siblings_after(SPObject *o) {
1853         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1854     }
1855     static void dispose(Iterator i) {
1856         g_slist_free(i);
1857     }
1859     static SPObject *object(Iterator i) {
1860         return reinterpret_cast<SPObject *>(i->data);
1861     }
1862     static Iterator next(Iterator i) { return i->next; }
1864 private:
1865     static GSList *make_list(SPObject *object, SPObject *limit) {
1866         GSList *list=NULL;
1867         while ( object != limit ) {
1868             list = g_slist_prepend(list, object);
1869             object = SP_OBJECT_NEXT(object);
1870         }
1871         return list;
1872     }
1873 };
1877 void
1878 sp_selection_item_next(void)
1880     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1881     g_return_if_fail(desktop != NULL);
1882     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1884     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1885     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1886     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1888     SPObject *root;
1889     if (PREFS_SELECTION_ALL != inlayer) {
1890         root = selection->activeContext();
1891     } else {
1892         root = desktop->currentRoot();
1893     }
1895     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1897     if (item) {
1898         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1899         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1900             scroll_to_show_item(desktop, item);
1901         }
1902     }
1905 void
1906 sp_selection_item_prev(void)
1908     SPDocument *document = SP_ACTIVE_DOCUMENT;
1909     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1910     g_return_if_fail(document != NULL);
1911     g_return_if_fail(desktop != NULL);
1912     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1914     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1915     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1916     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1918     SPObject *root;
1919     if (PREFS_SELECTION_ALL != inlayer) {
1920         root = selection->activeContext();
1921     } else {
1922         root = desktop->currentRoot();
1923     }
1925     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1927     if (item) {
1928         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1929         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1930             scroll_to_show_item(desktop, item);
1931         }
1932     }
1935 namespace {
1937 template <typename D>
1938 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1939                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1941     SPObject *current=root;
1942     while (items) {
1943         SPItem *item=SP_ITEM(items->data);
1944         if ( root->isAncestorOf(item) &&
1945              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1946         {
1947             current = item;
1948             break;
1949         }
1950         items = items->next;
1951     }
1953     GSList *path=NULL;
1954     while ( current != root ) {
1955         path = g_slist_prepend(path, current);
1956         current = SP_OBJECT_PARENT(current);
1957     }
1959     SPItem *next;
1960     // first, try from the current object
1961     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1962     g_slist_free(path);
1964     if (!next) { // if we ran out of objects, start over at the root
1965         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1966     }
1968     return next;
1971 template <typename D>
1972 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1973                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1975     typename D::Iterator children;
1976     typename D::Iterator iter;
1978     SPItem *found=NULL;
1980     if (path) {
1981         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1982         g_assert(SP_OBJECT_PARENT(object) == root);
1983         if (desktop->isLayer(object)) {
1984             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1985         }
1986         iter = children = D::siblings_after(object);
1987     } else {
1988         iter = children = D::children(root);
1989     }
1991     while ( iter && !found ) {
1992         SPObject *object=D::object(iter);
1993         if (desktop->isLayer(object)) {
1994             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1995                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1996             }
1997         } else if ( SP_IS_ITEM(object) &&
1998                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1999                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2000                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2001                     !desktop->isLayer(SP_ITEM(object)) )
2002         {
2003             found = SP_ITEM(object);
2004         }
2005         iter = D::next(iter);
2006     }
2008     D::dispose(children);
2010     return found;
2015 /**
2016  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2017  * \a item.
2018  */
2019 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2021     NR::Rect dbox = desktop->get_display_area();
2022     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2024     if ( sbox && dbox.contains(*sbox) == false ) {
2025         NR::Point const s_dt = sbox->midpoint();
2026         NR::Point const s_w = desktop->d2w(s_dt);
2027         NR::Point const d_dt = dbox.midpoint();
2028         NR::Point const d_w = desktop->d2w(d_dt);
2029         NR::Point const moved_w( d_w - s_w );
2030         gint const dx = (gint) moved_w[X];
2031         gint const dy = (gint) moved_w[Y];
2032         desktop->scroll_world(dx, dy);
2033     }
2037 void
2038 sp_selection_clone()
2040     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2041     if (desktop == NULL)
2042         return;
2044     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2046     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2048     // check if something is selected
2049     if (selection->isEmpty()) {
2050         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2051         return;
2052     }
2054     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2055   
2056     selection->clear();
2057   
2058     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2059     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2061     GSList *newsel = NULL;
2062  
2063     while (reprs) {
2064         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2065         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2067         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2068         sp_repr_set_attr(clone, "x", "0");
2069         sp_repr_set_attr(clone, "y", "0");
2070         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2072         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2073         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2074         
2075         // add the new clone to the top of the original's parent
2076         parent->appendChild(clone);
2078         newsel = g_slist_prepend(newsel, clone);
2079         reprs = g_slist_remove(reprs, sel_repr);
2080         Inkscape::GC::release(clone);
2081     }
2082     
2083     // TRANSLATORS: only translate "string" in "context|string".
2084     // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2085     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2086                      Q_("action|Clone"));
2088     selection->setReprList(newsel);
2089  
2090     g_slist_free(newsel);
2093 void
2094 sp_selection_unlink()
2096     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2097     if (!desktop)
2098         return;
2100     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2102     if (selection->isEmpty()) {
2103         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2104         return;
2105     }
2107     // Get a copy of current selection.
2108     GSList *new_select = NULL;
2109     bool unlinked = false;
2110     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2111          items != NULL;
2112          items = items->next)
2113     {
2114         SPItem *use = (SPItem *) items->data;
2116         if (!SP_IS_USE(use)) {
2117             // keep the non-yse item in the new selection
2118             new_select = g_slist_prepend(new_select, use);
2119             continue;
2120         }
2122         SPItem *unlink = sp_use_unlink(SP_USE(use));
2123         unlinked = true;
2124         // Add ungrouped items to the new selection.
2125         new_select = g_slist_prepend(new_select, unlink);
2126     }
2128     if (new_select) { // set new selection
2129         selection->clear();
2130         selection->setList(new_select);
2131         g_slist_free(new_select);
2132     }
2133     if (!unlinked) {
2134         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2135     }
2137     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2138                      _("Unlink clone"));
2141 void
2142 sp_select_clone_original()
2144     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2145     if (desktop == NULL)
2146         return;
2148     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2150     SPItem *item = selection->singleItem();
2152     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.");
2154     // Check if other than two objects are selected
2155     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2156         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2157         return;
2158     }
2160     SPItem *original = NULL;
2161     if (SP_IS_USE(item)) {
2162         original = sp_use_get_original (SP_USE(item));
2163     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2164         original = sp_offset_get_source (SP_OFFSET(item));
2165     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2166         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2167     } else if (SP_IS_FLOWTEXT(item)) {
2168         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2169     } else { // it's an object that we don't know what to do with
2170         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2171         return;
2172     }
2174     if (!original) {
2175         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2176         return;
2177     }
2179     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2180         if (SP_IS_DEFS (o)) {
2181             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2182             return;
2183         }
2184     }
2186     if (original) {
2187         selection->clear();
2188         selection->set(original);
2189         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2190             scroll_to_show_item(desktop, original);
2191         }
2192     }
2195 void
2196 sp_selection_tile(bool apply)
2198     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2199     if (desktop == NULL)
2200         return;
2202     SPDocument *doc = sp_desktop_document(desktop);
2203     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2205     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2207     // check if something is selected
2208     if (selection->isEmpty()) {
2209         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2210         return;
2211     }
2213     sp_document_ensure_up_to_date(doc);
2214     NR::Maybe<NR::Rect> r = selection->bounds();
2215     if ( !r || r->isEmpty() ) {
2216         return;
2217     }
2219     // calculate the transform to be applied to objects to move them to 0,0
2220     NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2221     move_p[NR::Y] = -move_p[NR::Y];
2222     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2224     GSList *items = g_slist_copy((GSList *) selection->itemList());
2226     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2228     // bottommost object, after sorting
2229     SPObject *parent = SP_OBJECT_PARENT (items->data);
2231     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2233     // remember the position of the first item
2234     gint pos = SP_OBJECT_REPR (items->data)->position();
2236     // create a list of duplicates
2237     GSList *repr_copies = NULL;
2238     for (GSList *i = items; i != NULL; i = i->next) {
2239         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2240         repr_copies = g_slist_prepend (repr_copies, dup);
2241     }
2243     NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2245     if (apply) {
2246         // delete objects so that their clones don't get alerted; this object will be restored shortly
2247         for (GSList *i = items; i != NULL; i = i->next) {
2248             SPObject *item = SP_OBJECT (i->data);
2249             item->deleteObject (false);
2250         }
2251     }
2253     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2254     // without disturbing clones.
2255     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2256     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2257     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2259     const gchar *pat_id = pattern_tile (repr_copies, bounds, doc,
2260                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X], r->max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2262     // restore compensation setting
2263     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2265     if (apply) {
2266         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2267         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2269         NR::Point min = bounds.min() * parent_transform.inverse();
2270         NR::Point max = bounds.max() * parent_transform.inverse();
2272         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2273         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2274         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2275         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2277         // restore parent and position
2278         SP_OBJECT_REPR (parent)->appendChild(rect);
2279         rect->setPosition(pos > 0 ? pos : 0);
2280         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2282         Inkscape::GC::release(rect);
2284         selection->clear();
2285         selection->set(rectangle);
2286     }
2288     g_slist_free (items);
2290     sp_document_done (doc, SP_VERB_EDIT_TILE, 
2291                       _("Objects to pattern"));
2294 void
2295 sp_selection_untile()
2297     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2298     if (desktop == NULL)
2299         return;
2301     SPDocument *doc = sp_desktop_document(desktop);
2302     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2304     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2306     // check if something is selected
2307     if (selection->isEmpty()) {
2308         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2309         return;
2310     }
2312     GSList *new_select = NULL;
2314     bool did = false;
2316     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2317          items != NULL;
2318          items = items->next) {
2320         SPItem *item = (SPItem *) items->data;
2322         SPStyle *style = SP_OBJECT_STYLE (item);
2324         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2325             continue;
2327         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2329         if (!SP_IS_PATTERN(server))
2330             continue;
2332         did = true;
2334         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2336         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2337         pat_transform *= item->transform;
2339         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2340             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2341             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2343            // FIXME: relink clones to the new canvas objects
2344            // use SPObject::setid when mental finishes it to steal ids of
2346             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2347             sp_document_ensure_up_to_date (doc);
2349             NR::Matrix transform( i->transform * pat_transform );
2350             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2352             new_select = g_slist_prepend(new_select, i);
2353         }
2355         SPCSSAttr *css = sp_repr_css_attr_new ();
2356         sp_repr_css_set_property (css, "fill", "none");
2357         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2358     }
2360     if (!did) {
2361         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2362     } else {
2363         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2364                          _("Pattern to objects"));
2365         selection->setList(new_select);
2366     }
2369 void
2370 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2372     if (selection->isEmpty()) {
2373         return;
2374     }
2376     const GSList * reprlst = selection->reprList();
2377     bool filename_search = TRUE;
2378     bool xdpi_search = TRUE;
2379     bool ydpi_search = TRUE;
2381     for(; reprlst != NULL &&
2382             filename_search &&
2383             xdpi_search &&
2384             ydpi_search;
2385         reprlst = reprlst->next) {
2386         const gchar * dpi_string;
2387         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2389         if (filename_search) {
2390             *filename = repr->attribute("inkscape:export-filename");
2391             if (*filename != NULL)
2392                 filename_search = FALSE;
2393         }
2395         if (xdpi_search) {
2396             dpi_string = NULL;
2397             dpi_string = repr->attribute("inkscape:export-xdpi");
2398             if (dpi_string != NULL) {
2399                 *xdpi = atof(dpi_string);
2400                 xdpi_search = FALSE;
2401             }
2402         }
2404         if (ydpi_search) {
2405             dpi_string = NULL;
2406             dpi_string = repr->attribute("inkscape:export-ydpi");
2407             if (dpi_string != NULL) {
2408                 *ydpi = atof(dpi_string);
2409                 ydpi_search = FALSE;
2410             }
2411         }
2412     }
2415 void
2416 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2418     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2419     const gchar * dpi_string;
2421     *filename = repr->attribute("inkscape:export-filename");
2423     dpi_string = NULL;
2424     dpi_string = repr->attribute("inkscape:export-xdpi");
2425     if (dpi_string != NULL) {
2426         *xdpi = atof(dpi_string);
2427     }
2429     dpi_string = NULL;
2430     dpi_string = repr->attribute("inkscape:export-ydpi");
2431     if (dpi_string != NULL) {
2432         *ydpi = atof(dpi_string);
2433     }
2436 void
2437 sp_selection_create_bitmap_copy ()
2439     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2440     if (desktop == NULL)
2441         return;
2443     SPDocument *document = sp_desktop_document(desktop);
2444     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2446     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2448     // check if something is selected
2449     if (selection->isEmpty()) {
2450         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2451         return;
2452     }
2454     // Get the bounding box of the selection
2455     NRRect bbox;
2456     sp_document_ensure_up_to_date (document);
2457     selection->bounds(&bbox);
2458     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2459         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2460     }
2462     // List of the items to show; all others will be hidden
2463     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2465     // Sort items so that the topmost comes last
2466     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2468     // Generate a random value from the current time (you may create bitmap from the same object(s)
2469     // multiple times, and this is done so that they don't clash)
2470     GTimeVal cu;
2471     g_get_current_time (&cu);
2472     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2474     // Create the filename
2475     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2476     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2477     // digits, and a few other chars, with "_"
2478     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2479     // Build the complete path by adding document->base if set
2480     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2482     //g_print ("%s\n", filepath);
2484     // Remember parent and z-order of the topmost one
2485     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2486     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2487     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2489     // Calculate resolution
2490     double res;
2491     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2492     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2493     if (0 < prefs_res) {
2494         // If it's given explicitly in prefs, take it
2495         res = prefs_res;
2496     } else if (0 < prefs_min) {
2497         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2498         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2499     } else {
2500         float hint_xdpi = 0, hint_ydpi = 0;
2501         const char *hint_filename;
2502         // take resolution hint from the selected objects
2503         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2504         if (hint_xdpi != 0) {
2505             res = hint_xdpi;
2506         } else {
2507             // take resolution hint from the document
2508             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2509             if (hint_xdpi != 0) {
2510                 res = hint_xdpi;
2511             } else {
2512                 // if all else fails, take the default 90 dpi
2513                 res = PX_PER_IN;
2514             }
2515         }
2516     }
2518     // The width and height of the bitmap in pixels
2519     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2520     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2522     // Find out if we have to run a filter
2523     const gchar *run = NULL;
2524     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2525     if (filter) {
2526         // filter command is given;
2527         // see if we have a parameter to pass to it
2528         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2529         if (param1) {
2530             if (param1[strlen(param1) - 1] == '%') {
2531                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2532                 gchar p1[256];
2533                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2534                 // the first param is always the image filename, the second is param1
2535                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2536             } else {
2537                 // otherwise pass the param1 unchanged
2538                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2539             }
2540         } else {
2541             // run without extra parameter
2542             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2543         }
2544     }
2546     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2547     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2548     NR::Matrix t;
2550     double shift_x = bbox.x0;
2551     double shift_y = bbox.y1; 
2552     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2553         shift_x = round (shift_x);
2554         shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2555     }
2556     t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2558     // Do the export
2559     sp_export_png_file(document, filepath,
2560                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2561                    width, height, res, res,
2562                    (guint32) 0xffffff00,
2563                    NULL, NULL,
2564                    true,  /*bool force_overwrite,*/
2565                    items);
2567     g_slist_free (items);
2569     // Run filter, if any
2570     if (run) {
2571         g_print ("Running external filter: %s\n", run);
2572         system (run);
2573     }
2575     // Import the image back
2576     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2577     if (pb) {
2578         // Create the repr for the image
2579         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2580         repr->setAttribute("xlink:href", filename);
2581         repr->setAttribute("sodipodi:absref", filepath);
2582         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2583             sp_repr_set_svg_double(repr, "width", width);
2584             sp_repr_set_svg_double(repr, "height", height);
2585         } else {
2586             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2587             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2588         }
2590         // Write transform
2591         gchar *c=sp_svg_transform_write(t);
2592         repr->setAttribute("transform", c);
2593         g_free(c);
2595         // add the new repr to the parent
2596         parent->appendChild(repr);
2598         // move to the saved position
2599         repr->setPosition(pos > 0 ? pos + 1 : 1);
2601         // Set selection to the new image
2602         selection->clear();
2603         selection->add(repr);
2605         // Clean up
2606         Inkscape::GC::release(repr);
2607         gdk_pixbuf_unref (pb);
2609         // Complete undoable transaction
2610         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2611                           _("Create bitmap"));
2612     }
2614     g_free (filename);
2615     g_free (filepath);
2618 /**
2619  * \brief sp_selection_set_mask
2620  *
2621  * This function creates a mask or clipPath from selection
2622  * Two different modes:
2623  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2624  *       and is applied to current layer
2625  *  otherwise, topmost object is used as mask for other objects
2626  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2627  * 
2628  */
2629 void
2630 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2632     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2633     if (desktop == NULL)
2634         return;
2636     SPDocument *doc = sp_desktop_document(desktop);
2637     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2638     
2639     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2641     // check if something is selected
2642     bool is_empty = selection->isEmpty();
2643     if ( apply_to_layer && is_empty) {
2644         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2645         return;
2646     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2647         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2648         return;
2649     }
2651     // FIXME: temporary patch to prevent crash! 
2652     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2653     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2654     if (clone_with_original) {
2655         return; // in this version, you cannot clip/mask an object with its own clone
2656     }
2657     // /END FIXME
2658     
2659     sp_document_ensure_up_to_date(doc);
2661     GSList *items = g_slist_copy((GSList *) selection->itemList());
2662     
2663     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2665     // create a list of duplicates
2666     GSList *mask_items = NULL;
2667     GSList *apply_to_items = NULL;
2668     GSList *items_to_delete = NULL;
2669     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2670     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2671     
2672     if (apply_to_layer) {
2673         // all selected items are used for mask, which is applied to a layer
2674         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2676         for (GSList *i = items; i != NULL; i = i->next) {
2677             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2678             mask_items = g_slist_prepend (mask_items, dup);
2680             if (remove_original) {
2681                 SPObject *item = SP_OBJECT (i->data);
2682                 items_to_delete = g_slist_prepend (items_to_delete, item);
2683             }
2684         }
2685     } else if (!topmost) {
2686         // topmost item is used as a mask, which is applied to other items in a selection
2687         GSList *i = items;
2688         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2689         mask_items = g_slist_prepend (mask_items, dup);
2691         if (remove_original) {
2692             SPObject *item = SP_OBJECT (i->data);
2693             items_to_delete = g_slist_prepend (items_to_delete, item);
2694         }
2695         
2696         for (i = i->next; i != NULL; i = i->next) {
2697             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2698         }
2699     } else {
2700         GSList *i = NULL;
2701         for (i = items; NULL != i->next; i = i->next) {
2702             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2703         }
2705         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2706         mask_items = g_slist_prepend (mask_items, dup);
2708         if (remove_original) {
2709             SPObject *item = SP_OBJECT (i->data);
2710             items_to_delete = g_slist_prepend (items_to_delete, item);
2711         }
2712     }
2713     
2714     g_slist_free (items);
2715     items = NULL;
2716             
2717     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2718     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2719         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2720         // inverted object transform should be applied to a mask object,
2721         // as mask is calculated in user space (after applying transform)
2722         NR::Matrix maskTransform (item->transform.inverse());
2724         GSList *mask_items_dup = NULL;
2725         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2726             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2727             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2728         }
2730         const gchar *mask_id = NULL;
2731         if (apply_clip_path) {
2732             mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2733         } else {
2734             mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2735         }
2737         g_slist_free (mask_items_dup);
2738         mask_items_dup = NULL;
2740         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2741     }
2743     g_slist_free (mask_items);
2744     g_slist_free (apply_to_items);
2746     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2747         SPObject *item = SP_OBJECT (i->data);
2748         item->deleteObject (false);
2749     }
2750     g_slist_free (items_to_delete);
2752     if (apply_clip_path) 
2753         sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2754     else 
2755         sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2758 void sp_selection_unset_mask(bool apply_clip_path) {
2759     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2760     if (desktop == NULL)
2761         return;
2762     
2763     SPDocument *doc = sp_desktop_document(desktop);    
2764     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2765     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2767     // check if something is selected
2768     if (selection->isEmpty()) {
2769         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2770         return;
2771     }
2772     
2773     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2774     sp_document_ensure_up_to_date(doc);
2776     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2777     std::map<SPObject*,SPItem*> referenced_objects;
2778     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2779         if (remove_original) {
2780             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2781             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2782             Inkscape::URIReference *uri_ref = NULL;
2783         
2784             if (apply_clip_path) {
2785                 uri_ref = item->clip_ref;
2786             } else {
2787                 uri_ref = item->mask_ref;
2788             }
2790             // collect distinct mask object (and associate with item to apply transform)
2791             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2792                 referenced_objects[uri_ref->getObject()] = item;
2793             }
2794         }
2796         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2797     }
2799     // restore mask objects into a document
2800     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2801         SPObject *obj = (*it).first;
2802         GSList *items_to_move = NULL;
2803         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2804             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2805             items_to_move = g_slist_prepend (items_to_move, copy);
2806         }
2808         if (!obj->isReferenced()) {
2809             // delete from defs if no other object references this mask
2810             obj->deleteObject(false);
2811         }
2813         // remember parent and position of the item to which the clippath/mask was applied
2814         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2815         gint pos = SP_OBJECT_REPR((*it).second)->position();
2817         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2818             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2820             // insert into parent, restore pos
2821             parent->appendChild(repr);
2822             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2824             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2825             selection->add(repr);
2827             // transform mask, so it is moved the same spot where mask was applied
2828             NR::Matrix transform (mask_item->transform);
2829             transform *= (*it).second->transform;
2830             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2831         }
2833         g_slist_free (items_to_move);
2834     }
2836     if (apply_clip_path) 
2837         sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2838     else 
2839         sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2842 void fit_canvas_to_selection(SPDesktop *desktop) {
2843     g_return_if_fail(desktop != NULL);
2844     SPDocument *doc = sp_desktop_document(desktop);
2846     g_return_if_fail(doc != NULL);
2847     g_return_if_fail(desktop->selection != NULL);
2848     g_return_if_fail(!desktop->selection->isEmpty());
2850     NR::Maybe<NR::Rect> const bbox(desktop->selection->bounds());
2851     if (bbox && !bbox->isEmpty()) {
2852         doc->fitToRect(*bbox);
2853     }
2854 };
2856 void fit_canvas_to_drawing(SPDocument *doc) {
2857     g_return_if_fail(doc != NULL);
2859     sp_document_ensure_up_to_date(doc);
2860     SPItem const *const root = SP_ITEM(doc->root);
2861     NR::Maybe<NR::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
2862     if (bbox && !bbox->isEmpty()) {
2863         doc->fitToRect(*bbox);
2864     }
2865 };
2867 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2868     g_return_if_fail(desktop != NULL);
2869     SPDocument *doc = sp_desktop_document(desktop);
2871     g_return_if_fail(doc != NULL);
2872     g_return_if_fail(desktop->selection != NULL);
2874     if (desktop->selection->isEmpty()) {
2875         fit_canvas_to_drawing(doc);
2876     } else {
2877         fit_canvas_to_selection(desktop);
2878     }
2880     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2881                      _("Fit page to selection"));
2882 };
2884 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2885     // don't operate on layers
2886     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2887         f(SP_ITEM(root), desktop);
2888     }
2889     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2890         //don't recurse into locked layers
2891         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2892             itemtree_map(f, iter, desktop);
2893         }
2894     }
2897 static void unlock(SPItem *item, SPDesktop *desktop) {
2898     if (item->isLocked()) {
2899         item->setLocked(FALSE);
2900     }
2903 static void unhide(SPItem *item, SPDesktop *desktop) {
2904     if (desktop->itemIsHidden(item)) {
2905         item->setExplicitlyHidden(FALSE);
2906     }
2909 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2910     if (!dt) return;
2911         
2912     SPObject *root;
2913     if (layer_only) {
2914         root = dt->currentLayer();
2915     } else {
2916         root = dt->currentRoot();
2917     }
2918     
2919     itemtree_map(f, root, dt);
2922 void unlock_all(SPDesktop *dt) {
2923     process_all(&unlock, dt, true);
2926 void unlock_all_in_all_layers(SPDesktop *dt) {
2927     process_all(&unlock, dt, false);
2930 void unhide_all(SPDesktop *dt) {
2931     process_all(&unhide, dt, true);
2934 void unhide_all_in_all_layers(SPDesktop *dt) {
2935     process_all(&unhide, dt, false);
2938 /*
2939   Local Variables:
2940   mode:c++
2941   c-file-style:"stroustrup"
2942   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2943   indent-tabs-mode:nil
2944   fill-column:99
2945   End:
2946 */
2947 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :