Code

make rotations, scales and flips work with the object's rotation axis
[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"
77 using NR::X;
78 using NR::Y;
80 #include "selection-chemistry.h"
82 /* fixme: find a better place */
83 Inkscape::XML::Document *clipboard_document = NULL;
84 GSList *clipboard = NULL;
85 GSList *defs_clipboard = NULL;
86 SPCSSAttr *style_clipboard = NULL;
87 NR::Maybe<NR::Rect> size_clipboard;
89 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc);
91 /**
92  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
93  * then prepends the copy to 'clip'.
94  */
95 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
96 {
97     Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
99     // copy complete inherited style
100     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
101     sp_repr_css_set(copy, css, "style");
102     sp_repr_css_attr_unref(css);
104     // write the complete accumulated transform passed to us
105     // (we're dealing with unattached repr, so we write to its attr 
106     // instead of using sp_item_set_transform)
107     gchar *affinestr=sp_svg_transform_write(full_t);
108     copy->setAttribute("transform", affinestr);
109     g_free(affinestr);
111     *clip = g_slist_prepend(*clip, copy);
114 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip, Inkscape::XML::Document* xml_doc)
117     // Copy stuff referenced by all items to defs_clip:
118     if (defs_clip) {
119         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
120             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items, xml_doc);
121         }
122         *defs_clip = g_slist_reverse(*defs_clip);
123     }
125     // Store style:
126     if (style_clip) {
127         SPItem *item = SP_ITEM (items->data); // take from the first selected item
128         *style_clip = take_style_from_item (item);
129     }
131     if (clip) {
132         // Sort items:
133         GSList *sorted_items = g_slist_copy ((GSList *) items);
134         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
136         // Copy item reprs:
137         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
138             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
139         }
141         *clip = g_slist_reverse(*clip);
142         g_slist_free ((GSList *) sorted_items);
143     }
146 /**
147  * Add gradients/patterns/markers referenced by copied objects to defs.
148  * Iterates through 'defs_clip', and for each item it adds the data
149  * repr into the global defs.
150  */
151 void
152 paste_defs (GSList **defs_clip, SPDocument *doc)
154     if (!defs_clip)
155         return;
157     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
158         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
159         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
160         gchar const *id = repr->attribute("id");
161         if (!id || !doc->getObjectById(id)) {
162             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
163             Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
164             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
165             Inkscape::GC::release(copy);
166         }
167     }
170 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip, GSList **defs_clip)
172     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
173     paste_defs (defs_clip, doc);
175     GSList *copied = NULL;
176     // add objects to document
177     for (GSList *l = *clip; l != NULL; l = l->next) {
178         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
179         Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
181         // premultiply the item transform by the accumulated parent transform in the paste layer
182         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
183         if (!local.test_identity()) {
184             gchar const *t_str = copy->attribute("transform");
185             NR::Matrix item_t (NR::identity());
186             if (t_str)
187                 sp_svg_transform_read(t_str, &item_t);
188             item_t *= local.inverse();
189             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
190             gchar *affinestr=sp_svg_transform_write(item_t);
191             copy->setAttribute("transform", affinestr);
192             g_free(affinestr);
193         }
195         parent->appendChildRepr(copy);
196         copied = g_slist_prepend(copied, copy);
197         Inkscape::GC::release(copy);
198     }
199     return copied;
202 void sp_selection_delete_impl(const GSList *items)
204     for (const GSList *i = items ; i ; i = i->next ) {
205         sp_object_ref((SPObject *)i->data, NULL);
206     }
207     for (const GSList *i = items; i != NULL; i = i->next) {
208         SPItem *item = (SPItem *) i->data;
209         SP_OBJECT(item)->deleteObject();
210         sp_object_unref((SPObject *)item, NULL);
211     }
215 void sp_selection_delete()
217     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
218     if (desktop == NULL) {
219         return;
220     }
222     if (tools_isactive (desktop, TOOLS_TEXT))
223         if (sp_text_delete_selection(desktop->event_context)) {
224             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
225                              _("Delete text"));
226             return;
227         }
229     Inkscape::Selection *selection = sp_desktop_selection(desktop);
231     // check if something is selected
232     if (selection->isEmpty()) {
233         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
234         return;
235     }
237     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
238     selection->clear();
239     sp_selection_delete_impl (selected);
240     g_slist_free ((GSList *) selected);
242     /* a tool may have set up private information in it's selection context
243      * that depends on desktop items.  I think the only sane way to deal with
244      * this currently is to reset the current tool, which will reset it's
245      * associated selection context.  For example: deleting an object
246      * while moving it around the canvas.
247      */
248     tools_switch ( desktop, tools_active ( desktop ) );
250     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
251                      _("Delete"));
254 /* fixme: sequencing */
255 void sp_selection_duplicate()
257     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
258     if (desktop == NULL)
259         return;
261     Inkscape::XML::Document* xml_doc = sp_document_repr_doc(desktop->doc());
262     Inkscape::Selection *selection = sp_desktop_selection(desktop);
264     // check if something is selected
265     if (selection->isEmpty()) {
266         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
267         return;
268     }
270     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
272     selection->clear();
274     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
275     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
277     GSList *newsel = NULL;
279     while (reprs) {
280         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
281         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate(xml_doc);
283         parent->appendChild(copy);
285         newsel = g_slist_prepend(newsel, copy);
286         reprs = g_slist_remove(reprs, reprs->data);
287         Inkscape::GC::release(copy);
288     }
290     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
291                      _("Duplicate"));
293     selection->setReprList(newsel);
295     g_slist_free(newsel);
298 void sp_edit_clear_all()
300     SPDesktop *dt = SP_ACTIVE_DESKTOP;
301     if (!dt)
302         return;
304     SPDocument *doc = sp_desktop_document(dt);
305     sp_desktop_selection(dt)->clear();
307     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
308     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
310     while (items) {
311         SP_OBJECT (items->data)->deleteObject();
312         items = g_slist_remove(items, items->data);
313     }
315     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
316                      _("Delete all"));
319 GSList *
320 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
322     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
323         if (SP_IS_ITEM(child) &&
324             !desktop->isLayer(SP_ITEM(child)) &&
325             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
326             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
327             (!exclude || !g_slist_find ((GSList *) exclude, child))
328             )
329         {
330             list = g_slist_prepend (list, SP_ITEM(child));
331         }
333         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
334             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
335         }
336     }
338     return list;
341 void sp_edit_select_all_full (bool force_all_layers, bool invert)
343     SPDesktop *dt = SP_ACTIVE_DESKTOP;
344     if (!dt)
345         return;
347     Inkscape::Selection *selection = sp_desktop_selection(dt);
349     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
351     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
352     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
353     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
355     GSList *items = NULL;
357     const GSList *exclude = NULL;
358     if (invert) {
359         exclude = selection->itemList();
360     }
362     if (force_all_layers)
363         inlayer = PREFS_SELECTION_ALL;
365     switch (inlayer) {
366         case PREFS_SELECTION_LAYER: {
367         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
368              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
369         return;
371         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
373         for (GSList *i = all_items; i; i = i->next) {
374             SPItem *item = SP_ITEM (i->data);
376             if (item && (!onlysensitive || !item->isLocked())) {
377                 if (!onlyvisible || !dt->itemIsHidden(item)) {
378                     if (!dt->isLayer(item)) {
379                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
380                             items = g_slist_prepend (items, item); // leave it in the list
381                         }
382                     }
383                 }
384             }
385         }
387         g_slist_free (all_items);
388             break;
389         }
390         case PREFS_SELECTION_LAYER_RECURSIVE: {
391             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
392             break;
393         }
394         default: {
395         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
396             break;
397     }
398     }
400     selection->setList (items);
402     if (items) {
403         g_slist_free (items);
404     }
407 void sp_edit_select_all ()
409     sp_edit_select_all_full (false, false);
412 void sp_edit_select_all_in_all_layers ()
414     sp_edit_select_all_full (true, false);
417 void sp_edit_invert ()
419     sp_edit_select_all_full (false, true);
422 void sp_edit_invert_in_all_layers ()
424     sp_edit_select_all_full (true, true);
427 void sp_selection_group()
429     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
430     if (desktop == NULL)
431         return;
433     SPDocument *doc = sp_desktop_document (desktop);
434     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
436     Inkscape::Selection *selection = sp_desktop_selection(desktop);
438     // Check if something is selected.
439     if (selection->isEmpty()) {
440         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
441         return;
442     }
444     GSList const *l = (GSList *) selection->reprList();
446     GSList *p = g_slist_copy((GSList *) l);
448     selection->clear();
450     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
452     // Remember the position and parent of the topmost object.
453     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
454     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
456     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
458     while (p) {
459         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
461         if (current->parent() == topmost_parent) {
462             Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
463             sp_repr_unparent(current);
464             group->appendChild(spnew);
465             Inkscape::GC::release(spnew);
466             topmost --; // only reduce count for those items deleted from topmost_parent
467         } else { // move it to topmost_parent first
468                 GSList *temp_clip = NULL;
470                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
471                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
472                 gchar const *t_str = current->attribute("transform");
473                 NR::Matrix item_t (NR::identity());
474                 if (t_str)
475                     sp_svg_transform_read(t_str, &item_t);
476                 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
477                 //FIXME: when moving both clone and original from a transformed group (either by
478                 //grouping into another parent, or by cut/paste) the transform from the original's
479                 //parent becomes embedded into original itself, and this affects its clones. Fix
480                 //this by remembering the transform diffs we write to each item into an array and
481                 //then, if this is clone, looking up its original in that array and pre-multiplying
482                 //it by the inverse of that original's transform diff.
484                 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
485                 sp_repr_unparent(current);
487                 // paste into topmost_parent (temporarily)
488                 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip, NULL);
489                 if (temp_clip) g_slist_free (temp_clip);
490                 if (copied) { // if success,
491                     // take pasted object (now in topmost_parent)
492                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
493                     // make a copy
494                     Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
495                     // remove pasted
496                     sp_repr_unparent(in_topmost);
497                     // put its copy into group
498                     group->appendChild(spnew);
499                     Inkscape::GC::release(spnew);
500                     g_slist_free (copied);
501                 }
502         }
503         p = g_slist_remove(p, current);
504     }
506     // Add the new group to the topmost members' parent
507     topmost_parent->appendChild(group);
509     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
510     group->setPosition(topmost + 1);
512     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
513                      _("Group"));
515     selection->set(group);
516     Inkscape::GC::release(group);
519 void sp_selection_ungroup()
521     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
522     if (desktop == NULL)
523         return;
525     Inkscape::Selection *selection = sp_desktop_selection(desktop);
527     if (selection->isEmpty()) {
528         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
529         return;
530     }
532     GSList *items = g_slist_copy((GSList *) selection->itemList());
533     selection->clear();
535     // Get a copy of current selection.
536     GSList *new_select = NULL;
537     bool ungrouped = false;
538     for (GSList *i = items;
539          i != NULL;
540          i = i->next)
541     {
542         SPItem *group = (SPItem *) i->data;
544         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
545         if (!SP_IS_OBJECT(group)) {
546             continue;
547         }
549         /* We do not allow ungrouping <svg> etc. (lauris) */
550         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
551             // keep the non-group item in the new selection
552             selection->add(group);
553             continue;
554         }
556         GSList *children = NULL;
557         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
558         sp_item_group_ungroup(SP_GROUP(group), &children, false);
559         ungrouped = true;
560         // Add ungrouped items to the new selection.
561         new_select = g_slist_concat(new_select, children);
562     }
564     if (new_select) { // Set new selection.
565         selection->addList(new_select);
566         g_slist_free(new_select);
567     }
568     if (!ungrouped) {
569         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
570     }
572     g_slist_free(items);
574     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
575                      _("Ungroup"));
578 static SPGroup *
579 sp_item_list_common_parent_group(const GSList *items)
581     if (!items) {
582         return NULL;
583     }
584     SPObject *parent = SP_OBJECT_PARENT(items->data);
585     /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
586     if (!SP_IS_GROUP(parent)) {
587         return NULL;
588     }
589     for (items = items->next; items; items = items->next) {
590         if (SP_OBJECT_PARENT(items->data) != parent) {
591             return NULL;
592         }
593     }
595     return SP_GROUP(parent);
598 /** Finds out the minimum common bbox of the selected items
599  */
600 static NR::Maybe<NR::Rect>
601 enclose_items(const GSList *items)
603     g_assert(items != NULL);
605     NR::Maybe<NR::Rect> r = NR::Nothing();
606     for (GSList const *i = items; i; i = i->next) {
607         r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
608     }
609     return r;
612 SPObject *
613 prev_sibling(SPObject *child)
615     SPObject *parent = SP_OBJECT_PARENT(child);
616     if (!SP_IS_GROUP(parent)) {
617         return NULL;
618     }
619     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
620         if (i->next == child)
621             return i;
622     }
623     return NULL;
626 void
627 sp_selection_raise()
629     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
630     if (!desktop)
631         return;
633     Inkscape::Selection *selection = sp_desktop_selection(desktop);
635     GSList const *items = (GSList *) selection->itemList();
636     if (!items) {
637         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
638         return;
639     }
641     SPGroup const *group = sp_item_list_common_parent_group(items);
642     if (!group) {
643         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
644         return;
645     }
647     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
649     /* construct reverse-ordered list of selected children */
650     GSList *rev = g_slist_copy((GSList *) items);
651     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
653     // find out the common bbox of the selected items
654     NR::Maybe<NR::Rect> selected = enclose_items(items);
656     // for all objects in the selection (starting from top)
657     if (selected) {
658         while (rev) {
659             SPObject *child = SP_OBJECT(rev->data);
660             // for each selected object, find the next sibling
661             for (SPObject *newref = child->next; newref; newref = newref->next) {
662                 // if the sibling is an item AND overlaps our selection,
663                 if (SP_IS_ITEM(newref)) {
664                     NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
665                     if ( newref_bbox && selected->intersects(*newref_bbox) ) {
666                         // AND if it's not one of our selected objects,
667                         if (!g_slist_find((GSList *) items, newref)) {
668                             // move the selected object after that sibling
669                             grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
670                         }
671                         break;
672                     }
673                 }
674             }
675             rev = g_slist_remove(rev, child);
676         }
677     } else {
678         g_slist_free(rev);
679     }
681     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
682                      _("Raise"));
685 void sp_selection_raise_to_top()
687     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
688     if (desktop == NULL)
689         return;
691     SPDocument *document = sp_desktop_document(desktop);
692     Inkscape::Selection *selection = sp_desktop_selection(desktop);
694     if (selection->isEmpty()) {
695         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
696         return;
697     }
699     GSList const *items = (GSList *) selection->itemList();
701     SPGroup const *group = sp_item_list_common_parent_group(items);
702     if (!group) {
703         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
704         return;
705     }
707     GSList *rl = g_slist_copy((GSList *) selection->reprList());
708     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
710     for (GSList *l = rl; l != NULL; l = l->next) {
711         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
712         repr->setPosition(-1);
713     }
715     g_slist_free(rl);
717     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
718                      _("Raise to top"));
721 void
722 sp_selection_lower()
724     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
725     if (desktop == NULL)
726         return;
728     Inkscape::Selection *selection = sp_desktop_selection(desktop);
730     GSList const *items = (GSList *) selection->itemList();
731     if (!items) {
732         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
733         return;
734     }
736     SPGroup const *group = sp_item_list_common_parent_group(items);
737     if (!group) {
738         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
739         return;
740     }
742     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
744     // find out the common bbox of the selected items
745     NR::Maybe<NR::Rect> selected = enclose_items(items);
747     /* construct direct-ordered list of selected children */
748     GSList *rev = g_slist_copy((GSList *) items);
749     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
750     rev = g_slist_reverse(rev);
752     // for all objects in the selection (starting from top)
753     if (selected) {
754         while (rev) {
755             SPObject *child = SP_OBJECT(rev->data);
756             // for each selected object, find the prev sibling
757             for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
758                 // if the sibling is an item AND overlaps our selection,
759                 if (SP_IS_ITEM(newref)) {
760                     NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
761                     if ( ref_bbox && selected->intersects(*ref_bbox) ) {
762                         // AND if it's not one of our selected objects,
763                         if (!g_slist_find((GSList *) items, newref)) {
764                             // move the selected object before that sibling
765                             SPObject *put_after = prev_sibling(newref);
766                             if (put_after)
767                                 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
768                             else
769                                 SP_OBJECT_REPR(child)->setPosition(0);
770                         }
771                         break;
772                     }
773                 }
774             }
775             rev = g_slist_remove(rev, child);
776         }
777     } else {
778         g_slist_free(rev);
779     }
781     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
782                      _("Lower"));
785 void sp_selection_lower_to_bottom()
787     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
788     if (desktop == NULL)
789         return;
791     SPDocument *document = sp_desktop_document(desktop);
792     Inkscape::Selection *selection = sp_desktop_selection(desktop);
794     if (selection->isEmpty()) {
795         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
796         return;
797     }
799     GSList const *items = (GSList *) selection->itemList();
801     SPGroup const *group = sp_item_list_common_parent_group(items);
802     if (!group) {
803         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
804         return;
805     }
807     GSList *rl;
808     rl = g_slist_copy((GSList *) selection->reprList());
809     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
810     rl = g_slist_reverse(rl);
812     for (GSList *l = rl; l != NULL; l = l->next) {
813         gint minpos;
814         SPObject *pp, *pc;
815         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
816         pp = document->getObjectByRepr(sp_repr_parent(repr));
817         minpos = 0;
818         g_assert(SP_IS_GROUP(pp));
819         pc = sp_object_first_child(pp);
820         while (!SP_IS_ITEM(pc)) {
821             minpos += 1;
822             pc = pc->next;
823         }
824         repr->setPosition(minpos);
825     }
827     g_slist_free(rl);
829     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
830                      _("Lower to bottom"));
833 void
834 sp_undo(SPDesktop *desktop, SPDocument *)
836         if (!sp_document_undo(sp_desktop_document(desktop)))
837             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
840 void
841 sp_redo(SPDesktop *desktop, SPDocument *)
843         if (!sp_document_redo(sp_desktop_document(desktop)))
844             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
847 void sp_selection_cut()
849     sp_selection_copy();
850     sp_selection_delete();
853 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient, Inkscape::XML::Document* xml_doc)
855     SPGradient *ref = gradient;
857     while (ref) {
858         // climb up the refs, copying each one in the chain
859         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
860         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
862         ref = ref->ref->getObject();
863     }
866 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern, Inkscape::XML::Document* xml_doc)
868     SPPattern *ref = pattern;
870     while (ref) {
871         // climb up the refs, copying each one in the chain
872         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate(xml_doc);
873         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
875         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
876         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
877             if (!SP_IS_ITEM (child))
878                 continue;
879             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL, xml_doc);
880         }
882         ref = ref->ref->getObject();
883     }
886 void sp_copy_single (GSList **defs_clip, SPObject *thing, Inkscape::XML::Document* xml_doc)
888     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate(xml_doc);
889     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
893 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items, Inkscape::XML::Document* xml_doc)
895     SPItem *path = sp_textpath_get_path_item (tp);
896     if (!path)
897         return;
898     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
899         return;
900     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate(xml_doc);
901     *defs_clip = g_slist_prepend (*defs_clip, repr);
904 /**
905  * Copies things like patterns, markers, gradients, etc.
906  */
907 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items, Inkscape::XML::Document* xml_doc)
909     SPStyle *style = SP_OBJECT_STYLE (item);
911     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
912         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
913         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
914             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
915         if (SP_IS_PATTERN (server))
916             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
917     }
919     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
920         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
921         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
922             sp_copy_gradient (defs_clip, SP_GRADIENT(server), xml_doc);
923         if (SP_IS_PATTERN (server))
924             sp_copy_pattern (defs_clip, SP_PATTERN(server), xml_doc);
925     }
927     // For shapes, copy all of the shape's markers into defs_clip
928     if (SP_IS_SHAPE (item)) {
929         SPShape *shape = SP_SHAPE (item);
930         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
931             if (shape->marker[i]) {
932                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]), xml_doc);
933             }
934         }
935     }
937     if (SP_IS_TEXT_TEXTPATH (item)) {
938         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items, xml_doc);
939     }
941     if (item->clip_ref->getObject()) {
942         sp_copy_single (defs_clip, item->clip_ref->getObject(), xml_doc);
943     }
945     if (item->mask_ref->getObject()) {
946         SPObject *mask = item->mask_ref->getObject();
947         sp_copy_single (defs_clip, mask, xml_doc);
948         // recurse into the mask for its gradients etc.
949         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
950             if (SP_IS_ITEM(o))
951                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
952         }
953     }
955     if (style->filter.filter) {
956         SPObject *filter = style->filter.filter;
957         if (SP_IS_FILTER(filter)) {
958             sp_copy_single (defs_clip, filter, xml_doc);
959         }
960     }
962     // recurse
963     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
964         if (SP_IS_ITEM(o))
965             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items, xml_doc);
966     }
969 /**
970  * \pre item != NULL
971  */
972 SPCSSAttr *
973 take_style_from_item (SPItem *item)
975     // write the complete cascaded style, context-free
976     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
977     if (css == NULL)
978         return NULL;
980     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
981         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
982         // if this is a text with exactly one tspan child, merge the style of that tspan as well
983         // If this is a group, merge the style of its topmost (last) child with style
984         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
985             if (SP_OBJECT_STYLE (last_element) != NULL) {
986                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
987                 if (temp) {
988                     sp_repr_css_merge (css, temp);
989                     sp_repr_css_attr_unref (temp);
990                 }
991                 break;
992             }
993         }
994     }
995     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
996         // do not copy text properties from non-text objects, it's confusing
997         css = sp_css_attr_unset_text (css);
998     }
1000     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1001     double ex = NR::expansion(sp_item_i2doc_affine(item));
1002     if (ex != 1.0) {
1003         css = sp_css_attr_scale (css, ex);
1004     }
1006     return css;
1010 void sp_selection_copy()
1012     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1013     if (desktop == NULL)
1014         return;
1016     if (!clipboard_document) {
1017         clipboard_document = new Inkscape::XML::SimpleDocument();
1018     }
1020     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1022     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1023         sp_dropper_context_copy(desktop->event_context);
1024         return; // copied color under cursor, nothing else to do
1025     }
1027     // check if something is selected
1028     if (selection->isEmpty()) {
1029         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1030         return;
1031     }
1033     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1035     // 0. Copy text to system clipboard
1036     // FIXME: for non-texts, put serialized Inkscape::XML as text to the clipboard;
1037     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1038     Glib::ustring text;
1039     if (tools_isactive (desktop, TOOLS_TEXT)) {
1040         text = sp_text_get_selected_text(desktop->event_context);
1041     }
1043     if (text.empty()) {
1044         guint texts = 0;
1045         for (GSList *i = (GSList *) items; i; i = i->next) {
1046             SPItem *item = SP_ITEM (i->data);
1047             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1048                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1049                     text += " ";
1050                 gchar *this_text = sp_te_get_string_multiline (item);
1051                 if (this_text) {
1052                     text += this_text;
1053                     g_free(this_text);
1054                 }
1055                 texts++;
1056             }
1057         }
1058     }
1059     if (!text.empty()) {
1060         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1061         refClipboard->set_text(text);
1062     }
1064     // clear old defs clipboard
1065     while (defs_clipboard) {
1066         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1067         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1068     }
1070     // clear style clipboard
1071     if (style_clipboard) {
1072         sp_repr_css_attr_unref (style_clipboard);
1073         style_clipboard = NULL;
1074     }
1076     //clear main clipboard
1077     while (clipboard) {
1078         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1079         clipboard = g_slist_remove(clipboard, clipboard->data);
1080     }
1082     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard, clipboard_document);
1084     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1085         SPStyle *const query = sp_style_new();
1086         if (sp_desktop_query_style_all (desktop, query)) {
1087             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1088             if (css != NULL) {
1089                 // clear style clipboard
1090                 if (style_clipboard) {
1091                     sp_repr_css_attr_unref (style_clipboard);
1092                     style_clipboard = NULL;
1093                 }
1094                 //sp_repr_css_print (css);
1095                 style_clipboard = css;
1096             }
1097         }
1098         g_free (query);
1099     }
1101     size_clipboard = selection->bounds();
1103     g_slist_free ((GSList *) items);
1106 void sp_selection_paste(bool in_place)
1108     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1110     if (desktop == NULL) {
1111         return;
1112     }
1114     SPDocument *document = sp_desktop_document(desktop);
1116     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1117         return;
1118     }
1120     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1122     if (tools_isactive (desktop, TOOLS_TEXT)) {
1123         if (sp_text_paste_inline(desktop->event_context))
1124             return; // pasted from system clipboard into text, nothing else to do
1125     }
1127     // check if something is in the clipboard
1128     if (clipboard == NULL) {
1129         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1130         return;
1131     }
1133     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1134     // add pasted objects to selection
1135     selection->setReprList((GSList const *) copied);
1136     g_slist_free (copied);
1138     if (!in_place) {
1139         sp_document_ensure_up_to_date(document);
1141         NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1142         NR::Point m( desktop->point() );
1143         if (sel_bbox) {
1144             m -= sel_bbox->midpoint();
1145         }
1147         /* Snap the offset of the new item(s) to the grid */
1148         /* FIXME: this gridsnap fiddling is a hack. */
1149         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1150         gdouble const curr_gridsnap = s.getDistance();
1151         s.setDistance(NR_HUGE);
1152         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1153         s.setDistance(curr_gridsnap);
1154         sp_selection_move_relative(selection, m);
1155     }
1157     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1158                      _("Paste"));
1161 void sp_selection_paste_style()
1163     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1164     if (desktop == NULL) return;
1166     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1168     // check if something is in the clipboard
1169     if (clipboard == NULL) {
1170         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1171         return;
1172     }
1174     // check if something is selected
1175     if (selection->isEmpty()) {
1176         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1177         return;
1178     }
1180     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1182     sp_desktop_set_style (desktop, style_clipboard);
1184     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1185                      _("Paste style"));
1188 void sp_selection_paste_size (bool apply_x, bool apply_y)
1190     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1191     if (desktop == NULL) return;
1193     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1195     // check if something is in the clipboard
1196     if (!size_clipboard) {
1197         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1198         return;
1199     }
1201     // check if something is selected
1202     if (selection->isEmpty()) {
1203         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1204         return;
1205     }
1207     NR::Maybe<NR::Rect> current = selection->bounds();
1208     if ( !current || current->isEmpty() ) {
1209         return;
1210     }
1212     double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1213     double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1215     sp_selection_scale_relative (selection, current->midpoint(),
1216                                  NR::scale(
1217                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1218                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1220     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1221                      _("Paste size"));
1224 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1226     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1227     if (desktop == NULL) return;
1229     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1231     // check if something is in the clipboard
1232     if ( !size_clipboard ) {
1233         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1234         return;
1235     }
1237     // check if something is selected
1238     if (selection->isEmpty()) {
1239         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1240         return;
1241     }
1243     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1244         SPItem *item = SP_ITEM(l->data);
1246         NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1247         if ( !current || current->isEmpty() ) {
1248             continue;
1249         }
1251         double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1252         double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1254         sp_item_scale_rel (item,
1255                                  NR::scale(
1256                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1257                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1259     }
1261     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1262                      _("Paste size separately"));
1265 void sp_selection_to_next_layer ()
1267     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1269     Inkscape::Selection *selection = sp_desktop_selection(dt);
1271     // check if something is selected
1272     if (selection->isEmpty()) {
1273         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1274         return;
1275     }
1277     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1279     bool no_more = false; // Set to true, if no more layers above
1280     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1281     if (next) {
1282         GSList *temp_clip = NULL;
1283         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
1284         sp_selection_delete_impl (items);
1285         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1286         GSList *copied;
1287         if(next) {
1288             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1289         } else {
1290             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1291             no_more = true;
1292         }
1293         selection->setReprList((GSList const *) copied);
1294         g_slist_free (copied);
1295         if (temp_clip) g_slist_free (temp_clip);
1296         if (next) dt->setCurrentLayer(next);
1297         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1298                          _("Raise to next layer"));
1299     } else {
1300         no_more = true;
1301     }
1303     if (no_more) {
1304         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1305     }
1307     g_slist_free ((GSList *) items);
1310 void sp_selection_to_prev_layer ()
1312     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1314     Inkscape::Selection *selection = sp_desktop_selection(dt);
1316     // check if something is selected
1317     if (selection->isEmpty()) {
1318         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1319         return;
1320     }
1322     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1324     bool no_more = false; // Set to true, if no more layers below
1325     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1326     if (next) {
1327         GSList *temp_clip = NULL;
1328         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
1329         sp_selection_delete_impl (items);
1330         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1331         GSList *copied;
1332         if(next) {
1333             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1334         } else {
1335             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1336             no_more = true;
1337         }
1338         selection->setReprList((GSList const *) copied);
1339         g_slist_free (copied);
1340         if (temp_clip) g_slist_free (temp_clip);
1341         if (next) dt->setCurrentLayer(next);
1342         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1343                          _("Lower to previous layer"));
1344     } else {
1345         no_more = true;
1346     }
1348     if (no_more) {
1349         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1350     }
1352     g_slist_free ((GSList *) items);
1355 bool
1356 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1358     bool contains_original = false;
1359     bool is_use = SP_IS_USE(item);
1360     SPItem *item_use = item;
1361     SPItem *item_use_first = item;
1362     while (is_use && item_use && !contains_original)
1363     {
1364         item_use = sp_use_get_original (SP_USE(item_use));
1365         contains_original |= selection->includes(item_use);
1366         if (item_use == item_use_first)
1367             break;
1368         is_use = SP_IS_USE(item_use);
1369     }   
1370     return contains_original;
1374 bool
1375 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1377     bool clone_with_original = false;
1378     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1379         SPItem *item = SP_ITEM(l->data);
1380         clone_with_original |= selection_contains_original(item, selection);
1381         if (clone_with_original) 
1382             break;
1383     }
1384     return clone_with_original;
1388 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1389 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1390 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1391 that case, items are already in the new position, but the repr is in the old, and this function
1392 then simply updates the repr from item->transform.
1393  */
1394 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1396     if (selection->isEmpty())
1397         return;
1399     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1400         SPItem *item = SP_ITEM(l->data);
1402         NR::Point old_center(0,0);
1403         if (set_i2d && item->isCenterSet())
1404             old_center = item->getCenter();
1406 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1407          At the time of writing, this is the only place to re-enable. */
1408         sp_item_update_cns(*item, selection->desktop());
1409 #endif
1411         // we're moving both a clone and its original or any ancestor in clone chain?
1412         bool transform_clone_with_original = selection_contains_original(item, selection);
1413         // ...both a text-on-path and its path?
1414         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)))) ));
1415         // ...both a flowtext and its frame?
1416         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)
1417         // ...both an offset and its source?
1418         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1419        
1420         // If we're moving a connector, we want to detach it
1421         // from shapes that aren't part of the selection, but
1422         // leave it attached if they are
1423         if (cc_item_is_connector(item)) {
1424             SPItem *attItem[2];
1425             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1426             
1427             for (int n = 0; n < 2; ++n) {
1428                 if (!selection->includes(attItem[n])) {
1429                     sp_conn_end_detach(item, n);
1430                 }
1431             }
1432         }
1433         
1434         // "clones are unmoved when original is moved" preference
1435         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1436         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1437         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1439         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1440         // transform of its original and respond to it itself. Without this, a clone is doubly
1441         // transformed, very unintuitive.
1442       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1443       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1444       // Same for linked offset if we are also moving its source: do not move it.
1445         if (transform_textpath_with_path || transform_offset_with_source) {
1446                 // restore item->transform field from the repr, in case it was changed by seltrans
1447             sp_object_read_attr (SP_OBJECT (item), "transform");
1449         } else if (transform_flowtext_with_frame) {
1450             // apply the inverse of the region's transform to the <use> so that the flow remains
1451             // the same (even though the output itself gets transformed)
1452             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1453                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1454                     continue;
1455                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1456                     if (!SP_IS_USE(use)) continue;
1457                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1458                 }
1459             }
1460         } else if (transform_clone_with_original) {
1461             // We are transforming a clone along with its original. The below matrix juggling is
1462             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1463             // transform and its move compensation are both cancelled out.
1465             // restore item->transform field from the repr, in case it was changed by seltrans
1466             sp_object_read_attr (SP_OBJECT (item), "transform");
1468             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1469             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1470             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1471             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1472             NR::Matrix result = t_inv * item->transform * t;
1474             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1475                 // we need to cancel out the move compensation, too
1477                 // find out the clone move, same as in sp_use_move_compensate
1478                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1479                 NR::Matrix clone_move = parent.inverse() * t * parent;
1481                 if (prefs_parallel) {
1482                     NR::Matrix move = result * clone_move * t_inv;
1483                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1485                 } else if (prefs_unmoved) {
1486                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1487                     //    clone_move = NR::identity();
1488                     NR::Matrix move = result * clone_move;
1489                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1490                 }
1492             } else {
1493                 // just apply the result
1494                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1495             }
1497         } else {
1498             if (set_i2d) {
1499                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1500             }
1501             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1502         }
1504         // if we're moving the actual object, not just updating the repr, we can transform the
1505         // center by the same matrix (only necessary for non-translations)
1506         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1507             item->setCenter(old_center * affine);
1508             SP_OBJECT(item)->updateRepr();
1509         }
1510     }
1513 void sp_selection_remove_transform()
1515     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1516     if (desktop == NULL)
1517         return;
1519     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1521     GSList const *l = (GSList *) selection->reprList();
1522     while (l != NULL) {
1523         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1524         l = l->next;
1525     }
1527     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1528                      _("Remove transform"));
1531 void
1532 sp_selection_scale_absolute(Inkscape::Selection *selection,
1533                             double const x0, double const x1,
1534                             double const y0, double const y1)
1536     if (selection->isEmpty())
1537         return;
1539     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1540     if ( !bbox || bbox->isEmpty() ) {
1541         return;
1542     }
1544     NR::translate const p2o(-bbox->min());
1546     NR::scale const newSize(x1 - x0,
1547                             y1 - y0);
1548     NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1549     NR::translate const o2n(x0, y0);
1550     NR::Matrix const final( p2o * scale * o2n );
1552     sp_selection_apply_affine(selection, final);
1556 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1558     if (selection->isEmpty())
1559         return;
1561     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1563     if ( !bbox || bbox->isEmpty() ) {
1564         return;
1565     }
1567     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1568     if ( bbox->extent(NR::X) * scale[NR::X] > 1e6  ||
1569          bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1570     {
1571         return;
1572     }
1574     NR::translate const n2d(-align);
1575     NR::translate const d2n(align);
1576     NR::Matrix const final( n2d * scale * d2n );
1577     sp_selection_apply_affine(selection, final);
1580 void
1581 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1583     NR::translate const d2n(center);
1584     NR::translate const n2d(-center);
1585     NR::rotate const rotate(rotate_degrees(angle_degrees));
1586     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1587     sp_selection_apply_affine(selection, final);
1590 void
1591 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1593     NR::translate const d2n(align);
1594     NR::translate const n2d(-align);
1595     NR::Matrix const skew(1, dy,
1596                           dx, 1,
1597                           0, 0);
1598     NR::Matrix const final( n2d * skew * d2n );
1599     sp_selection_apply_affine(selection, final);
1602 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1604     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1607 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1609     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1613 /**
1614  * \brief sp_selection_rotate_90
1615  *
1616  * This function rotates selected objects 90 degrees clockwise.
1617  *
1618  */
1620 void sp_selection_rotate_90_cw()
1622     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1624     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1626     if (selection->isEmpty())
1627         return;
1629     GSList const *l = selection->itemList();
1630     NR::rotate const rot_neg_90(NR::Point(0, -1));
1631     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1632         SPItem *item = SP_ITEM(l2->data);
1633         sp_item_rotate_rel(item, rot_neg_90);
1634     }
1636     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1637                      _("Rotate 90&#176; CW"));
1641 /**
1642  * \brief sp_selection_rotate_90_ccw
1643  *
1644  * This function rotates selected objects 90 degrees counter-clockwise.
1645  *
1646  */
1648 void sp_selection_rotate_90_ccw()
1650     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1652     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1654     if (selection->isEmpty())
1655         return;
1657     GSList const *l = selection->itemList();
1658     NR::rotate const rot_neg_90(NR::Point(0, 1));
1659     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1660         SPItem *item = SP_ITEM(l2->data);
1661         sp_item_rotate_rel(item, rot_neg_90);
1662     }
1664     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1665                      _("Rotate 90&#176; CCW"));
1668 void
1669 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1671     if (selection->isEmpty())
1672         return;
1674     NR::Maybe<NR::Point> center = selection->center();
1675     if (!center) {
1676         return;
1677     }
1679     sp_selection_rotate_relative(selection, *center, angle_degrees);
1681     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1682                            ( ( angle_degrees > 0 )
1683                              ? "selector:rotate:ccw"
1684                              : "selector:rotate:cw" ), 
1685                            SP_VERB_CONTEXT_SELECT, 
1686                            _("Rotate"));
1689 /**
1690 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1691 */
1692 void
1693 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1695     if (selection->isEmpty())
1696         return;
1698     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1699     NR::Maybe<NR::Point> center = selection->center();
1701     if ( !bbox || !center ) {
1702         return;
1703     }
1705     gdouble const zoom = selection->desktop()->current_zoom();
1706     gdouble const zmove = angle / zoom;
1707     gdouble const r = NR::L2(bbox->max() - *center);
1709     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1711     sp_selection_rotate_relative(selection, *center, zangle);
1713     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1714                            ( (angle > 0)
1715                              ? "selector:rotate:ccw"
1716                              : "selector:rotate:cw" ),
1717                            SP_VERB_CONTEXT_SELECT, 
1718                            _("Rotate by pixels"));
1721 void
1722 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1724     if (selection->isEmpty())
1725         return;
1727     NR::Maybe<NR::Rect> const bbox(selection->bounds());
1728     if (!bbox) {
1729         return;
1730     }
1732     NR::Point const center(bbox->midpoint());
1734     // you can't scale "do nizhe pola" (below zero)
1735     double const max_len = bbox->maxExtent();
1736     if ( max_len + grow <= 1e-3 ) {
1737         return;
1738     }
1740     double const times = 1.0 + grow / max_len;
1741     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1743     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1744                            ( (grow > 0)
1745                              ? "selector:scale:larger"
1746                              : "selector:scale:smaller" ),
1747                            SP_VERB_CONTEXT_SELECT,
1748                            _("Scale"));
1751 void
1752 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1754     sp_selection_scale(selection,
1755                        grow_pixels / selection->desktop()->current_zoom());
1758 void
1759 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1761     if (selection->isEmpty())
1762         return;
1764     NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1766     if (!sel_bbox) {
1767         return;
1768     }
1770     NR::Point const center(sel_bbox->midpoint());
1771     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1772     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1773                      _("Scale by whole factor"));
1776 void
1777 sp_selection_move(gdouble dx, gdouble dy)
1779     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1780     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1781     if (selection->isEmpty()) {
1782         return;
1783     }
1785     sp_selection_move_relative(selection, dx, dy);
1787     if (dx == 0) {
1788         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1789                                _("Move vertically"));
1790     } else if (dy == 0) {
1791         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1792                                _("Move horizontally"));
1793     } else {
1794         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1795                          _("Move"));
1796     }
1799 void
1800 sp_selection_move_screen(gdouble dx, gdouble dy)
1802     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1804     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1805     if (selection->isEmpty()) {
1806         return;
1807     }
1809     // same as sp_selection_move but divide deltas by zoom factor
1810     gdouble const zoom = desktop->current_zoom();
1811     gdouble const zdx = dx / zoom;
1812     gdouble const zdy = dy / zoom;
1813     sp_selection_move_relative(selection, zdx, zdy);
1815     if (dx == 0) {
1816         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1817                                _("Move vertically by pixels"));
1818     } else if (dy == 0) {
1819         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1820                                _("Move horizontally by pixels"));
1821     } else {
1822         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1823                          _("Move"));
1824     }
1827 namespace {
1829 template <typename D>
1830 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1831                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1833 template <typename D>
1834 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1835                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1837 struct Forward {
1838     typedef SPObject *Iterator;
1840     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1841     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1842     static void dispose(Iterator i) {}
1844     static SPObject *object(Iterator i) { return i; }
1845     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1846 };
1848 struct Reverse {
1849     typedef GSList *Iterator;
1851     static Iterator children(SPObject *o) {
1852         return make_list(o->firstChild(), NULL);
1853     }
1854     static Iterator siblings_after(SPObject *o) {
1855         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1856     }
1857     static void dispose(Iterator i) {
1858         g_slist_free(i);
1859     }
1861     static SPObject *object(Iterator i) {
1862         return reinterpret_cast<SPObject *>(i->data);
1863     }
1864     static Iterator next(Iterator i) { return i->next; }
1866 private:
1867     static GSList *make_list(SPObject *object, SPObject *limit) {
1868         GSList *list=NULL;
1869         while ( object != limit ) {
1870             list = g_slist_prepend(list, object);
1871             object = SP_OBJECT_NEXT(object);
1872         }
1873         return list;
1874     }
1875 };
1879 void
1880 sp_selection_item_next(void)
1882     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1883     g_return_if_fail(desktop != NULL);
1884     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1886     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1887     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1888     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1890     SPObject *root;
1891     if (PREFS_SELECTION_ALL != inlayer) {
1892         root = selection->activeContext();
1893     } else {
1894         root = desktop->currentRoot();
1895     }
1897     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1899     if (item) {
1900         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1901         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1902             scroll_to_show_item(desktop, item);
1903         }
1904     }
1907 void
1908 sp_selection_item_prev(void)
1910     SPDocument *document = SP_ACTIVE_DOCUMENT;
1911     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1912     g_return_if_fail(document != NULL);
1913     g_return_if_fail(desktop != NULL);
1914     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1916     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1917     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1918     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1920     SPObject *root;
1921     if (PREFS_SELECTION_ALL != inlayer) {
1922         root = selection->activeContext();
1923     } else {
1924         root = desktop->currentRoot();
1925     }
1927     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1929     if (item) {
1930         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1931         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1932             scroll_to_show_item(desktop, item);
1933         }
1934     }
1937 namespace {
1939 template <typename D>
1940 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1941                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1943     SPObject *current=root;
1944     while (items) {
1945         SPItem *item=SP_ITEM(items->data);
1946         if ( root->isAncestorOf(item) &&
1947              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1948         {
1949             current = item;
1950             break;
1951         }
1952         items = items->next;
1953     }
1955     GSList *path=NULL;
1956     while ( current != root ) {
1957         path = g_slist_prepend(path, current);
1958         current = SP_OBJECT_PARENT(current);
1959     }
1961     SPItem *next;
1962     // first, try from the current object
1963     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1964     g_slist_free(path);
1966     if (!next) { // if we ran out of objects, start over at the root
1967         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1968     }
1970     return next;
1973 template <typename D>
1974 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1975                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1977     typename D::Iterator children;
1978     typename D::Iterator iter;
1980     SPItem *found=NULL;
1982     if (path) {
1983         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1984         g_assert(SP_OBJECT_PARENT(object) == root);
1985         if (desktop->isLayer(object)) {
1986             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1987         }
1988         iter = children = D::siblings_after(object);
1989     } else {
1990         iter = children = D::children(root);
1991     }
1993     while ( iter && !found ) {
1994         SPObject *object=D::object(iter);
1995         if (desktop->isLayer(object)) {
1996             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1997                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1998             }
1999         } else if ( SP_IS_ITEM(object) &&
2000                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
2001                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
2002                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
2003                     !desktop->isLayer(SP_ITEM(object)) )
2004         {
2005             found = SP_ITEM(object);
2006         }
2007         iter = D::next(iter);
2008     }
2010     D::dispose(children);
2012     return found;
2017 /**
2018  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2019  * \a item.
2020  */
2021 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2023     NR::Rect dbox = desktop->get_display_area();
2024     NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2026     if ( sbox && dbox.contains(*sbox) == false ) {
2027         NR::Point const s_dt = sbox->midpoint();
2028         NR::Point const s_w = desktop->d2w(s_dt);
2029         NR::Point const d_dt = dbox.midpoint();
2030         NR::Point const d_w = desktop->d2w(d_dt);
2031         NR::Point const moved_w( d_w - s_w );
2032         gint const dx = (gint) moved_w[X];
2033         gint const dy = (gint) moved_w[Y];
2034         desktop->scroll_world(dx, dy);
2035     }
2039 void
2040 sp_selection_clone()
2042     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2043     if (desktop == NULL)
2044         return;
2046     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2048     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2050     // check if something is selected
2051     if (selection->isEmpty()) {
2052         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2053         return;
2054     }
2056     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2057   
2058     selection->clear();
2059   
2060     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2061     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2063     GSList *newsel = NULL;
2064  
2065     while (reprs) {
2066         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2067         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2069         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2070         sp_repr_set_attr(clone, "x", "0");
2071         sp_repr_set_attr(clone, "y", "0");
2072         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2074         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2075         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2076         
2077         // add the new clone to the top of the original's parent
2078         parent->appendChild(clone);
2080         newsel = g_slist_prepend(newsel, clone);
2081         reprs = g_slist_remove(reprs, sel_repr);
2082         Inkscape::GC::release(clone);
2083     }
2084     
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());
2849     NRRect bbox(0, 0, 0, 0);
2851     desktop->selection->bounds(&bbox);
2852     if (!nr_rect_d_test_empty(&bbox)) {
2853         doc->fitToRect(bbox);
2854     }
2855 };
2857 void fit_canvas_to_drawing(SPDocument *doc) {
2858     g_return_if_fail(doc != NULL);
2859     NRRect bbox(0, 0, 0, 0);
2861     sp_document_ensure_up_to_date (doc);
2862     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2864     if (!nr_rect_d_test_empty(&bbox)) {
2865         doc->fitToRect(bbox);
2866     }
2867 };
2869 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2870     g_return_if_fail(desktop != NULL);
2871     SPDocument *doc = sp_desktop_document(desktop);
2873     g_return_if_fail(doc != NULL);
2874     g_return_if_fail(desktop->selection != NULL);
2876     if (desktop->selection->isEmpty()) {
2877         fit_canvas_to_drawing(doc);
2878     } else {
2879         fit_canvas_to_selection(desktop);
2880     }
2882     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2883                      _("Fit page to selection"));
2884 };
2886 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2887     // don't operate on layers
2888     if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2889         f(SP_ITEM(root), desktop);
2890     }
2891     for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2892         //don't recurse into locked layers
2893         if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2894             itemtree_map(f, iter, desktop);
2895         }
2896     }
2899 static void unlock(SPItem *item, SPDesktop *desktop) {
2900     if (item->isLocked()) {
2901         item->setLocked(FALSE);
2902     }
2905 static void unhide(SPItem *item, SPDesktop *desktop) {
2906     if (desktop->itemIsHidden(item)) {
2907         item->setExplicitlyHidden(FALSE);
2908     }
2911 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2912     if (!dt) return;
2913         
2914     SPObject *root;
2915     if (layer_only) {
2916         root = dt->currentLayer();
2917     } else {
2918         root = dt->currentRoot();
2919     }
2920     
2921     itemtree_map(f, root, dt);
2924 void unlock_all(SPDesktop *dt) {
2925     process_all(&unlock, dt, true);
2928 void unlock_all_in_all_layers(SPDesktop *dt) {
2929     process_all(&unlock, dt, false);
2932 void unhide_all(SPDesktop *dt) {
2933     process_all(&unhide, dt, true);
2936 void unhide_all_in_all_layers(SPDesktop *dt) {
2937     process_all(&unhide, dt, false);
2940 /*
2941   Local Variables:
2942   mode:c++
2943   c-file-style:"stroustrup"
2944   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2945   indent-tabs-mode:nil
2946   fill-column:99
2947   End:
2948 */
2949 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :