Code

start switching sp_repr_new* over to XML::Document::create*, and rename create method...
[inkscape.git] / src / selection-chemistry.cpp
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /*
4  * Miscellanous operations on selected items
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Frank Felfe <innerspace@iname.com>
9  *   MenTaLguY <mental@rydia.net>
10  *   bulia byak <buliabyak@users.sf.net>
11  *   Andrius R. <knutux@gmail.com>
12  *
13  * Copyright (C) 1999-2006 authors
14  * Copyright (C) 2001-2002 Ximian, Inc.
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include <gtkmm/clipboard.h>
25 #include "svg/svg.h"
26 #include "inkscape.h"
27 #include "desktop.h"
28 #include "desktop-style.h"
29 #include "selection.h"
30 #include "tools-switch.h"
31 #include "desktop-handles.h"
32 #include "message-stack.h"
33 #include "sp-item-transform.h"
34 #include "marker.h"
35 #include "sp-use.h"
36 #include "sp-textpath.h"
37 #include "sp-tspan.h"
38 #include "sp-flowtext.h"
39 #include "sp-flowregion.h"
40 #include "text-editing.h"
41 #include "text-context.h"
42 #include "connector-context.h"
43 #include "sp-path.h"
44 #include "sp-conn-end.h"
45 #include "dropper-context.h"
46 #include <glibmm/i18n.h>
47 #include "libnr/nr-matrix-rotate-ops.h"
48 #include "libnr/nr-matrix-translate-ops.h"
49 #include "libnr/nr-rotate-fns.h"
50 #include "libnr/nr-scale-ops.h"
51 #include "libnr/nr-scale-translate-ops.h"
52 #include "libnr/nr-translate-matrix-ops.h"
53 #include "libnr/nr-translate-scale-ops.h"
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "prefs-utils.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include "helper/units.h"
73 #include "sp-item.h"
74 #include "unit-constants.h"
75 using NR::X;
76 using NR::Y;
78 #include "selection-chemistry.h"
80 /* fixme: find a better place */
81 GSList *clipboard = NULL;
82 GSList *defs_clipboard = NULL;
83 SPCSSAttr *style_clipboard = NULL;
84 NR::Rect size_clipboard(NR::Point(0,0), NR::Point(0,0));
86 static void sp_copy_stuff_used_by_item(GSList **defs_clip, SPItem *item, const GSList *items);
88 /**
89  * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
90  * then prepends the copy to 'clip'.
91  */
92 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip)
93 {
94     Inkscape::XML::Node *copy = repr->duplicate();
96     // copy complete inherited style
97     SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
98     sp_repr_css_set(copy, css, "style");
99     sp_repr_css_attr_unref(css);
101     // write the complete accumulated transform passed to us
102     // (we're dealing with unattached repr, so we write to its attr 
103     // instead of using sp_item_set_transform)
104     gchar affinestr[80];
105     if (sp_svg_transform_write(affinestr, 79, full_t)) {
106         copy->setAttribute("transform", affinestr);
107     } else {
108         copy->setAttribute("transform", NULL);
109     }
111     *clip = g_slist_prepend(*clip, copy);
114 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
117     // Copy stuff referenced by all items to defs_clip:
118     if (defs_clip) {
119         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
120             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
121         }
122         *defs_clip = g_slist_reverse(*defs_clip);
123     }
125     // Store style:
126     if (style_clip) {
127         SPItem *item = SP_ITEM (items->data); // take from the first selected item
128         *style_clip = take_style_from_item (item);
129     }
131     if (clip) {
132         // Sort items:
133         GSList *sorted_items = g_slist_copy ((GSList *) items);
134         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
136         // Copy item reprs:
137         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
138             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
139         }
141         *clip = g_slist_reverse(*clip);
142         g_slist_free ((GSList *) sorted_items);
143     }
146 /**
147  * Add gradients/patterns/markers referenced by copied objects to defs.
148  * Iterates through 'defs_clip', and for each item it adds the data
149  * repr into the global defs.
150  */
151 void
152 paste_defs (GSList **defs_clip, SPDocument *doc)
154     if (!defs_clip)
155         return;
157     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
158         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
159         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
160         gchar const *id = repr->attribute("id");
161         if (!id || !doc->getObjectById(id)) {
162             Inkscape::XML::Node *copy = repr->duplicate();
163             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
164             Inkscape::GC::release(copy);
165         }
166     }
169 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
171     paste_defs (defs_clip, document);
173     GSList *copied = NULL;
174     // add objects to document
175     for (GSList *l = *clip; l != NULL; l = l->next) {
176         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
177         Inkscape::XML::Node *copy = repr->duplicate();
179         // premultiply the item transform by the accumulated parent transform in the paste layer
180         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
181         if (!local.test_identity()) {
182             gchar const *t_str = copy->attribute("transform");
183             NR::Matrix item_t (NR::identity());
184             if (t_str)
185                 sp_svg_transform_read(t_str, &item_t);
186             item_t *= local.inverse();
187             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
188             gchar affinestr[80];
189             if (sp_svg_transform_write(affinestr, 79, item_t)) {
190                 copy->setAttribute("transform", affinestr);
191             } else {
192                 copy->setAttribute("transform", NULL);
193             }
194         }
196         parent->appendChildRepr(copy);
197         copied = g_slist_prepend(copied, copy);
198         Inkscape::GC::release(copy);
199     }
200     return copied;
203 void sp_selection_delete_impl(const GSList *items)
205     for (const GSList *i = items ; i ; i = i->next ) {
206         sp_object_ref((SPObject *)i->data, NULL);
207     }
208     for (const GSList *i = items; i != NULL; i = i->next) {
209         SPItem *item = (SPItem *) i->data;
210         SP_OBJECT(item)->deleteObject();
211         sp_object_unref((SPObject *)item, NULL);
212     }
216 void sp_selection_delete()
218     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
219     if (desktop == NULL) {
220         return;
221     }
223     if (tools_isactive (desktop, TOOLS_TEXT))
224         if (sp_text_delete_selection(desktop->event_context)) {
225             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
226                              _("Delete text"));
227             return;
228         }
230     Inkscape::Selection *selection = sp_desktop_selection(desktop);
232     // check if something is selected
233     if (selection->isEmpty()) {
234         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
235         return;
236     }
238     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
239     selection->clear();
240     sp_selection_delete_impl (selected);
241     g_slist_free ((GSList *) selected);
243     /* a tool may have set up private information in it's selection context
244      * that depends on desktop items.  I think the only sane way to deal with
245      * this currently is to reset the current tool, which will reset it's
246      * associated selection context.  For example: deleting an object
247      * while moving it around the canvas.
248      */
249     tools_switch ( desktop, tools_active ( desktop ) );
251     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
252                      _("Delete"));
255 /* fixme: sequencing */
256 void sp_selection_duplicate()
258     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
259     if (desktop == NULL)
260         return;
262     Inkscape::Selection *selection = sp_desktop_selection(desktop);
264     // check if something is selected
265     if (selection->isEmpty()) {
266         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
267         return;
268     }
270     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
272     selection->clear();
274     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
275     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
277     GSList *newsel = NULL;
279     while (reprs) {
280         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
281         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
283         parent->appendChild(copy);
285         newsel = g_slist_prepend(newsel, copy);
286         reprs = g_slist_remove(reprs, reprs->data);
287         Inkscape::GC::release(copy);
288     }
290     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
291                      _("Duplicate"));
293     selection->setReprList(newsel);
295     g_slist_free(newsel);
298 void sp_edit_clear_all()
300     SPDesktop *dt = SP_ACTIVE_DESKTOP;
301     if (!dt)
302         return;
304     SPDocument *doc = sp_desktop_document(dt);
305     sp_desktop_selection(dt)->clear();
307     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
308     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
310     while (items) {
311         SP_OBJECT (items->data)->deleteObject();
312         items = g_slist_remove(items, items->data);
313     }
315     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
316                      _("Delete all"));
319 GSList *
320 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
322     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
323         if (SP_IS_ITEM(child) &&
324             !desktop->isLayer(SP_ITEM(child)) &&
325             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
326             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
327             (!exclude || !g_slist_find ((GSList *) exclude, child))
328             )
329         {
330             list = g_slist_prepend (list, SP_ITEM(child));
331         }
333         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
334             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
335         }
336     }
338     return list;
341 void sp_edit_select_all_full (bool force_all_layers, bool invert)
343     SPDesktop *dt = SP_ACTIVE_DESKTOP;
344     if (!dt)
345         return;
347     Inkscape::Selection *selection = sp_desktop_selection(dt);
349     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
351     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
352     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
353     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
355     GSList *items = NULL;
357     const GSList *exclude = NULL;
358     if (invert) {
359         exclude = selection->itemList();
360     }
362     if (force_all_layers)
363         inlayer = PREFS_SELECTION_ALL;
365     switch (inlayer) {
366         case PREFS_SELECTION_LAYER: {
367         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
368              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
369         return;
371         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
373         for (GSList *i = all_items; i; i = i->next) {
374             SPItem *item = SP_ITEM (i->data);
376             if (item && (!onlysensitive || !item->isLocked())) {
377                 if (!onlyvisible || !dt->itemIsHidden(item)) {
378                     if (!dt->isLayer(item)) {
379                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
380                             items = g_slist_prepend (items, item); // leave it in the list
381                         }
382                     }
383                 }
384             }
385         }
387         g_slist_free (all_items);
388             break;
389         }
390         case PREFS_SELECTION_LAYER_RECURSIVE: {
391             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
392             break;
393         }
394         default: {
395         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
396             break;
397     }
398     }
400     selection->setList (items);
402     if (items) {
403         g_slist_free (items);
404     }
407 void sp_edit_select_all ()
409     sp_edit_select_all_full (false, false);
412 void sp_edit_select_all_in_all_layers ()
414     sp_edit_select_all_full (true, false);
417 void sp_edit_invert ()
419     sp_edit_select_all_full (false, true);
422 void sp_edit_invert_in_all_layers ()
424     sp_edit_select_all_full (true, true);
427 void sp_selection_group()
429     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
430     if (desktop == NULL)
431         return;
433     SPDocument *document = sp_desktop_document (desktop);
434     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
436     Inkscape::Selection *selection = sp_desktop_selection(desktop);
438     // Check if something is selected.
439     if (selection->isEmpty()) {
440         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>two or more objects</b> to group."));
441         return;
442     }
444     GSList const *l = (GSList *) selection->reprList();
446     // Check if at least two objects are selected.
447     if (l->next == NULL) {
448         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>at least two objects</b> to group."));
449         return;
450     }
452     GSList *p = g_slist_copy((GSList *) l);
454     selection->clear();
456     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
458     // Remember the position and parent of the topmost object.
459     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
460     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
462     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
464     while (p) {
465         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
467         if (current->parent() == topmost_parent) {
468             Inkscape::XML::Node *spnew = current->duplicate();
469             sp_repr_unparent(current);
470             group->appendChild(spnew);
471             Inkscape::GC::release(spnew);
472             topmost --; // only reduce count for those items deleted from topmost_parent
473         } else { // move it to topmost_parent first
474                 GSList *temp_clip = NULL;
476                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
477                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
478                 gchar const *t_str = current->attribute("transform");
479                 NR::Matrix item_t (NR::identity());
480                 if (t_str)
481                     sp_svg_transform_read(t_str, &item_t);
482                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
483                 //FIXME: when moving both clone and original from a transformed group (either by
484                 //grouping into another parent, or by cut/paste) the transform from the original's
485                 //parent becomes embedded into original itself, and this affects its clones. Fix
486                 //this by remembering the transform diffs we write to each item into an array and
487                 //then, if this is clone, looking up its original in that array and pre-multiplying
488                 //it by the inverse of that original's transform diff.
490                 sp_selection_copy_one (current, item_t, &temp_clip);
491                 sp_repr_unparent(current);
493                 // paste into topmost_parent (temporarily)
494                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
495                 if (temp_clip) g_slist_free (temp_clip);
496                 if (copied) { // if success,
497                     // take pasted object (now in topmost_parent)
498                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
499                     // make a copy
500                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
501                     // remove pasted
502                     sp_repr_unparent(in_topmost);
503                     // put its copy into group
504                     group->appendChild(spnew);
505                     Inkscape::GC::release(spnew);
506                     g_slist_free (copied);
507                 }
508         }
509         p = g_slist_remove(p, current);
510     }
512     // Add the new group to the topmost members' parent
513     topmost_parent->appendChild(group);
515     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
516     group->setPosition(topmost + 1);
518     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
519                      _("Group"));
521     selection->set(group);
522     Inkscape::GC::release(group);
525 void sp_selection_ungroup()
527     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
528     if (desktop == NULL)
529         return;
531     Inkscape::Selection *selection = sp_desktop_selection(desktop);
533     if (selection->isEmpty()) {
534         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
535         return;
536     }
538     GSList *items = g_slist_copy((GSList *) selection->itemList());
539     selection->clear();
541     // Get a copy of current selection.
542     GSList *new_select = NULL;
543     bool ungrouped = false;
544     for (GSList *i = items;
545          i != NULL;
546          i = i->next)
547     {
548         SPItem *group = (SPItem *) i->data;
550         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
551         if (!SP_IS_OBJECT(group)) {
552             continue;
553         }
555         /* We do not allow ungrouping <svg> etc. (lauris) */
556         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
557             // keep the non-group item in the new selection
558             selection->add(group);
559             continue;
560         }
562         GSList *children = NULL;
563         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
564         sp_item_group_ungroup(SP_GROUP(group), &children, false);
565         ungrouped = true;
566         // Add ungrouped items to the new selection.
567         new_select = g_slist_concat(new_select, children);
568     }
570     if (new_select) { // Set new selection.
571         selection->addList(new_select);
572         g_slist_free(new_select);
573     }
574     if (!ungrouped) {
575         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
576     }
578     g_slist_free(items);
580     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
581                      _("Ungroup"));
584 static SPGroup *
585 sp_item_list_common_parent_group(const GSList *items)
587     if (!items) {
588         return NULL;
589     }
590     SPObject *parent = SP_OBJECT_PARENT(items->data);
591     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
592     if (!SP_IS_GROUP(parent)) {
593         return NULL;
594     }
595     for (items = items->next; items; items = items->next) {
596         if (SP_OBJECT_PARENT(items->data) != parent) {
597             return NULL;
598         }
599     }
601     return SP_GROUP(parent);
604 /** Finds out the minimum common bbox of the selected items
605  */
606 NR::Rect
607 enclose_items(const GSList *items)
609     g_assert(items != NULL);
611     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
613     for (GSList *i = items->next; i; i = i->next) {
614         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
615     }
617     return r;
620 SPObject *
621 prev_sibling(SPObject *child)
623     SPObject *parent = SP_OBJECT_PARENT(child);
624     if (!SP_IS_GROUP(parent)) {
625         return NULL;
626     }
627     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
628         if (i->next == child)
629             return i;
630     }
631     return NULL;
634 void
635 sp_selection_raise()
637     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
638     if (!desktop)
639         return;
641     Inkscape::Selection *selection = sp_desktop_selection(desktop);
643     GSList const *items = (GSList *) selection->itemList();
644     if (!items) {
645         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
646         return;
647     }
649     SPGroup const *group = sp_item_list_common_parent_group(items);
650     if (!group) {
651         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
652         return;
653     }
655     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
657     /* construct reverse-ordered list of selected children */
658     GSList *rev = g_slist_copy((GSList *) items);
659     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
661     // find out the common bbox of the selected items
662     NR::Rect selected = enclose_items(items);
664     // for all objects in the selection (starting from top)
665     while (rev) {
666         SPObject *child = SP_OBJECT(rev->data);
667         // for each selected object, find the next sibling
668         for (SPObject *newref = child->next; newref; newref = newref->next) {
669             // if the sibling is an item AND overlaps our selection,
670             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
671                 // AND if it's not one of our selected objects,
672                 if (!g_slist_find((GSList *) items, newref)) {
673                     // move the selected object after that sibling
674                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
675                 }
676                 break;
677             }
678         }
679         rev = g_slist_remove(rev, child);
680     }
682     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
683                      _("Raise"));
686 void sp_selection_raise_to_top()
688     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
689     if (desktop == NULL)
690         return;
692     SPDocument *document = sp_desktop_document(desktop);
693     Inkscape::Selection *selection = sp_desktop_selection(desktop);
695     if (selection->isEmpty()) {
696         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
697         return;
698     }
700     GSList const *items = (GSList *) selection->itemList();
702     SPGroup const *group = sp_item_list_common_parent_group(items);
703     if (!group) {
704         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
705         return;
706     }
708     GSList *rl = g_slist_copy((GSList *) selection->reprList());
709     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
711     for (GSList *l = rl; l != NULL; l = l->next) {
712         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
713         repr->setPosition(-1);
714     }
716     g_slist_free(rl);
718     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
719                      _("Raise to top"));
722 void
723 sp_selection_lower()
725     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
726     if (desktop == NULL)
727         return;
729     Inkscape::Selection *selection = sp_desktop_selection(desktop);
731     GSList const *items = (GSList *) selection->itemList();
732     if (!items) {
733         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
734         return;
735     }
737     SPGroup const *group = sp_item_list_common_parent_group(items);
738     if (!group) {
739         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
740         return;
741     }
743     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
745     // find out the common bbox of the selected items
746     NR::Rect selected = enclose_items(items);
748     /* construct direct-ordered list of selected children */
749     GSList *rev = g_slist_copy((GSList *) items);
750     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
751     rev = g_slist_reverse(rev);
753     // for all objects in the selection (starting from top)
754     while (rev) {
755         SPObject *child = SP_OBJECT(rev->data);
756         // for each selected object, find the prev sibling
757         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
758             // if the sibling is an item AND overlaps our selection,
759             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
760                 // AND if it's not one of our selected objects,
761                 if (!g_slist_find((GSList *) items, newref)) {
762                     // move the selected object before that sibling
763                     SPObject *put_after = prev_sibling(newref);
764                     if (put_after)
765                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
766                     else
767                         SP_OBJECT_REPR(child)->setPosition(0);
768                 }
769                 break;
770             }
771         }
772         rev = g_slist_remove(rev, child);
773     }
775     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
776                      _("Lower"));
780 void sp_selection_lower_to_bottom()
782     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
783     if (desktop == NULL)
784         return;
786     SPDocument *document = sp_desktop_document(desktop);
787     Inkscape::Selection *selection = sp_desktop_selection(desktop);
789     if (selection->isEmpty()) {
790         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
791         return;
792     }
794     GSList const *items = (GSList *) selection->itemList();
796     SPGroup const *group = sp_item_list_common_parent_group(items);
797     if (!group) {
798         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
799         return;
800     }
802     GSList *rl;
803     rl = g_slist_copy((GSList *) selection->reprList());
804     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
805     rl = g_slist_reverse(rl);
807     for (GSList *l = rl; l != NULL; l = l->next) {
808         gint minpos;
809         SPObject *pp, *pc;
810         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
811         pp = document->getObjectByRepr(sp_repr_parent(repr));
812         minpos = 0;
813         g_assert(SP_IS_GROUP(pp));
814         pc = sp_object_first_child(pp);
815         while (!SP_IS_ITEM(pc)) {
816             minpos += 1;
817             pc = pc->next;
818         }
819         repr->setPosition(minpos);
820     }
822     g_slist_free(rl);
824     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
825                      _("Lower to bottom"));
828 void
829 sp_undo(SPDesktop *desktop, SPDocument *)
831         if (!sp_document_undo(sp_desktop_document(desktop)))
832             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
835 void
836 sp_redo(SPDesktop *desktop, SPDocument *)
838         if (!sp_document_redo(sp_desktop_document(desktop)))
839             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
842 void sp_selection_cut()
844     sp_selection_copy();
845     sp_selection_delete();
848 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
850     SPGradient *ref = gradient;
852     while (ref) {
853         // climb up the refs, copying each one in the chain
854         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
855         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
857         ref = ref->ref->getObject();
858     }
861 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
863     SPPattern *ref = pattern;
865     while (ref) {
866         // climb up the refs, copying each one in the chain
867         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
868         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
870         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
871         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
872             if (!SP_IS_ITEM (child))
873                 continue;
874             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
875         }
877         ref = ref->ref->getObject();
878     }
881 void sp_copy_single (GSList **defs_clip, SPObject *thing)
883     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
884     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
888 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
890     SPItem *path = sp_textpath_get_path_item (tp);
891     if (!path)
892         return;
893     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
894         return;
895     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
896     *defs_clip = g_slist_prepend (*defs_clip, repr);
899 /**
900  * Copies things like patterns, markers, gradients, etc.
901  */
902 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
904     SPStyle *style = SP_OBJECT_STYLE (item);
906     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
907         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
908         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
909             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
910         if (SP_IS_PATTERN (server))
911             sp_copy_pattern (defs_clip, SP_PATTERN(server));
912     }
914     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
915         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
916         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
917             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
918         if (SP_IS_PATTERN (server))
919             sp_copy_pattern (defs_clip, SP_PATTERN(server));
920     }
922     // For shapes, copy all of the shape's markers into defs_clip
923     if (SP_IS_SHAPE (item)) {
924         SPShape *shape = SP_SHAPE (item);
925         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
926             if (shape->marker[i]) {
927                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
928             }
929         }
930     }
932     if (SP_IS_TEXT_TEXTPATH (item)) {
933         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
934     }
936     if (item->clip_ref->getObject()) {
937         sp_copy_single (defs_clip, item->clip_ref->getObject());
938     }
940     if (item->mask_ref->getObject()) {
941         SPObject *mask = item->mask_ref->getObject();
942         sp_copy_single (defs_clip, mask);
943         // recurse into the mask for its gradients etc.
944         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
945             if (SP_IS_ITEM(o))
946                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
947         }
948     }
950     if (style->filter.filter) {
951         SPObject *filter = style->filter.filter;
952         if (SP_IS_FILTER(filter)) {
953             sp_copy_single (defs_clip, filter);
954         }
955     }
957     // recurse
958     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
959         if (SP_IS_ITEM(o))
960             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
961     }
964 /**
965  * \pre item != NULL
966  */
967 SPCSSAttr *
968 take_style_from_item (SPItem *item)
970     // write the complete cascaded style, context-free
971     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
972     if (css == NULL)
973         return NULL;
975     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
976         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
977         // if this is a text with exactly one tspan child, merge the style of that tspan as well
978         // If this is a group, merge the style of its topmost (last) child with style
979         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
980             if (SP_OBJECT_STYLE (last_element) != NULL) {
981                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
982                 if (temp) {
983                     sp_repr_css_merge (css, temp);
984                     sp_repr_css_attr_unref (temp);
985                 }
986                 break;
987             }
988         }
989     }
990     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
991         // do not copy text properties from non-text objects, it's confusing
992         css = sp_css_attr_unset_text (css);
993     }
995     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
996     double ex = NR::expansion(sp_item_i2doc_affine(item));
997     if (ex != 1.0) {
998         css = sp_css_attr_scale (css, ex);
999     }
1001     return css;
1005 void sp_selection_copy()
1007     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1008     if (desktop == NULL)
1009         return;
1011     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1013     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1014         sp_dropper_context_copy(desktop->event_context);
1015         return; // copied color under cursor, nothing else to do
1016     }
1018     // check if something is selected
1019     if (selection->isEmpty()) {
1020         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1021         return;
1022     }
1024     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1026     // 0. Copy text to system clipboard
1027     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1028     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1029     Glib::ustring text;
1030     if (tools_isactive (desktop, TOOLS_TEXT)) {
1031         text = sp_text_get_selected_text(desktop->event_context);
1032     }
1034     if (text.empty()) {
1035         guint texts = 0;
1036         for (GSList *i = (GSList *) items; i; i = i->next) {
1037             SPItem *item = SP_ITEM (i->data);
1038             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1039                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1040                     text += " ";
1041                 gchar *this_text = sp_te_get_string_multiline (item);
1042                 if (this_text) {
1043                     text += this_text;
1044                     g_free(this_text);
1045                 }
1046                 texts++;
1047             }
1048         }
1049     }
1050     if (!text.empty()) {
1051         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1052         refClipboard->set_text(text);
1053     }
1055     // clear old defs clipboard
1056     while (defs_clipboard) {
1057         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1058         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1059     }
1061     // clear style clipboard
1062     if (style_clipboard) {
1063         sp_repr_css_attr_unref (style_clipboard);
1064         style_clipboard = NULL;
1065     }
1067     //clear main clipboard
1068     while (clipboard) {
1069         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1070         clipboard = g_slist_remove(clipboard, clipboard->data);
1071     }
1073     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1075     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1076         SPStyle *const query = sp_style_new();
1077         if (sp_desktop_query_style_all (desktop, query)) {
1078             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1079             if (css != NULL) {
1080                 // clear style clipboard
1081                 if (style_clipboard) {
1082                     sp_repr_css_attr_unref (style_clipboard);
1083                     style_clipboard = NULL;
1084                 }
1085                 //sp_repr_css_print (css);
1086                 style_clipboard = css;
1087             }
1088         }
1089         g_free (query);
1090     }
1092     size_clipboard = selection->bounds();
1094     g_slist_free ((GSList *) items);
1097 void sp_selection_paste(bool in_place)
1099     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1101     if (desktop == NULL) {
1102         return;
1103     }
1105     SPDocument *document = sp_desktop_document(desktop);
1107     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1108         return;
1109     }
1111     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1113     if (tools_isactive (desktop, TOOLS_TEXT)) {
1114         if (sp_text_paste_inline(desktop->event_context))
1115             return; // pasted from system clipboard into text, nothing else to do
1116     }
1118     // check if something is in the clipboard
1119     if (clipboard == NULL) {
1120         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1121         return;
1122     }
1124     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1125     // add pasted objects to selection
1126     selection->setReprList((GSList const *) copied);
1127     g_slist_free (copied);
1129     if (!in_place) {
1130         sp_document_ensure_up_to_date(document);
1132         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1134         /* Snap the offset of the new item(s) to the grid */
1135         /* FIXME: this gridsnap fiddling is a hack. */
1136         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1137         gdouble const curr_gridsnap = s.getDistance();
1138         s.setDistance(NR_HUGE);
1139         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1140         s.setDistance(curr_gridsnap);
1141         sp_selection_move_relative(selection, m);
1142     }
1144     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1145                      _("Paste"));
1148 void sp_selection_paste_style()
1150     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1151     if (desktop == NULL) return;
1153     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1155     // check if something is in the clipboard
1156     if (clipboard == NULL) {
1157         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1158         return;
1159     }
1161     // check if something is selected
1162     if (selection->isEmpty()) {
1163         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1164         return;
1165     }
1167     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1169     sp_desktop_set_style (desktop, style_clipboard);
1171     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1172                      _("Paste style"));
1175 void sp_selection_paste_size (bool apply_x, bool apply_y)
1177     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1178     if (desktop == NULL) return;
1180     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1182     // check if something is in the clipboard
1183     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1184         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1185         return;
1186     }
1188     // check if something is selected
1189     if (selection->isEmpty()) {
1190         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1191         return;
1192     }
1194     NR::Rect current = selection->bounds();
1195     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1196         return;
1197     }
1199     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1200     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1202     sp_selection_scale_relative (selection, current.midpoint(), 
1203                                  NR::scale(
1204                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1205                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1207     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1208                      _("Paste size"));
1211 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1213     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1214     if (desktop == NULL) return;
1216     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1218     // check if something is in the clipboard
1219     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1220         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1221         return;
1222     }
1224     // check if something is selected
1225     if (selection->isEmpty()) {
1226         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1227         return;
1228     }
1230     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1231         SPItem *item = SP_ITEM(l->data);
1233         NR::Rect current = sp_item_bbox_desktop(item);
1234         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1235             continue;
1236         }
1238         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1239         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1241         sp_item_scale_rel (item,
1242                                  NR::scale(
1243                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1244                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1246     }
1248     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1249                      _("Paste size separately"));
1252 void sp_selection_to_next_layer ()
1254     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1256     Inkscape::Selection *selection = sp_desktop_selection(dt);
1258     // check if something is selected
1259     if (selection->isEmpty()) {
1260         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1261         return;
1262     }
1264     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1266     bool no_more = false; // Set to true, if no more layers above
1267     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1268     if (next) {
1269         GSList *temp_clip = NULL;
1270         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1271         sp_selection_delete_impl (items);
1272         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1273         GSList *copied;
1274         if(next) {
1275             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1276         } else {
1277             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1278             no_more = true;
1279         }
1280         selection->setReprList((GSList const *) copied);
1281         g_slist_free (copied);
1282         if (temp_clip) g_slist_free (temp_clip);
1283         if (next) dt->setCurrentLayer(next);
1284         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1285                          _("Raise to next layer"));
1286     } else {
1287         no_more = true;
1288     }
1290     if (no_more) {
1291         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1292     }
1294     g_slist_free ((GSList *) items);
1297 void sp_selection_to_prev_layer ()
1299     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1301     Inkscape::Selection *selection = sp_desktop_selection(dt);
1303     // check if something is selected
1304     if (selection->isEmpty()) {
1305         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1306         return;
1307     }
1309     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1311     bool no_more = false; // Set to true, if no more layers below
1312     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1313     if (next) {
1314         GSList *temp_clip = NULL;
1315         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1316         sp_selection_delete_impl (items);
1317         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1318         GSList *copied;
1319         if(next) {
1320             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1321         } else {
1322             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1323             no_more = true;
1324         }
1325         selection->setReprList((GSList const *) copied);
1326         g_slist_free (copied);
1327         if (temp_clip) g_slist_free (temp_clip);
1328         if (next) dt->setCurrentLayer(next);
1329         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1330                          _("Lower to previous layer"));
1331     } else {
1332         no_more = true;
1333     }
1335     if (no_more) {
1336         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1337     }
1339     g_slist_free ((GSList *) items);
1342 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1343 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1344 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1345 that case, items are already in the new position, but the repr is in the old, and this function
1346 then simply updates the repr from item->transform.
1347  */
1348 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1350     if (selection->isEmpty())
1351         return;
1353     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1354         SPItem *item = SP_ITEM(l->data);
1356         NR::Point old_center(0,0);
1357         if (set_i2d && item->isCenterSet())
1358             old_center = item->getCenter();
1360 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1361          At the time of writing, this is the only place to re-enable. */
1362         sp_item_update_cns(*item, selection->desktop());
1363 #endif
1365         // we're moving both a clone and its original?
1366         bool transform_clone_with_original = (SP_IS_USE(item) && selection->includes( sp_use_get_original (SP_USE(item)) ));
1367         // ...both a text-on-path and its path?
1368         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)))) ));
1369         // ...both a flowtext and its frame?
1370         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)
1371         // ...both an offset and its source?
1372         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1373        
1374         // If we're moving a connector, we want to detach it
1375         // from shapes that aren't part of the selection, but
1376         // leave it attached if they are
1377         if (cc_item_is_connector(item)) {
1378             SPItem *attItem[2];
1379             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1380             
1381             for (int n = 0; n < 2; ++n) {
1382                 if (!selection->includes(attItem[n])) {
1383                     sp_conn_end_detach(item, n);
1384                 }
1385             }
1386         }
1387         
1388         // "clones are unmoved when original is moved" preference
1389         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1390         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1391         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1393         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1394         // transform of its original and respond to it itself. Without this, a clone is doubly
1395         // transformed, very unintuitive.
1396       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1397       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1398       // Same for linked offset if we are also moving its source: do not move it.
1399         if (transform_textpath_with_path || transform_offset_with_source) {
1400                 // restore item->transform field from the repr, in case it was changed by seltrans
1401             sp_object_read_attr (SP_OBJECT (item), "transform");
1403         } else if (transform_flowtext_with_frame) {
1404             // apply the inverse of the region's transform to the <use> so that the flow remains
1405             // the same (even though the output itself gets transformed)
1406             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1407                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1408                     continue;
1409                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1410                     if (!SP_IS_USE(use)) continue;
1411                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1412                 }
1413             }
1414         } else if (transform_clone_with_original) {
1415             // We are transforming a clone along with its original. The below matrix juggling is
1416             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1417             // transform and its move compensation are both cancelled out.
1419             // restore item->transform field from the repr, in case it was changed by seltrans
1420             sp_object_read_attr (SP_OBJECT (item), "transform");
1422             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1423             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1424             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1425             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1426             NR::Matrix result = t_inv * item->transform * t;
1428             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1429                 // we need to cancel out the move compensation, too
1431                 // find out the clone move, same as in sp_use_move_compensate
1432                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1433                 NR::Matrix clone_move = parent.inverse() * t * parent;
1435                 if (prefs_parallel) {
1436                     NR::Matrix move = result * clone_move * t_inv;
1437                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1439                 } else if (prefs_unmoved) {
1440                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1441                     //    clone_move = NR::identity();
1442                     NR::Matrix move = result * clone_move;
1443                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1444                 }
1446             } else {
1447                 // just apply the result
1448                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1449             }
1451         } else {
1452             if (set_i2d) {
1453                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1454             }
1455             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1456         }
1458         // if we're moving the actual object, not just updating the repr, we can transform the
1459         // center by the same matrix (only necessary for non-translations)
1460         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1461             item->setCenter(old_center * affine);
1462             SP_OBJECT(item)->updateRepr();
1463         }
1464     }
1467 void sp_selection_remove_transform()
1469     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1470     if (desktop == NULL)
1471         return;
1473     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1475     GSList const *l = (GSList *) selection->reprList();
1476     while (l != NULL) {
1477         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1478         l = l->next;
1479     }
1481     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1482                      _("Remove transform"));
1485 void
1486 sp_selection_scale_absolute(Inkscape::Selection *selection,
1487                             double const x0, double const x1,
1488                             double const y0, double const y1)
1490     if (selection->isEmpty())
1491         return;
1493     NR::Rect const bbox(selection->bounds());
1494     if (bbox.isEmpty()) {
1495         return;
1496     }
1498     NR::translate const p2o(-bbox.min());
1500     NR::scale const newSize(x1 - x0,
1501                             y1 - y0);
1502     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1503     NR::translate const o2n(x0, y0);
1504     NR::Matrix const final( p2o * scale * o2n );
1506     sp_selection_apply_affine(selection, final);
1510 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1512     if (selection->isEmpty())
1513         return;
1515     NR::Rect const bbox(selection->bounds());
1517     if (bbox.isEmpty()) {
1518         return;
1519     }
1521     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1522     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1523          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1524     {
1525         return;
1526     }
1528     NR::translate const n2d(-align);
1529     NR::translate const d2n(align);
1530     NR::Matrix const final( n2d * scale * d2n );
1531     sp_selection_apply_affine(selection, final);
1534 void
1535 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1537     NR::translate const d2n(center);
1538     NR::translate const n2d(-center);
1539     NR::rotate const rotate(rotate_degrees(angle_degrees));
1540     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1541     sp_selection_apply_affine(selection, final);
1544 void
1545 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1547     NR::translate const d2n(align);
1548     NR::translate const n2d(-align);
1549     NR::Matrix const skew(1, dy,
1550                           dx, 1,
1551                           0, 0);
1552     NR::Matrix const final( n2d * skew * d2n );
1553     sp_selection_apply_affine(selection, final);
1556 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1558     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1561 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1563     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1567 /**
1568  * \brief sp_selection_rotate_90
1569  *
1570  * This function rotates selected objects 90 degrees clockwise.
1571  *
1572  */
1574 void sp_selection_rotate_90_cw()
1576     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1578     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1580     if (selection->isEmpty())
1581         return;
1583     GSList const *l = selection->itemList();
1584     NR::rotate const rot_neg_90(NR::Point(0, -1));
1585     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1586         SPItem *item = SP_ITEM(l2->data);
1587         sp_item_rotate_rel(item, rot_neg_90);
1588     }
1590     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1591                      _("Rotate 90&#176; CW"));
1595 /**
1596  * \brief sp_selection_rotate_90_ccw
1597  *
1598  * This function rotates selected objects 90 degrees counter-clockwise.
1599  *
1600  */
1602 void sp_selection_rotate_90_ccw()
1604     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1606     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1608     if (selection->isEmpty())
1609         return;
1611     GSList const *l = selection->itemList();
1612     NR::rotate const rot_neg_90(NR::Point(0, 1));
1613     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1614         SPItem *item = SP_ITEM(l2->data);
1615         sp_item_rotate_rel(item, rot_neg_90);
1616     }
1618     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1619                      _("Rotate 90&#176; CCW"));
1622 void
1623 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1625     if (selection->isEmpty())
1626         return;
1628     NR::Point center = selection->center();
1630     sp_selection_rotate_relative(selection, center, angle_degrees);
1632     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1633                            ( ( angle_degrees > 0 )
1634                              ? "selector:rotate:ccw"
1635                              : "selector:rotate:cw" ), 
1636                            SP_VERB_CONTEXT_SELECT, 
1637                            _("Rotate"));
1640 /**
1641 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1642 */
1643 void
1644 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1646     if (selection->isEmpty())
1647         return;
1649     NR::Rect const bbox(selection->bounds());
1651     NR::Point center = selection->center();
1653     gdouble const zoom = selection->desktop()->current_zoom();
1654     gdouble const zmove = angle / zoom;
1655     gdouble const r = NR::L2(bbox.max() - center);
1657     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1659     sp_selection_rotate_relative(selection, center, zangle);
1661     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1662                            ( (angle > 0)
1663                              ? "selector:rotate:ccw"
1664                              : "selector:rotate:cw" ),
1665                            SP_VERB_CONTEXT_SELECT, 
1666                            _("Rotate by pixels"));
1669 void
1670 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1672     if (selection->isEmpty())
1673         return;
1675     NR::Rect const bbox(selection->bounds());
1676     NR::Point const center(bbox.midpoint());
1677     double const max_len = bbox.maxExtent();
1679     // you can't scale "do nizhe pola" (below zero)
1680     if ( max_len + grow <= 1e-3 ) {
1681         return;
1682     }
1684     double const times = 1.0 + grow / max_len;
1685     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1687     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1688                            ( (grow > 0)
1689                              ? "selector:scale:larger"
1690                              : "selector:scale:smaller" ),
1691                            SP_VERB_CONTEXT_SELECT,
1692                            _("Scale"));
1695 void
1696 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1698     sp_selection_scale(selection,
1699                        grow_pixels / selection->desktop()->current_zoom());
1702 void
1703 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1705     if (selection->isEmpty())
1706         return;
1708     NR::Point const center(selection->bounds().midpoint());
1709     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1710     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1711                      _("Scale by whole factor"));
1714 void
1715 sp_selection_move(gdouble dx, gdouble dy)
1717     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1718     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1719     if (selection->isEmpty()) {
1720         return;
1721     }
1723     sp_selection_move_relative(selection, dx, dy);
1725     if (dx == 0) {
1726         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1727                                _("Move vertically"));
1728     } else if (dy == 0) {
1729         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1730                                _("Move horizontally"));
1731     } else {
1732         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1733                          _("Move"));
1734     }
1737 void
1738 sp_selection_move_screen(gdouble dx, gdouble dy)
1740     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1742     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1743     if (selection->isEmpty()) {
1744         return;
1745     }
1747     // same as sp_selection_move but divide deltas by zoom factor
1748     gdouble const zoom = desktop->current_zoom();
1749     gdouble const zdx = dx / zoom;
1750     gdouble const zdy = dy / zoom;
1751     sp_selection_move_relative(selection, zdx, zdy);
1753     if (dx == 0) {
1754         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1755                                _("Move vertically by pixels"));
1756     } else if (dy == 0) {
1757         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1758                                _("Move horizontally by pixels"));
1759     } else {
1760         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1761                          _("Move"));
1762     }
1765 namespace {
1767 template <typename D>
1768 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1769                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1771 template <typename D>
1772 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1773                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1775 struct Forward {
1776     typedef SPObject *Iterator;
1778     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1779     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1780     static void dispose(Iterator i) {}
1782     static SPObject *object(Iterator i) { return i; }
1783     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1784 };
1786 struct Reverse {
1787     typedef GSList *Iterator;
1789     static Iterator children(SPObject *o) {
1790         return make_list(o->firstChild(), NULL);
1791     }
1792     static Iterator siblings_after(SPObject *o) {
1793         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1794     }
1795     static void dispose(Iterator i) {
1796         g_slist_free(i);
1797     }
1799     static SPObject *object(Iterator i) {
1800         return reinterpret_cast<SPObject *>(i->data);
1801     }
1802     static Iterator next(Iterator i) { return i->next; }
1804 private:
1805     static GSList *make_list(SPObject *object, SPObject *limit) {
1806         GSList *list=NULL;
1807         while ( object != limit ) {
1808             list = g_slist_prepend(list, object);
1809             object = SP_OBJECT_NEXT(object);
1810         }
1811         return list;
1812     }
1813 };
1817 void
1818 sp_selection_item_next(void)
1820     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1821     g_return_if_fail(desktop != NULL);
1822     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1824     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1825     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1826     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1828     SPObject *root;
1829     if (PREFS_SELECTION_ALL != inlayer) {
1830         root = selection->activeContext();
1831     } else {
1832         root = desktop->currentRoot();
1833     }
1835     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1837     if (item) {
1838         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1839         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1840             scroll_to_show_item(desktop, item);
1841         }
1842     }
1845 void
1846 sp_selection_item_prev(void)
1848     SPDocument *document = SP_ACTIVE_DOCUMENT;
1849     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1850     g_return_if_fail(document != NULL);
1851     g_return_if_fail(desktop != NULL);
1852     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1854     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1855     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1856     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1858     SPObject *root;
1859     if (PREFS_SELECTION_ALL != inlayer) {
1860         root = selection->activeContext();
1861     } else {
1862         root = desktop->currentRoot();
1863     }
1865     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1867     if (item) {
1868         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1869         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1870             scroll_to_show_item(desktop, item);
1871         }
1872     }
1875 namespace {
1877 template <typename D>
1878 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1879                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1881     SPObject *current=root;
1882     while (items) {
1883         SPItem *item=SP_ITEM(items->data);
1884         if ( root->isAncestorOf(item) &&
1885              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1886         {
1887             current = item;
1888             break;
1889         }
1890         items = items->next;
1891     }
1893     GSList *path=NULL;
1894     while ( current != root ) {
1895         path = g_slist_prepend(path, current);
1896         current = SP_OBJECT_PARENT(current);
1897     }
1899     SPItem *next;
1900     // first, try from the current object
1901     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1902     g_slist_free(path);
1904     if (!next) { // if we ran out of objects, start over at the root
1905         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1906     }
1908     return next;
1911 template <typename D>
1912 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1913                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1915     typename D::Iterator children;
1916     typename D::Iterator iter;
1918     SPItem *found=NULL;
1920     if (path) {
1921         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1922         g_assert(SP_OBJECT_PARENT(object) == root);
1923         if (desktop->isLayer(object)) {
1924             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1925         }
1926         iter = children = D::siblings_after(object);
1927     } else {
1928         iter = children = D::children(root);
1929     }
1931     while ( iter && !found ) {
1932         SPObject *object=D::object(iter);
1933         if (desktop->isLayer(object)) {
1934             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1935                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1936             }
1937         } else if ( SP_IS_ITEM(object) &&
1938                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1939                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1940                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1941                     !desktop->isLayer(SP_ITEM(object)) )
1942         {
1943             found = SP_ITEM(object);
1944         }
1945         iter = D::next(iter);
1946     }
1948     D::dispose(children);
1950     return found;
1955 /**
1956  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1957  * \a item.
1958  */
1959 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1961     NR::Rect dbox = desktop->get_display_area();
1962     NR::Rect sbox = sp_item_bbox_desktop(item);
1964     if (dbox.contains(sbox) == false) {
1965         NR::Point const s_dt = sbox.midpoint();
1966         NR::Point const s_w = desktop->d2w(s_dt);
1967         NR::Point const d_dt = dbox.midpoint();
1968         NR::Point const d_w = desktop->d2w(d_dt);
1969         NR::Point const moved_w( d_w - s_w );
1970         gint const dx = (gint) moved_w[X];
1971         gint const dy = (gint) moved_w[Y];
1972         desktop->scroll_world(dx, dy);
1973     }
1977 void
1978 sp_selection_clone()
1980     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1981     if (desktop == NULL)
1982         return;
1984     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1986     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1988     // check if something is selected
1989     if (selection->isEmpty()) {
1990         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1991         return;
1992     }
1994     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1995   
1996     selection->clear();
1997   
1998     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1999     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2001     GSList *newsel = NULL;
2002  
2003     while (reprs) {
2004         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2005         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2007         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2008         sp_repr_set_attr(clone, "x", "0");
2009         sp_repr_set_attr(clone, "y", "0");
2010         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2012         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2013         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2014         
2015         // add the new clone to the top of the original's parent
2016         parent->appendChild(clone);
2018         newsel = g_slist_prepend(newsel, clone);
2019         reprs = g_slist_remove(reprs, sel_repr);
2020         Inkscape::GC::release(clone);
2021     }
2022     
2023     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2024                      _("Clone"));
2026     selection->setReprList(newsel);
2027  
2028     g_slist_free(newsel);
2031 void
2032 sp_selection_unlink()
2034     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2035     if (!desktop)
2036         return;
2038     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2040     if (selection->isEmpty()) {
2041         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2042         return;
2043     }
2045     // Get a copy of current selection.
2046     GSList *new_select = NULL;
2047     bool unlinked = false;
2048     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2049          items != NULL;
2050          items = items->next)
2051     {
2052         SPItem *use = (SPItem *) items->data;
2054         if (!SP_IS_USE(use)) {
2055             // keep the non-yse item in the new selection
2056             new_select = g_slist_prepend(new_select, use);
2057             continue;
2058         }
2060         SPItem *unlink = sp_use_unlink(SP_USE(use));
2061         unlinked = true;
2062         // Add ungrouped items to the new selection.
2063         new_select = g_slist_prepend(new_select, unlink);
2064     }
2066     if (new_select) { // set new selection
2067         selection->clear();
2068         selection->setList(new_select);
2069         g_slist_free(new_select);
2070     }
2071     if (!unlinked) {
2072         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2073     }
2075     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2076                      _("Unlink clone"));
2079 void
2080 sp_select_clone_original()
2082     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2083     if (desktop == NULL)
2084         return;
2086     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2088     SPItem *item = selection->singleItem();
2090     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.");
2092     // Check if other than two objects are selected
2093     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2094         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2095         return;
2096     }
2098     SPItem *original = NULL;
2099     if (SP_IS_USE(item)) {
2100         original = sp_use_get_original (SP_USE(item));
2101     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2102         original = sp_offset_get_source (SP_OFFSET(item));
2103     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2104         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2105     } else if (SP_IS_FLOWTEXT(item)) {
2106         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2107     } else { // it's an object that we don't know what to do with
2108         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2109         return;
2110     }
2112     if (!original) {
2113         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2114         return;
2115     }
2117     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2118         if (SP_IS_DEFS (o)) {
2119             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2120             return;
2121         }
2122     }
2124     if (original) {
2125         selection->clear();
2126         selection->set(original);
2127         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2128             scroll_to_show_item(desktop, original);
2129         }
2130     }
2133 void
2134 sp_selection_tile(bool apply)
2136     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2137     if (desktop == NULL)
2138         return;
2140     SPDocument *document = sp_desktop_document(desktop);
2141     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2143     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2145     // check if something is selected
2146     if (selection->isEmpty()) {
2147         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2148         return;
2149     }
2151     sp_document_ensure_up_to_date(document);
2152     NR::Rect r = selection->bounds();
2153     if (r.isEmpty()) {
2154         return;
2155     }
2157     // calculate the transform to be applied to objects to move them to 0,0
2158     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2159     move_p[NR::Y] = -move_p[NR::Y];
2160     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2162     GSList *items = g_slist_copy((GSList *) selection->itemList());
2164     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2166     // bottommost object, after sorting
2167     SPObject *parent = SP_OBJECT_PARENT (items->data);
2169     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2171     // remember the position of the first item
2172     gint pos = SP_OBJECT_REPR (items->data)->position();
2174     // create a list of duplicates
2175     GSList *repr_copies = NULL;
2176     for (GSList *i = items; i != NULL; i = i->next) {
2177         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2178         repr_copies = g_slist_prepend (repr_copies, dup);
2179     }
2181     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2183     if (apply) {
2184         // delete objects so that their clones don't get alerted; this object will be restored shortly
2185         for (GSList *i = items; i != NULL; i = i->next) {
2186             SPObject *item = SP_OBJECT (i->data);
2187             item->deleteObject (false);
2188         }
2189     }
2191     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2192     // without disturbing clones.
2193     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2194     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2195     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2197     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2198                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2200     // restore compensation setting
2201     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2203     if (apply) {
2204         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2205         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2207         NR::Point min = bounds.min() * parent_transform.inverse();
2208         NR::Point max = bounds.max() * parent_transform.inverse();
2210         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2211         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2212         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2213         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2215         // restore parent and position
2216         SP_OBJECT_REPR (parent)->appendChild(rect);
2217         rect->setPosition(pos > 0 ? pos : 0);
2218         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2220         Inkscape::GC::release(rect);
2222         selection->clear();
2223         selection->set(rectangle);
2224     }
2226     g_slist_free (items);
2228     sp_document_done (document, SP_VERB_EDIT_TILE, 
2229                       _("Objects to pattern"));
2232 void
2233 sp_selection_untile()
2235     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2236     if (desktop == NULL)
2237         return;
2239     SPDocument *document = sp_desktop_document(desktop);
2241     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2243     // check if something is selected
2244     if (selection->isEmpty()) {
2245         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2246         return;
2247     }
2249     GSList *new_select = NULL;
2251     bool did = false;
2253     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2254          items != NULL;
2255          items = items->next) {
2257         SPItem *item = (SPItem *) items->data;
2259         SPStyle *style = SP_OBJECT_STYLE (item);
2261         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2262             continue;
2264         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2266         if (!SP_IS_PATTERN(server))
2267             continue;
2269         did = true;
2271         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2273         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2274         pat_transform *= item->transform;
2276         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2277             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2278             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2280            // FIXME: relink clones to the new canvas objects
2281            // use SPObject::setid when mental finishes it to steal ids of
2283             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2284             sp_document_ensure_up_to_date (document);
2286             NR::Matrix transform( i->transform * pat_transform );
2287             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2289             new_select = g_slist_prepend(new_select, i);
2290         }
2292         SPCSSAttr *css = sp_repr_css_attr_new ();
2293         sp_repr_css_set_property (css, "fill", "none");
2294         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2295     }
2297     if (!did) {
2298         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2299     } else {
2300         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2301                          _("Pattern to objects"));
2302         selection->setList(new_select);
2303     }
2306 void
2307 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2309     if (selection->isEmpty()) {
2310         return;
2311     }
2313     const GSList * reprlst = selection->reprList();
2314     bool filename_search = TRUE;
2315     bool xdpi_search = TRUE;
2316     bool ydpi_search = TRUE;
2318     for(; reprlst != NULL &&
2319             filename_search &&
2320             xdpi_search &&
2321             ydpi_search;
2322         reprlst = reprlst->next) {
2323         const gchar * dpi_string;
2324         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2326         if (filename_search) {
2327             *filename = repr->attribute("inkscape:export-filename");
2328             if (*filename != NULL)
2329                 filename_search = FALSE;
2330         }
2332         if (xdpi_search) {
2333             dpi_string = NULL;
2334             dpi_string = repr->attribute("inkscape:export-xdpi");
2335             if (dpi_string != NULL) {
2336                 *xdpi = atof(dpi_string);
2337                 xdpi_search = FALSE;
2338             }
2339         }
2341         if (ydpi_search) {
2342             dpi_string = NULL;
2343             dpi_string = repr->attribute("inkscape:export-ydpi");
2344             if (dpi_string != NULL) {
2345                 *ydpi = atof(dpi_string);
2346                 ydpi_search = FALSE;
2347             }
2348         }
2349     }
2352 void
2353 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2355     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2356     const gchar * dpi_string;
2358     *filename = repr->attribute("inkscape:export-filename");
2360     dpi_string = NULL;
2361     dpi_string = repr->attribute("inkscape:export-xdpi");
2362     if (dpi_string != NULL) {
2363         *xdpi = atof(dpi_string);
2364     }
2366     dpi_string = NULL;
2367     dpi_string = repr->attribute("inkscape:export-ydpi");
2368     if (dpi_string != NULL) {
2369         *ydpi = atof(dpi_string);
2370     }
2373 void
2374 sp_selection_create_bitmap_copy ()
2376     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2377     if (desktop == NULL)
2378         return;
2380     SPDocument *document = sp_desktop_document(desktop);
2381     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2383     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2385     // check if something is selected
2386     if (selection->isEmpty()) {
2387         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2388         return;
2389     }
2391     // Get the bounding box of the selection
2392     NRRect bbox;
2393     sp_document_ensure_up_to_date (document);
2394     selection->bounds(&bbox);
2395     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2396         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2397     }
2399     // List of the items to show; all others will be hidden
2400     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2402     // Sort items so that the topmost comes last
2403     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2405     // Generate a random value from the current time (you may create bitmap from the same object(s)
2406     // multiple times, and this is done so that they don't clash)
2407     GTimeVal cu;
2408     g_get_current_time (&cu);
2409     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2411     // Create the filename
2412     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2413     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2414     // digits, and a few other chars, with "_"
2415     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2416     // Build the complete path by adding document->base if set
2417     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2419     //g_print ("%s\n", filepath);
2421     // Remember parent and z-order of the topmost one
2422     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2423     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2424     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2426     // Calculate resolution
2427     double res;
2428     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2429     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2430     if (0 < prefs_res) {
2431         // If it's given explicitly in prefs, take it
2432         res = prefs_res;
2433     } else if (0 < prefs_min) {
2434         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2435         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2436     } else {
2437         float hint_xdpi = 0, hint_ydpi = 0;
2438         const char *hint_filename;
2439         // take resolution hint from the selected objects
2440         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2441         if (hint_xdpi != 0) {
2442             res = hint_xdpi;
2443         } else {
2444             // take resolution hint from the document
2445             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2446             if (hint_xdpi != 0) {
2447                 res = hint_xdpi;
2448             } else {
2449                 // if all else fails, take the default 90 dpi
2450                 res = PX_PER_IN;
2451             }
2452         }
2453     }
2455     // The width and height of the bitmap in pixels
2456     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2457     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2459     // Find out if we have to run a filter
2460     const gchar *run = NULL;
2461     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2462     if (filter) {
2463         // filter command is given;
2464         // see if we have a parameter to pass to it
2465         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2466         if (param1) {
2467             if (param1[strlen(param1) - 1] == '%') {
2468                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2469                 gchar p1[256];
2470                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2471                 // the first param is always the image filename, the second is param1
2472                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2473             } else {
2474                 // otherwise pass the param1 unchanged
2475                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2476             }
2477         } else {
2478             // run without extra parameter
2479             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2480         }
2481     }
2483     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2484     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2485     NR::Matrix t;
2486     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2487         t = NR::scale (1, -1) * NR::translate ((unsigned) (bbox.x0 + 0.5), (unsigned) (bbox.y1 + 0.5)) * eek.inverse();
2488     } else {
2489         t = NR::scale (1, -1) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2490     }
2492     // Do the export
2493     sp_export_png_file(document, filepath,
2494                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2495                    width, height, res, res,
2496                    (guint32) 0xffffff00,
2497                    NULL, NULL,
2498                    true,  /*bool force_overwrite,*/
2499                    items);
2501     g_slist_free (items);
2503     // Run filter, if any
2504     if (run) {
2505         g_print ("Running external filter: %s\n", run);
2506         system (run);
2507     }
2509     // Import the image back
2510     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2511     if (pb) {
2512         // Create the repr for the image
2513         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2514         repr->setAttribute("xlink:href", filename);
2515         repr->setAttribute("sodipodi:absref", filepath);
2516         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2517             sp_repr_set_svg_double(repr, "width", width);
2518             sp_repr_set_svg_double(repr, "height", height);
2519         } else {
2520             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2521             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2522         }
2524         // Write transform
2525         gchar c[256];
2526         if (sp_svg_transform_write(c, 256, t)) {
2527             repr->setAttribute("transform", c);
2528         }
2530         // add the new repr to the parent
2531         parent->appendChild(repr);
2533         // move to the saved position
2534         repr->setPosition(pos > 0 ? pos + 1 : 1);
2536         // Set selection to the new image
2537         selection->clear();
2538         selection->add(repr);
2540         // Clean up
2541         Inkscape::GC::release(repr);
2542         gdk_pixbuf_unref (pb);
2544         // Complete undoable transaction
2545         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2546                           _("Create bitmap"));
2547     }
2549     g_free (filename);
2550     g_free (filepath);
2553 /**
2554  * \brief sp_selection_set_mask
2555  *
2556  * This function creates a mask or clipPath from selection
2557  * Two different modes:
2558  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2559  *       and is applied to current layer
2560  *  otherwise, topmost object is used as mask for other objects
2561  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2562  * 
2563  */
2564 void
2565 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2567     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2568     if (desktop == NULL)
2569         return;
2571     SPDocument *document = sp_desktop_document(desktop);
2572     
2573     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2575     // check if something is selected
2576     bool is_empty = selection->isEmpty();
2577     if ( apply_to_layer && is_empty) {
2578         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2579         return;
2580     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2581         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2582         return;
2583     }
2584     
2585     sp_document_ensure_up_to_date(document);
2587     GSList *items = g_slist_copy((GSList *) selection->itemList());
2588     
2589     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2591     // create a list of duplicates
2592     GSList *mask_items = NULL;
2593     GSList *apply_to_items = NULL;
2594     GSList *items_to_delete = NULL;
2595     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2596     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2597     
2598     if (apply_to_layer) {
2599         // all selected items are used for mask, which is applied to a layer
2600         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2602         for (GSList *i = items; i != NULL; i = i->next) {
2603             Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2604             mask_items = g_slist_prepend (mask_items, dup);
2606             if (remove_original) {
2607                 SPObject *item = SP_OBJECT (i->data);
2608                 items_to_delete = g_slist_prepend (items_to_delete, item);
2609             }
2610         }
2611     } else if (!topmost) {
2612         // topmost item is used as a mask, which is applied to other items in a selection
2613         GSList *i = items;
2614         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2615         mask_items = g_slist_prepend (mask_items, dup);
2617         if (remove_original) {
2618             SPObject *item = SP_OBJECT (i->data);
2619             items_to_delete = g_slist_prepend (items_to_delete, item);
2620         }
2621         
2622         for (i = i->next; i != NULL; i = i->next) {
2623             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2624         }
2625     } else {
2626         GSList *i = NULL;
2627         for (i = items; NULL != i->next; i = i->next) {
2628             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2629         }
2631         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2632         mask_items = g_slist_prepend (mask_items, dup);
2634         if (remove_original) {
2635             SPObject *item = SP_OBJECT (i->data);
2636             items_to_delete = g_slist_prepend (items_to_delete, item);
2637         }
2638     }
2639     
2640     g_slist_free (items);
2641     items = NULL;
2642             
2643     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2644     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2645         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2646         // inverted object transform should be applied to a mask object,
2647         // as mask is calculated in user space (after applying transform)
2648         NR::Matrix maskTransform (item->transform.inverse());
2650         GSList *mask_items_dup = NULL;
2651         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2652             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2653             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2654         }
2656         const gchar *mask_id = NULL;
2657         if (apply_clip_path) {
2658             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2659         } else {
2660             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2661         }
2663         g_slist_free (mask_items_dup);
2664         mask_items_dup = NULL;
2666         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2667     }
2669     g_slist_free (mask_items);
2670     g_slist_free (apply_to_items);
2672     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2673         SPObject *item = SP_OBJECT (i->data);
2674         item->deleteObject (false);
2675     }
2676     g_slist_free (items_to_delete);
2678     if (apply_clip_path) 
2679         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2680     else 
2681         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2684 void sp_selection_unset_mask(bool apply_clip_path) {
2685     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2686     if (desktop == NULL)
2687         return;
2688     
2689     SPDocument *document = sp_desktop_document(desktop);    
2690     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2692     // check if something is selected
2693     if (selection->isEmpty()) {
2694         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2695         return;
2696     }
2697     
2698     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2699     sp_document_ensure_up_to_date(document);
2701     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2702     std::map<SPObject*,SPItem*> referenced_objects;
2703     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2704         if (remove_original) {
2705             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2706             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2707             Inkscape::URIReference *uri_ref = NULL;
2708         
2709             if (apply_clip_path) {
2710                 uri_ref = item->clip_ref;
2711             } else {
2712                 uri_ref = item->mask_ref;
2713             }
2715             // collect distinct mask object (and associate with item to apply transform)
2716             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2717                 referenced_objects[uri_ref->getObject()] = item;
2718             }
2719         }
2721         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2722     }
2724     // restore mask objects into a document
2725     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2726         SPObject *obj = (*it).first;
2727         GSList *items_to_move = NULL;
2728         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2729             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2730             items_to_move = g_slist_prepend (items_to_move, copy);
2731         }
2733         if (!obj->isReferenced()) {
2734             // delete from defs if no other object references this mask
2735             obj->deleteObject(false);
2736         }
2738         // remember parent and position of the item to which the clippath/mask was applied
2739         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2740         gint pos = SP_OBJECT_REPR((*it).second)->position();
2742         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2743             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2745             // insert into parent, restore pos
2746             parent->appendChild(repr);
2747             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2749             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2750             selection->add(repr);
2752             // transform mask, so it is moved the same spot where mask was applied
2753             NR::Matrix transform (mask_item->transform);
2754             transform *= (*it).second->transform;
2755             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2756         }
2758         g_slist_free (items_to_move);
2759     }
2761     if (apply_clip_path) 
2762         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2763     else 
2764         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2767 void fit_canvas_to_selection(SPDesktop *desktop) {
2768     g_return_if_fail(desktop != NULL);
2769     SPDocument *doc = sp_desktop_document(desktop);
2771     g_return_if_fail(doc != NULL);
2772     g_return_if_fail(desktop->selection != NULL);
2773     g_return_if_fail(!desktop->selection->isEmpty());
2774     NRRect bbox = {0,0,0,0};
2776     desktop->selection->bounds(&bbox);
2777     if (!empty(bbox)) {
2778         doc->fitToRect(bbox);
2779     }
2780 };
2782 void fit_canvas_to_drawing(SPDocument *doc) {
2783     g_return_if_fail(doc != NULL);
2784     NRRect bbox = {0,0,0,0};
2786     sp_document_ensure_up_to_date (doc);
2787     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2789     if (!empty(bbox)) {
2790         doc->fitToRect(bbox);
2791     }
2792 };
2794 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2795     g_return_if_fail(desktop != NULL);
2796     SPDocument *doc = sp_desktop_document(desktop);
2798     g_return_if_fail(doc != NULL);
2799     g_return_if_fail(desktop->selection != NULL);
2801     if (desktop->selection->isEmpty()) {
2802         fit_canvas_to_drawing(doc);
2803     } else {
2804         fit_canvas_to_selection(desktop);
2805     }
2807     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2808                      _("Fit page to selection"));
2809 };
2811 /*
2812   Local Variables:
2813   mode:c++
2814   c-file-style:"stroustrup"
2815   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2816   indent-tabs-mode:nil
2817   fill-column:99
2818   End:
2819 */
2820 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :