Code

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