Code

refactor sp_svg_transform_write to return a dynamically-allocated string
[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=sp_svg_transform_write(full_t);
105     copy->setAttribute("transform", affinestr);
106     g_free(affinestr);
108     *clip = g_slist_prepend(*clip, copy);
111 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
114     // Copy stuff referenced by all items to defs_clip:
115     if (defs_clip) {
116         for (GSList *i = (GSList *) items; i != NULL; i = i->next) {
117             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (i->data), items);
118         }
119         *defs_clip = g_slist_reverse(*defs_clip);
120     }
122     // Store style:
123     if (style_clip) {
124         SPItem *item = SP_ITEM (items->data); // take from the first selected item
125         *style_clip = take_style_from_item (item);
126     }
128     if (clip) {
129         // Sort items:
130         GSList *sorted_items = g_slist_copy ((GSList *) items);
131         sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
133         // Copy item reprs:
134         for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
135             sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip);
136         }
138         *clip = g_slist_reverse(*clip);
139         g_slist_free ((GSList *) sorted_items);
140     }
143 /**
144  * Add gradients/patterns/markers referenced by copied objects to defs.
145  * Iterates through 'defs_clip', and for each item it adds the data
146  * repr into the global defs.
147  */
148 void
149 paste_defs (GSList **defs_clip, SPDocument *doc)
151     if (!defs_clip)
152         return;
154     for (GSList *gl = *defs_clip; gl != NULL; gl = gl->next) {
155         SPDefs *defs= (SPDefs *) SP_DOCUMENT_DEFS(doc);
156         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) gl->data;
157         gchar const *id = repr->attribute("id");
158         if (!id || !doc->getObjectById(id)) {
159             Inkscape::XML::Node *copy = repr->duplicate();
160             SP_OBJECT_REPR(defs)->addChild(copy, NULL);
161             Inkscape::GC::release(copy);
162         }
163     }
166 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
168     paste_defs (defs_clip, document);
170     GSList *copied = NULL;
171     // add objects to document
172     for (GSList *l = *clip; l != NULL; l = l->next) {
173         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
174         Inkscape::XML::Node *copy = repr->duplicate();
176         // premultiply the item transform by the accumulated parent transform in the paste layer
177         NR::Matrix local = sp_item_i2doc_affine(SP_ITEM(parent));
178         if (!local.test_identity()) {
179             gchar const *t_str = copy->attribute("transform");
180             NR::Matrix item_t (NR::identity());
181             if (t_str)
182                 sp_svg_transform_read(t_str, &item_t);
183             item_t *= local.inverse();
184             // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
185             gchar *affinestr=sp_svg_transform_write(item_t);
186             copy->setAttribute("transform", affinestr);
187             g_free(affinestr);
188         }
190         parent->appendChildRepr(copy);
191         copied = g_slist_prepend(copied, copy);
192         Inkscape::GC::release(copy);
193     }
194     return copied;
197 void sp_selection_delete_impl(const GSList *items)
199     for (const GSList *i = items ; i ; i = i->next ) {
200         sp_object_ref((SPObject *)i->data, NULL);
201     }
202     for (const GSList *i = items; i != NULL; i = i->next) {
203         SPItem *item = (SPItem *) i->data;
204         SP_OBJECT(item)->deleteObject();
205         sp_object_unref((SPObject *)item, NULL);
206     }
210 void sp_selection_delete()
212     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
213     if (desktop == NULL) {
214         return;
215     }
217     if (tools_isactive (desktop, TOOLS_TEXT))
218         if (sp_text_delete_selection(desktop->event_context)) {
219             sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
220                              _("Delete text"));
221             return;
222         }
224     Inkscape::Selection *selection = sp_desktop_selection(desktop);
226     // check if something is selected
227     if (selection->isEmpty()) {
228         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
229         return;
230     }
232     const GSList *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
233     selection->clear();
234     sp_selection_delete_impl (selected);
235     g_slist_free ((GSList *) selected);
237     /* a tool may have set up private information in it's selection context
238      * that depends on desktop items.  I think the only sane way to deal with
239      * this currently is to reset the current tool, which will reset it's
240      * associated selection context.  For example: deleting an object
241      * while moving it around the canvas.
242      */
243     tools_switch ( desktop, tools_active ( desktop ) );
245     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE, 
246                      _("Delete"));
249 /* fixme: sequencing */
250 void sp_selection_duplicate()
252     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
253     if (desktop == NULL)
254         return;
256     Inkscape::Selection *selection = sp_desktop_selection(desktop);
258     // check if something is selected
259     if (selection->isEmpty()) {
260         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
261         return;
262     }
264     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
266     selection->clear();
268     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
269     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
271     GSList *newsel = NULL;
273     while (reprs) {
274         Inkscape::XML::Node *parent = ((Inkscape::XML::Node *) reprs->data)->parent();
275         Inkscape::XML::Node *copy = ((Inkscape::XML::Node *) reprs->data)->duplicate();
277         parent->appendChild(copy);
279         newsel = g_slist_prepend(newsel, copy);
280         reprs = g_slist_remove(reprs, reprs->data);
281         Inkscape::GC::release(copy);
282     }
284     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE, 
285                      _("Duplicate"));
287     selection->setReprList(newsel);
289     g_slist_free(newsel);
292 void sp_edit_clear_all()
294     SPDesktop *dt = SP_ACTIVE_DESKTOP;
295     if (!dt)
296         return;
298     SPDocument *doc = sp_desktop_document(dt);
299     sp_desktop_selection(dt)->clear();
301     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
302     GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
304     while (items) {
305         SP_OBJECT (items->data)->deleteObject();
306         items = g_slist_remove(items, items->data);
307     }
309     sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
310                      _("Delete all"));
313 GSList *
314 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
316     for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
317         if (SP_IS_ITEM(child) &&
318             !desktop->isLayer(SP_ITEM(child)) &&
319             (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
320             (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
321             (!exclude || !g_slist_find ((GSList *) exclude, child))
322             )
323         {
324             list = g_slist_prepend (list, SP_ITEM(child));
325         }
327         if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
328             list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
329         }
330     }
332     return list;
335 void sp_edit_select_all_full (bool force_all_layers, bool invert)
337     SPDesktop *dt = SP_ACTIVE_DESKTOP;
338     if (!dt)
339         return;
341     Inkscape::Selection *selection = sp_desktop_selection(dt);
343     g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
345     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
346     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
347     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
349     GSList *items = NULL;
351     const GSList *exclude = NULL;
352     if (invert) {
353         exclude = selection->itemList();
354     }
356     if (force_all_layers)
357         inlayer = PREFS_SELECTION_ALL;
359     switch (inlayer) {
360         case PREFS_SELECTION_LAYER: {
361         if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
362              (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
363         return;
365         GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
367         for (GSList *i = all_items; i; i = i->next) {
368             SPItem *item = SP_ITEM (i->data);
370             if (item && (!onlysensitive || !item->isLocked())) {
371                 if (!onlyvisible || !dt->itemIsHidden(item)) {
372                     if (!dt->isLayer(item)) {
373                         if (!invert || !g_slist_find ((GSList *) exclude, item)) {
374                             items = g_slist_prepend (items, item); // leave it in the list
375                         }
376                     }
377                 }
378             }
379         }
381         g_slist_free (all_items);
382             break;
383         }
384         case PREFS_SELECTION_LAYER_RECURSIVE: {
385             items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
386             break;
387         }
388         default: {
389         items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
390             break;
391     }
392     }
394     selection->setList (items);
396     if (items) {
397         g_slist_free (items);
398     }
401 void sp_edit_select_all ()
403     sp_edit_select_all_full (false, false);
406 void sp_edit_select_all_in_all_layers ()
408     sp_edit_select_all_full (true, false);
411 void sp_edit_invert ()
413     sp_edit_select_all_full (false, true);
416 void sp_edit_invert_in_all_layers ()
418     sp_edit_select_all_full (true, true);
421 void sp_selection_group()
423     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
424     if (desktop == NULL)
425         return;
427     SPDocument *document = sp_desktop_document (desktop);
428     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
430     Inkscape::Selection *selection = sp_desktop_selection(desktop);
432     // Check if something is selected.
433     if (selection->isEmpty()) {
434         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
435         return;
436     }
438     GSList const *l = (GSList *) selection->reprList();
440     GSList *p = g_slist_copy((GSList *) l);
442     selection->clear();
444     p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
446     // Remember the position and parent of the topmost object.
447     gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
448     Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
450     Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
452     while (p) {
453         Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
455         if (current->parent() == topmost_parent) {
456             Inkscape::XML::Node *spnew = current->duplicate();
457             sp_repr_unparent(current);
458             group->appendChild(spnew);
459             Inkscape::GC::release(spnew);
460             topmost --; // only reduce count for those items deleted from topmost_parent
461         } else { // move it to topmost_parent first
462                 GSList *temp_clip = NULL;
464                 // At this point, current may already have no item, due to its being a clone whose original is already moved away
465                 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
466                 gchar const *t_str = current->attribute("transform");
467                 NR::Matrix item_t (NR::identity());
468                 if (t_str)
469                     sp_svg_transform_read(t_str, &item_t);
470                 item_t *= sp_item_i2doc_affine(SP_ITEM(document->getObjectByRepr(current->parent())));
471                 //FIXME: when moving both clone and original from a transformed group (either by
472                 //grouping into another parent, or by cut/paste) the transform from the original's
473                 //parent becomes embedded into original itself, and this affects its clones. Fix
474                 //this by remembering the transform diffs we write to each item into an array and
475                 //then, if this is clone, looking up its original in that array and pre-multiplying
476                 //it by the inverse of that original's transform diff.
478                 sp_selection_copy_one (current, item_t, &temp_clip);
479                 sp_repr_unparent(current);
481                 // paste into topmost_parent (temporarily)
482                 GSList *copied = sp_selection_paste_impl (document, document->getObjectByRepr(topmost_parent), &temp_clip, NULL);
483                 if (temp_clip) g_slist_free (temp_clip);
484                 if (copied) { // if success,
485                     // take pasted object (now in topmost_parent)
486                     Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
487                     // make a copy
488                     Inkscape::XML::Node *spnew = in_topmost->duplicate();
489                     // remove pasted
490                     sp_repr_unparent(in_topmost);
491                     // put its copy into group
492                     group->appendChild(spnew);
493                     Inkscape::GC::release(spnew);
494                     g_slist_free (copied);
495                 }
496         }
497         p = g_slist_remove(p, current);
498     }
500     // Add the new group to the topmost members' parent
501     topmost_parent->appendChild(group);
503     // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
504     group->setPosition(topmost + 1);
506     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP, 
507                      _("Group"));
509     selection->set(group);
510     Inkscape::GC::release(group);
513 void sp_selection_ungroup()
515     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
516     if (desktop == NULL)
517         return;
519     Inkscape::Selection *selection = sp_desktop_selection(desktop);
521     if (selection->isEmpty()) {
522         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
523         return;
524     }
526     GSList *items = g_slist_copy((GSList *) selection->itemList());
527     selection->clear();
529     // Get a copy of current selection.
530     GSList *new_select = NULL;
531     bool ungrouped = false;
532     for (GSList *i = items;
533          i != NULL;
534          i = i->next)
535     {
536         SPItem *group = (SPItem *) i->data;
538         // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
539         if (!SP_IS_OBJECT(group)) {
540             continue;
541         }
543         /* We do not allow ungrouping <svg> etc. (lauris) */
544         if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
545             // keep the non-group item in the new selection
546             selection->add(group);
547             continue;
548         }
550         GSList *children = NULL;
551         /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
552         sp_item_group_ungroup(SP_GROUP(group), &children, false);
553         ungrouped = true;
554         // Add ungrouped items to the new selection.
555         new_select = g_slist_concat(new_select, children);
556     }
558     if (new_select) { // Set new selection.
559         selection->addList(new_select);
560         g_slist_free(new_select);
561     }
562     if (!ungrouped) {
563         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
564     }
566     g_slist_free(items);
568     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP, 
569                      _("Ungroup"));
572 static SPGroup *
573 sp_item_list_common_parent_group(const GSList *items)
575     if (!items) {
576         return NULL;
577     }
578     SPObject *parent = SP_OBJECT_PARENT(items->data);
579     /* Strictly speaking this CAN happen, if user selects <svg> from XML editor */
580     if (!SP_IS_GROUP(parent)) {
581         return NULL;
582     }
583     for (items = items->next; items; items = items->next) {
584         if (SP_OBJECT_PARENT(items->data) != parent) {
585             return NULL;
586         }
587     }
589     return SP_GROUP(parent);
592 /** Finds out the minimum common bbox of the selected items
593  */
594 NR::Rect
595 enclose_items(const GSList *items)
597     g_assert(items != NULL);
599     NR::Rect r = sp_item_bbox_desktop((SPItem *) items->data);
601     for (GSList *i = items->next; i; i = i->next) {
602         r = NR::Rect::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
603     }
605     return r;
608 SPObject *
609 prev_sibling(SPObject *child)
611     SPObject *parent = SP_OBJECT_PARENT(child);
612     if (!SP_IS_GROUP(parent)) {
613         return NULL;
614     }
615     for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
616         if (i->next == child)
617             return i;
618     }
619     return NULL;
622 void
623 sp_selection_raise()
625     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
626     if (!desktop)
627         return;
629     Inkscape::Selection *selection = sp_desktop_selection(desktop);
631     GSList const *items = (GSList *) selection->itemList();
632     if (!items) {
633         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
634         return;
635     }
637     SPGroup const *group = sp_item_list_common_parent_group(items);
638     if (!group) {
639         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
640         return;
641     }
643     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
645     /* construct reverse-ordered list of selected children */
646     GSList *rev = g_slist_copy((GSList *) items);
647     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
649     // find out the common bbox of the selected items
650     NR::Rect selected = enclose_items(items);
652     // for all objects in the selection (starting from top)
653     while (rev) {
654         SPObject *child = SP_OBJECT(rev->data);
655         // for each selected object, find the next sibling
656         for (SPObject *newref = child->next; newref; newref = newref->next) {
657             // if the sibling is an item AND overlaps our selection,
658             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
659                 // AND if it's not one of our selected objects,
660                 if (!g_slist_find((GSList *) items, newref)) {
661                     // move the selected object after that sibling
662                     grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
663                 }
664                 break;
665             }
666         }
667         rev = g_slist_remove(rev, child);
668     }
670     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
671                      _("Raise"));
674 void sp_selection_raise_to_top()
676     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
677     if (desktop == NULL)
678         return;
680     SPDocument *document = sp_desktop_document(desktop);
681     Inkscape::Selection *selection = sp_desktop_selection(desktop);
683     if (selection->isEmpty()) {
684         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
685         return;
686     }
688     GSList const *items = (GSList *) selection->itemList();
690     SPGroup const *group = sp_item_list_common_parent_group(items);
691     if (!group) {
692         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
693         return;
694     }
696     GSList *rl = g_slist_copy((GSList *) selection->reprList());
697     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
699     for (GSList *l = rl; l != NULL; l = l->next) {
700         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
701         repr->setPosition(-1);
702     }
704     g_slist_free(rl);
706     sp_document_done(document, SP_VERB_SELECTION_TO_FRONT, 
707                      _("Raise to top"));
710 void
711 sp_selection_lower()
713     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
714     if (desktop == NULL)
715         return;
717     Inkscape::Selection *selection = sp_desktop_selection(desktop);
719     GSList const *items = (GSList *) selection->itemList();
720     if (!items) {
721         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
722         return;
723     }
725     SPGroup const *group = sp_item_list_common_parent_group(items);
726     if (!group) {
727         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
728         return;
729     }
731     Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
733     // find out the common bbox of the selected items
734     NR::Rect selected = enclose_items(items);
736     /* construct direct-ordered list of selected children */
737     GSList *rev = g_slist_copy((GSList *) items);
738     rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
739     rev = g_slist_reverse(rev);
741     // for all objects in the selection (starting from top)
742     while (rev) {
743         SPObject *child = SP_OBJECT(rev->data);
744         // for each selected object, find the prev sibling
745         for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
746             // if the sibling is an item AND overlaps our selection,
747             if (SP_IS_ITEM(newref) && selected.intersects(sp_item_bbox_desktop(SP_ITEM(newref)))) {
748                 // AND if it's not one of our selected objects,
749                 if (!g_slist_find((GSList *) items, newref)) {
750                     // move the selected object before that sibling
751                     SPObject *put_after = prev_sibling(newref);
752                     if (put_after)
753                         grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
754                     else
755                         SP_OBJECT_REPR(child)->setPosition(0);
756                 }
757                 break;
758             }
759         }
760         rev = g_slist_remove(rev, child);
761     }
763     sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER, 
764                      _("Lower"));
768 void sp_selection_lower_to_bottom()
770     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
771     if (desktop == NULL)
772         return;
774     SPDocument *document = sp_desktop_document(desktop);
775     Inkscape::Selection *selection = sp_desktop_selection(desktop);
777     if (selection->isEmpty()) {
778         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
779         return;
780     }
782     GSList const *items = (GSList *) selection->itemList();
784     SPGroup const *group = sp_item_list_common_parent_group(items);
785     if (!group) {
786         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
787         return;
788     }
790     GSList *rl;
791     rl = g_slist_copy((GSList *) selection->reprList());
792     rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
793     rl = g_slist_reverse(rl);
795     for (GSList *l = rl; l != NULL; l = l->next) {
796         gint minpos;
797         SPObject *pp, *pc;
798         Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
799         pp = document->getObjectByRepr(sp_repr_parent(repr));
800         minpos = 0;
801         g_assert(SP_IS_GROUP(pp));
802         pc = sp_object_first_child(pp);
803         while (!SP_IS_ITEM(pc)) {
804             minpos += 1;
805             pc = pc->next;
806         }
807         repr->setPosition(minpos);
808     }
810     g_slist_free(rl);
812     sp_document_done(document, SP_VERB_SELECTION_TO_BACK, 
813                      _("Lower to bottom"));
816 void
817 sp_undo(SPDesktop *desktop, SPDocument *)
819         if (!sp_document_undo(sp_desktop_document(desktop)))
820             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
823 void
824 sp_redo(SPDesktop *desktop, SPDocument *)
826         if (!sp_document_redo(sp_desktop_document(desktop)))
827             desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
830 void sp_selection_cut()
832     sp_selection_copy();
833     sp_selection_delete();
836 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
838     SPGradient *ref = gradient;
840     while (ref) {
841         // climb up the refs, copying each one in the chain
842         Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
843         *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
845         ref = ref->ref->getObject();
846     }
849 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
851     SPPattern *ref = pattern;
853     while (ref) {
854         // climb up the refs, copying each one in the chain
855         Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
856         *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
858         // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
859         for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
860             if (!SP_IS_ITEM (child))
861                 continue;
862             sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
863         }
865         ref = ref->ref->getObject();
866     }
869 void sp_copy_single (GSList **defs_clip, SPObject *thing)
871     Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
872     *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
876 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
878     SPItem *path = sp_textpath_get_path_item (tp);
879     if (!path)
880         return;
881     if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
882         return;
883     Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
884     *defs_clip = g_slist_prepend (*defs_clip, repr);
887 /**
888  * Copies things like patterns, markers, gradients, etc.
889  */
890 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
892     SPStyle *style = SP_OBJECT_STYLE (item);
894     if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
895         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
896         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
897             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
898         if (SP_IS_PATTERN (server))
899             sp_copy_pattern (defs_clip, SP_PATTERN(server));
900     }
902     if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
903         SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
904         if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
905             sp_copy_gradient (defs_clip, SP_GRADIENT(server));
906         if (SP_IS_PATTERN (server))
907             sp_copy_pattern (defs_clip, SP_PATTERN(server));
908     }
910     // For shapes, copy all of the shape's markers into defs_clip
911     if (SP_IS_SHAPE (item)) {
912         SPShape *shape = SP_SHAPE (item);
913         for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
914             if (shape->marker[i]) {
915                 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
916             }
917         }
918     }
920     if (SP_IS_TEXT_TEXTPATH (item)) {
921         sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
922     }
924     if (item->clip_ref->getObject()) {
925         sp_copy_single (defs_clip, item->clip_ref->getObject());
926     }
928     if (item->mask_ref->getObject()) {
929         SPObject *mask = item->mask_ref->getObject();
930         sp_copy_single (defs_clip, mask);
931         // recurse into the mask for its gradients etc.
932         for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
933             if (SP_IS_ITEM(o))
934                 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
935         }
936     }
938     if (style->filter.filter) {
939         SPObject *filter = style->filter.filter;
940         if (SP_IS_FILTER(filter)) {
941             sp_copy_single (defs_clip, filter);
942         }
943     }
945     // recurse
946     for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
947         if (SP_IS_ITEM(o))
948             sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
949     }
952 /**
953  * \pre item != NULL
954  */
955 SPCSSAttr *
956 take_style_from_item (SPItem *item)
958     // write the complete cascaded style, context-free
959     SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
960     if (css == NULL)
961         return NULL;
963     if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
964         (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
965         // if this is a text with exactly one tspan child, merge the style of that tspan as well
966         // If this is a group, merge the style of its topmost (last) child with style
967         for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
968             if (SP_OBJECT_STYLE (last_element) != NULL) {
969                 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
970                 if (temp) {
971                     sp_repr_css_merge (css, temp);
972                     sp_repr_css_attr_unref (temp);
973                 }
974                 break;
975             }
976         }
977     }
978     if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
979         // do not copy text properties from non-text objects, it's confusing
980         css = sp_css_attr_unset_text (css);
981     }
983     // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
984     double ex = NR::expansion(sp_item_i2doc_affine(item));
985     if (ex != 1.0) {
986         css = sp_css_attr_scale (css, ex);
987     }
989     return css;
993 void sp_selection_copy()
995     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
996     if (desktop == NULL)
997         return;
999     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1001     if (tools_isactive (desktop, TOOLS_DROPPER)) {
1002         sp_dropper_context_copy(desktop->event_context);
1003         return; // copied color under cursor, nothing else to do
1004     }
1006     // check if something is selected
1007     if (selection->isEmpty()) {
1008         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1009         return;
1010     }
1012     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1014     // 0. Copy text to system clipboard
1015     // FIXME: for non-texts, put serialized XML as text to the clipboard;
1016     //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1017     Glib::ustring text;
1018     if (tools_isactive (desktop, TOOLS_TEXT)) {
1019         text = sp_text_get_selected_text(desktop->event_context);
1020     }
1022     if (text.empty()) {
1023         guint texts = 0;
1024         for (GSList *i = (GSList *) items; i; i = i->next) {
1025             SPItem *item = SP_ITEM (i->data);
1026             if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1027                 if (texts > 0) // if more than one text object is copied, separate them by spaces
1028                     text += " ";
1029                 gchar *this_text = sp_te_get_string_multiline (item);
1030                 if (this_text) {
1031                     text += this_text;
1032                     g_free(this_text);
1033                 }
1034                 texts++;
1035             }
1036         }
1037     }
1038     if (!text.empty()) {
1039         Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1040         refClipboard->set_text(text);
1041     }
1043     // clear old defs clipboard
1044     while (defs_clipboard) {
1045         Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1046         defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1047     }
1049     // clear style clipboard
1050     if (style_clipboard) {
1051         sp_repr_css_attr_unref (style_clipboard);
1052         style_clipboard = NULL;
1053     }
1055     //clear main clipboard
1056     while (clipboard) {
1057         Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1058         clipboard = g_slist_remove(clipboard, clipboard->data);
1059     }
1061     sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1063     if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1064         SPStyle *const query = sp_style_new();
1065         if (sp_desktop_query_style_all (desktop, query)) {
1066             SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1067             if (css != NULL) {
1068                 // clear style clipboard
1069                 if (style_clipboard) {
1070                     sp_repr_css_attr_unref (style_clipboard);
1071                     style_clipboard = NULL;
1072                 }
1073                 //sp_repr_css_print (css);
1074                 style_clipboard = css;
1075             }
1076         }
1077         g_free (query);
1078     }
1080     size_clipboard = selection->bounds();
1082     g_slist_free ((GSList *) items);
1085 void sp_selection_paste(bool in_place)
1087     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1089     if (desktop == NULL) {
1090         return;
1091     }
1093     SPDocument *document = sp_desktop_document(desktop);
1095     if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1096         return;
1097     }
1099     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1101     if (tools_isactive (desktop, TOOLS_TEXT)) {
1102         if (sp_text_paste_inline(desktop->event_context))
1103             return; // pasted from system clipboard into text, nothing else to do
1104     }
1106     // check if something is in the clipboard
1107     if (clipboard == NULL) {
1108         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1109         return;
1110     }
1112     GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1113     // add pasted objects to selection
1114     selection->setReprList((GSList const *) copied);
1115     g_slist_free (copied);
1117     if (!in_place) {
1118         sp_document_ensure_up_to_date(document);
1120         NR::Point m( desktop->point() - selection->bounds().midpoint() );
1122         /* Snap the offset of the new item(s) to the grid */
1123         /* FIXME: this gridsnap fiddling is a hack. */
1124         Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1125         gdouble const curr_gridsnap = s.getDistance();
1126         s.setDistance(NR_HUGE);
1127         m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1128         s.setDistance(curr_gridsnap);
1129         sp_selection_move_relative(selection, m);
1130     }
1132     sp_document_done(document, SP_VERB_EDIT_PASTE, 
1133                      _("Paste"));
1136 void sp_selection_paste_style()
1138     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1139     if (desktop == NULL) return;
1141     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1143     // check if something is in the clipboard
1144     if (clipboard == NULL) {
1145         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1146         return;
1147     }
1149     // check if something is selected
1150     if (selection->isEmpty()) {
1151         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1152         return;
1153     }
1155     paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1157     sp_desktop_set_style (desktop, style_clipboard);
1159     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1160                      _("Paste style"));
1163 void sp_selection_paste_size (bool apply_x, bool apply_y)
1165     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1166     if (desktop == NULL) return;
1168     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1170     // check if something is in the clipboard
1171     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1172         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1173         return;
1174     }
1176     // check if something is selected
1177     if (selection->isEmpty()) {
1178         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1179         return;
1180     }
1182     NR::Rect current = selection->bounds();
1183     if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1184         return;
1185     }
1187     double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1188     double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1190     sp_selection_scale_relative (selection, current.midpoint(), 
1191                                  NR::scale(
1192                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1193                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1195     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1196                      _("Paste size"));
1199 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1201     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1202     if (desktop == NULL) return;
1204     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1206     // check if something is in the clipboard
1207     if (size_clipboard.extent(NR::X) < 1e-6 || size_clipboard.extent(NR::Y) < 1e-6) {
1208         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1209         return;
1210     }
1212     // check if something is selected
1213     if (selection->isEmpty()) {
1214         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1215         return;
1216     }
1218     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1219         SPItem *item = SP_ITEM(l->data);
1221         NR::Rect current = sp_item_bbox_desktop(item);
1222         if (current.extent(NR::X) < 1e-6 || current.extent(NR::Y) < 1e-6) {
1223             continue;
1224         }
1226         double scale_x = size_clipboard.extent(NR::X) / current.extent(NR::X);
1227         double scale_y = size_clipboard.extent(NR::Y) / current.extent(NR::Y);
1229         sp_item_scale_rel (item,
1230                                  NR::scale(
1231                                      apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1232                                      apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1234     }
1236     sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1237                      _("Paste size separately"));
1240 void sp_selection_to_next_layer ()
1242     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1244     Inkscape::Selection *selection = sp_desktop_selection(dt);
1246     // check if something is selected
1247     if (selection->isEmpty()) {
1248         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1249         return;
1250     }
1252     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1254     bool no_more = false; // Set to true, if no more layers above
1255     SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1256     if (next) {
1257         GSList *temp_clip = NULL;
1258         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1259         sp_selection_delete_impl (items);
1260         next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1261         GSList *copied;
1262         if(next) {
1263             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1264         } else {
1265             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1266             no_more = true;
1267         }
1268         selection->setReprList((GSList const *) copied);
1269         g_slist_free (copied);
1270         if (temp_clip) g_slist_free (temp_clip);
1271         if (next) dt->setCurrentLayer(next);
1272         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT, 
1273                          _("Raise to next layer"));
1274     } else {
1275         no_more = true;
1276     }
1278     if (no_more) {
1279         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1280     }
1282     g_slist_free ((GSList *) items);
1285 void sp_selection_to_prev_layer ()
1287     SPDesktop *dt = SP_ACTIVE_DESKTOP;
1289     Inkscape::Selection *selection = sp_desktop_selection(dt);
1291     // check if something is selected
1292     if (selection->isEmpty()) {
1293         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1294         return;
1295     }
1297     const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1299     bool no_more = false; // Set to true, if no more layers below
1300     SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1301     if (next) {
1302         GSList *temp_clip = NULL;
1303         sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1304         sp_selection_delete_impl (items);
1305         next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1306         GSList *copied;
1307         if(next) {
1308             copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1309         } else {
1310             copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1311             no_more = true;
1312         }
1313         selection->setReprList((GSList const *) copied);
1314         g_slist_free (copied);
1315         if (temp_clip) g_slist_free (temp_clip);
1316         if (next) dt->setCurrentLayer(next);
1317         sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1318                          _("Lower to previous layer"));
1319     } else {
1320         no_more = true;
1321     }
1323     if (no_more) {
1324         dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1325     }
1327     g_slist_free ((GSList *) items);
1330 bool
1331 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1333     bool contains_original = false;
1334     bool is_use = SP_IS_USE(item);
1335     SPItem *item_use = item;
1336     SPItem *item_use_first = item;
1337     while (is_use && item_use && !contains_original)
1338     {
1339         item_use = sp_use_get_original (SP_USE(item_use));
1340         contains_original |= selection->includes(item_use);
1341         if (item_use == item_use_first)
1342             break;
1343         is_use = SP_IS_USE(item_use);
1344     }   
1345     return contains_original;
1349 bool
1350 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1352     bool clone_with_original = false;
1353     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1354         SPItem *item = SP_ITEM(l->data);
1355         clone_with_original |= selection_contains_original(item, selection);
1356         if (clone_with_original) 
1357             break;
1358     }
1359     return clone_with_original;
1363 /** Apply matrix to the selection.  \a set_i2d is normally true, which means objects are in the
1364 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1365 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1366 that case, items are already in the new position, but the repr is in the old, and this function
1367 then simply updates the repr from item->transform.
1368  */
1369 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1371     if (selection->isEmpty())
1372         return;
1374     for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1375         SPItem *item = SP_ITEM(l->data);
1377         NR::Point old_center(0,0);
1378         if (set_i2d && item->isCenterSet())
1379             old_center = item->getCenter();
1381 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1382          At the time of writing, this is the only place to re-enable. */
1383         sp_item_update_cns(*item, selection->desktop());
1384 #endif
1386         // we're moving both a clone and its original or any ancestor in clone chain?
1387         bool transform_clone_with_original = selection_contains_original(item, selection);
1388         // ...both a text-on-path and its path?
1389         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)))) ));
1390         // ...both a flowtext and its frame?
1391         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)
1392         // ...both an offset and its source?
1393         bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1394        
1395         // If we're moving a connector, we want to detach it
1396         // from shapes that aren't part of the selection, but
1397         // leave it attached if they are
1398         if (cc_item_is_connector(item)) {
1399             SPItem *attItem[2];
1400             SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1401             
1402             for (int n = 0; n < 2; ++n) {
1403                 if (!selection->includes(attItem[n])) {
1404                     sp_conn_end_detach(item, n);
1405                 }
1406             }
1407         }
1408         
1409         // "clones are unmoved when original is moved" preference
1410         int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1411         bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1412         bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1414         // If this is a clone and it's selected along with its original, do not move it; it will feel the
1415         // transform of its original and respond to it itself. Without this, a clone is doubly
1416         // transformed, very unintuitive.
1417       // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1418       // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1419       // Same for linked offset if we are also moving its source: do not move it.
1420         if (transform_textpath_with_path || transform_offset_with_source) {
1421                 // restore item->transform field from the repr, in case it was changed by seltrans
1422             sp_object_read_attr (SP_OBJECT (item), "transform");
1424         } else if (transform_flowtext_with_frame) {
1425             // apply the inverse of the region's transform to the <use> so that the flow remains
1426             // the same (even though the output itself gets transformed)
1427             for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1428                 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1429                     continue;
1430                 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1431                     if (!SP_IS_USE(use)) continue;
1432                     sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1433                 }
1434             }
1435         } else if (transform_clone_with_original) {
1436             // We are transforming a clone along with its original. The below matrix juggling is
1437             // necessary to ensure that they transform as a whole, i.e. the clone's induced
1438             // transform and its move compensation are both cancelled out.
1440             // restore item->transform field from the repr, in case it was changed by seltrans
1441             sp_object_read_attr (SP_OBJECT (item), "transform");
1443             // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1444             NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1445             NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1446             NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1447             NR::Matrix result = t_inv * item->transform * t;
1449             if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1450                 // we need to cancel out the move compensation, too
1452                 // find out the clone move, same as in sp_use_move_compensate
1453                 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1454                 NR::Matrix clone_move = parent.inverse() * t * parent;
1456                 if (prefs_parallel) {
1457                     NR::Matrix move = result * clone_move * t_inv;
1458                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1460                 } else if (prefs_unmoved) {
1461                     //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1462                     //    clone_move = NR::identity();
1463                     NR::Matrix move = result * clone_move;
1464                     sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1465                 }
1467             } else {
1468                 // just apply the result
1469                 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1470             }
1472         } else {
1473             if (set_i2d) {
1474                 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1475             }
1476             sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1477         }
1479         // if we're moving the actual object, not just updating the repr, we can transform the
1480         // center by the same matrix (only necessary for non-translations)
1481         if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1482             item->setCenter(old_center * affine);
1483             SP_OBJECT(item)->updateRepr();
1484         }
1485     }
1488 void sp_selection_remove_transform()
1490     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1491     if (desktop == NULL)
1492         return;
1494     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1496     GSList const *l = (GSList *) selection->reprList();
1497     while (l != NULL) {
1498         sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1499         l = l->next;
1500     }
1502     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN, 
1503                      _("Remove transform"));
1506 void
1507 sp_selection_scale_absolute(Inkscape::Selection *selection,
1508                             double const x0, double const x1,
1509                             double const y0, double const y1)
1511     if (selection->isEmpty())
1512         return;
1514     NR::Rect const bbox(selection->bounds());
1515     if (bbox.isEmpty()) {
1516         return;
1517     }
1519     NR::translate const p2o(-bbox.min());
1521     NR::scale const newSize(x1 - x0,
1522                             y1 - y0);
1523     NR::scale const scale( newSize / NR::scale(bbox.dimensions()) );
1524     NR::translate const o2n(x0, y0);
1525     NR::Matrix const final( p2o * scale * o2n );
1527     sp_selection_apply_affine(selection, final);
1531 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1533     if (selection->isEmpty())
1534         return;
1536     NR::Rect const bbox(selection->bounds());
1538     if (bbox.isEmpty()) {
1539         return;
1540     }
1542     // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1543     if ( bbox.extent(NR::X) * scale[NR::X] > 1e6  ||
1544          bbox.extent(NR::Y) * scale[NR::Y] > 1e6 )
1545     {
1546         return;
1547     }
1549     NR::translate const n2d(-align);
1550     NR::translate const d2n(align);
1551     NR::Matrix const final( n2d * scale * d2n );
1552     sp_selection_apply_affine(selection, final);
1555 void
1556 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const &center, gdouble const angle_degrees)
1558     NR::translate const d2n(center);
1559     NR::translate const n2d(-center);
1560     NR::rotate const rotate(rotate_degrees(angle_degrees));
1561     NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1562     sp_selection_apply_affine(selection, final);
1565 void
1566 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1568     NR::translate const d2n(align);
1569     NR::translate const n2d(-align);
1570     NR::Matrix const skew(1, dy,
1571                           dx, 1,
1572                           0, 0);
1573     NR::Matrix const final( n2d * skew * d2n );
1574     sp_selection_apply_affine(selection, final);
1577 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1579     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1582 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1584     sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1588 /**
1589  * \brief sp_selection_rotate_90
1590  *
1591  * This function rotates selected objects 90 degrees clockwise.
1592  *
1593  */
1595 void sp_selection_rotate_90_cw()
1597     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1599     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1601     if (selection->isEmpty())
1602         return;
1604     GSList const *l = selection->itemList();
1605     NR::rotate const rot_neg_90(NR::Point(0, -1));
1606     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1607         SPItem *item = SP_ITEM(l2->data);
1608         sp_item_rotate_rel(item, rot_neg_90);
1609     }
1611     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW, 
1612                      _("Rotate 90&#176; CW"));
1616 /**
1617  * \brief sp_selection_rotate_90_ccw
1618  *
1619  * This function rotates selected objects 90 degrees counter-clockwise.
1620  *
1621  */
1623 void sp_selection_rotate_90_ccw()
1625     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1627     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1629     if (selection->isEmpty())
1630         return;
1632     GSList const *l = selection->itemList();
1633     NR::rotate const rot_neg_90(NR::Point(0, 1));
1634     for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1635         SPItem *item = SP_ITEM(l2->data);
1636         sp_item_rotate_rel(item, rot_neg_90);
1637     }
1639     sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1640                      _("Rotate 90&#176; CCW"));
1643 void
1644 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1646     if (selection->isEmpty())
1647         return;
1649     NR::Point center = selection->center();
1651     sp_selection_rotate_relative(selection, center, angle_degrees);
1653     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1654                            ( ( angle_degrees > 0 )
1655                              ? "selector:rotate:ccw"
1656                              : "selector:rotate:cw" ), 
1657                            SP_VERB_CONTEXT_SELECT, 
1658                            _("Rotate"));
1661 /**
1662 \param  angle   the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1663 */
1664 void
1665 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1667     if (selection->isEmpty())
1668         return;
1670     NR::Rect const bbox(selection->bounds());
1672     NR::Point center = selection->center();
1674     gdouble const zoom = selection->desktop()->current_zoom();
1675     gdouble const zmove = angle / zoom;
1676     gdouble const r = NR::L2(bbox.max() - center);
1678     gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1680     sp_selection_rotate_relative(selection, center, zangle);
1682     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1683                            ( (angle > 0)
1684                              ? "selector:rotate:ccw"
1685                              : "selector:rotate:cw" ),
1686                            SP_VERB_CONTEXT_SELECT, 
1687                            _("Rotate by pixels"));
1690 void
1691 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1693     if (selection->isEmpty())
1694         return;
1696     NR::Rect const bbox(selection->bounds());
1697     NR::Point const center(bbox.midpoint());
1698     double const max_len = bbox.maxExtent();
1700     // you can't scale "do nizhe pola" (below zero)
1701     if ( max_len + grow <= 1e-3 ) {
1702         return;
1703     }
1705     double const times = 1.0 + grow / max_len;
1706     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1708     sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1709                            ( (grow > 0)
1710                              ? "selector:scale:larger"
1711                              : "selector:scale:smaller" ),
1712                            SP_VERB_CONTEXT_SELECT,
1713                            _("Scale"));
1716 void
1717 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1719     sp_selection_scale(selection,
1720                        grow_pixels / selection->desktop()->current_zoom());
1723 void
1724 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1726     if (selection->isEmpty())
1727         return;
1729     NR::Point const center(selection->bounds().midpoint());
1730     sp_selection_scale_relative(selection, center, NR::scale(times, times));
1731     sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT, 
1732                      _("Scale by whole factor"));
1735 void
1736 sp_selection_move(gdouble dx, gdouble dy)
1738     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1739     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1740     if (selection->isEmpty()) {
1741         return;
1742     }
1744     sp_selection_move_relative(selection, dx, dy);
1746     if (dx == 0) {
1747         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1748                                _("Move vertically"));
1749     } else if (dy == 0) {
1750         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1751                                _("Move horizontally"));
1752     } else {
1753         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1754                          _("Move"));
1755     }
1758 void
1759 sp_selection_move_screen(gdouble dx, gdouble dy)
1761     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1763     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1764     if (selection->isEmpty()) {
1765         return;
1766     }
1768     // same as sp_selection_move but divide deltas by zoom factor
1769     gdouble const zoom = desktop->current_zoom();
1770     gdouble const zdx = dx / zoom;
1771     gdouble const zdy = dy / zoom;
1772     sp_selection_move_relative(selection, zdx, zdy);
1774     if (dx == 0) {
1775         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT, 
1776                                _("Move vertically by pixels"));
1777     } else if (dy == 0) {
1778         sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT, 
1779                                _("Move horizontally by pixels"));
1780     } else {
1781         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT, 
1782                          _("Move"));
1783     }
1786 namespace {
1788 template <typename D>
1789 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1790                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1792 template <typename D>
1793 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1794                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1796 struct Forward {
1797     typedef SPObject *Iterator;
1799     static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1800     static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1801     static void dispose(Iterator i) {}
1803     static SPObject *object(Iterator i) { return i; }
1804     static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1805 };
1807 struct Reverse {
1808     typedef GSList *Iterator;
1810     static Iterator children(SPObject *o) {
1811         return make_list(o->firstChild(), NULL);
1812     }
1813     static Iterator siblings_after(SPObject *o) {
1814         return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1815     }
1816     static void dispose(Iterator i) {
1817         g_slist_free(i);
1818     }
1820     static SPObject *object(Iterator i) {
1821         return reinterpret_cast<SPObject *>(i->data);
1822     }
1823     static Iterator next(Iterator i) { return i->next; }
1825 private:
1826     static GSList *make_list(SPObject *object, SPObject *limit) {
1827         GSList *list=NULL;
1828         while ( object != limit ) {
1829             list = g_slist_prepend(list, object);
1830             object = SP_OBJECT_NEXT(object);
1831         }
1832         return list;
1833     }
1834 };
1838 void
1839 sp_selection_item_next(void)
1841     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1842     g_return_if_fail(desktop != NULL);
1843     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1845     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1846     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1847     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1849     SPObject *root;
1850     if (PREFS_SELECTION_ALL != inlayer) {
1851         root = selection->activeContext();
1852     } else {
1853         root = desktop->currentRoot();
1854     }
1856     SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1858     if (item) {
1859         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1860         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1861             scroll_to_show_item(desktop, item);
1862         }
1863     }
1866 void
1867 sp_selection_item_prev(void)
1869     SPDocument *document = SP_ACTIVE_DOCUMENT;
1870     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1871     g_return_if_fail(document != NULL);
1872     g_return_if_fail(desktop != NULL);
1873     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1875     PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1876     bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1877     bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1879     SPObject *root;
1880     if (PREFS_SELECTION_ALL != inlayer) {
1881         root = selection->activeContext();
1882     } else {
1883         root = desktop->currentRoot();
1884     }
1886     SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1888     if (item) {
1889         selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1890         if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1891             scroll_to_show_item(desktop, item);
1892         }
1893     }
1896 namespace {
1898 template <typename D>
1899 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1900                             SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1902     SPObject *current=root;
1903     while (items) {
1904         SPItem *item=SP_ITEM(items->data);
1905         if ( root->isAncestorOf(item) &&
1906              ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1907         {
1908             current = item;
1909             break;
1910         }
1911         items = items->next;
1912     }
1914     GSList *path=NULL;
1915     while ( current != root ) {
1916         path = g_slist_prepend(path, current);
1917         current = SP_OBJECT_PARENT(current);
1918     }
1920     SPItem *next;
1921     // first, try from the current object
1922     next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1923     g_slist_free(path);
1925     if (!next) { // if we ran out of objects, start over at the root
1926         next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1927     }
1929     return next;
1932 template <typename D>
1933 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1934                   bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1936     typename D::Iterator children;
1937     typename D::Iterator iter;
1939     SPItem *found=NULL;
1941     if (path) {
1942         SPObject *object=reinterpret_cast<SPObject *>(path->data);
1943         g_assert(SP_OBJECT_PARENT(object) == root);
1944         if (desktop->isLayer(object)) {
1945             found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1946         }
1947         iter = children = D::siblings_after(object);
1948     } else {
1949         iter = children = D::children(root);
1950     }
1952     while ( iter && !found ) {
1953         SPObject *object=D::object(iter);
1954         if (desktop->isLayer(object)) {
1955             if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1956                 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1957             }
1958         } else if ( SP_IS_ITEM(object) &&
1959                     ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1960                     ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1961                     ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1962                     !desktop->isLayer(SP_ITEM(object)) )
1963         {
1964             found = SP_ITEM(object);
1965         }
1966         iter = D::next(iter);
1967     }
1969     D::dispose(children);
1971     return found;
1976 /**
1977  * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1978  * \a item.
1979  */
1980 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1982     NR::Rect dbox = desktop->get_display_area();
1983     NR::Rect sbox = sp_item_bbox_desktop(item);
1985     if (dbox.contains(sbox) == false) {
1986         NR::Point const s_dt = sbox.midpoint();
1987         NR::Point const s_w = desktop->d2w(s_dt);
1988         NR::Point const d_dt = dbox.midpoint();
1989         NR::Point const d_w = desktop->d2w(d_dt);
1990         NR::Point const moved_w( d_w - s_w );
1991         gint const dx = (gint) moved_w[X];
1992         gint const dy = (gint) moved_w[Y];
1993         desktop->scroll_world(dx, dy);
1994     }
1998 void
1999 sp_selection_clone()
2001     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2002     if (desktop == NULL)
2003         return;
2005     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2007     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2009     // check if something is selected
2010     if (selection->isEmpty()) {
2011         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2012         return;
2013     }
2015     GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2016   
2017     selection->clear();
2018   
2019     // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2020     reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2022     GSList *newsel = NULL;
2023  
2024     while (reprs) {
2025         Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2026         Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2028         Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2029         sp_repr_set_attr(clone, "x", "0");
2030         sp_repr_set_attr(clone, "y", "0");
2031         sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2033         sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2034         sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2035         
2036         // add the new clone to the top of the original's parent
2037         parent->appendChild(clone);
2039         newsel = g_slist_prepend(newsel, clone);
2040         reprs = g_slist_remove(reprs, sel_repr);
2041         Inkscape::GC::release(clone);
2042     }
2043     
2044     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE, 
2045                      _("Clone"));
2047     selection->setReprList(newsel);
2048  
2049     g_slist_free(newsel);
2052 void
2053 sp_selection_unlink()
2055     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2056     if (!desktop)
2057         return;
2059     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2061     if (selection->isEmpty()) {
2062         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2063         return;
2064     }
2066     // Get a copy of current selection.
2067     GSList *new_select = NULL;
2068     bool unlinked = false;
2069     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2070          items != NULL;
2071          items = items->next)
2072     {
2073         SPItem *use = (SPItem *) items->data;
2075         if (!SP_IS_USE(use)) {
2076             // keep the non-yse item in the new selection
2077             new_select = g_slist_prepend(new_select, use);
2078             continue;
2079         }
2081         SPItem *unlink = sp_use_unlink(SP_USE(use));
2082         unlinked = true;
2083         // Add ungrouped items to the new selection.
2084         new_select = g_slist_prepend(new_select, unlink);
2085     }
2087     if (new_select) { // set new selection
2088         selection->clear();
2089         selection->setList(new_select);
2090         g_slist_free(new_select);
2091     }
2092     if (!unlinked) {
2093         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2094     }
2096     sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2097                      _("Unlink clone"));
2100 void
2101 sp_select_clone_original()
2103     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2104     if (desktop == NULL)
2105         return;
2107     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2109     SPItem *item = selection->singleItem();
2111     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.");
2113     // Check if other than two objects are selected
2114     if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2115         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2116         return;
2117     }
2119     SPItem *original = NULL;
2120     if (SP_IS_USE(item)) {
2121         original = sp_use_get_original (SP_USE(item));
2122     } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2123         original = sp_offset_get_source (SP_OFFSET(item));
2124     } else if (SP_IS_TEXT_TEXTPATH(item)) {
2125         original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2126     } else if (SP_IS_FLOWTEXT(item)) {
2127         original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2128     } else { // it's an object that we don't know what to do with
2129         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2130         return;
2131     }
2133     if (!original) {
2134         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2135         return;
2136     }
2138     for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2139         if (SP_IS_DEFS (o)) {
2140             desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in &lt;defs&gt;)"));
2141             return;
2142         }
2143     }
2145     if (original) {
2146         selection->clear();
2147         selection->set(original);
2148         if (SP_CYCLING == SP_CYCLE_FOCUS) {
2149             scroll_to_show_item(desktop, original);
2150         }
2151     }
2154 void
2155 sp_selection_tile(bool apply)
2157     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2158     if (desktop == NULL)
2159         return;
2161     SPDocument *document = sp_desktop_document(desktop);
2162     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2164     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2166     // check if something is selected
2167     if (selection->isEmpty()) {
2168         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2169         return;
2170     }
2172     sp_document_ensure_up_to_date(document);
2173     NR::Rect r = selection->bounds();
2174     if (r.isEmpty()) {
2175         return;
2176     }
2178     // calculate the transform to be applied to objects to move them to 0,0
2179     NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r.min() + NR::Point (0, r.extent(NR::Y)));
2180     move_p[NR::Y] = -move_p[NR::Y];
2181     NR::Matrix move = NR::Matrix (NR::translate (move_p));
2183     GSList *items = g_slist_copy((GSList *) selection->itemList());
2185     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2187     // bottommost object, after sorting
2188     SPObject *parent = SP_OBJECT_PARENT (items->data);
2190     NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2192     // remember the position of the first item
2193     gint pos = SP_OBJECT_REPR (items->data)->position();
2195     // create a list of duplicates
2196     GSList *repr_copies = NULL;
2197     for (GSList *i = items; i != NULL; i = i->next) {
2198         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2199         repr_copies = g_slist_prepend (repr_copies, dup);
2200     }
2202     NR::Rect bounds(desktop->dt2doc(r.min()), desktop->dt2doc(r.max()));
2204     if (apply) {
2205         // delete objects so that their clones don't get alerted; this object will be restored shortly
2206         for (GSList *i = items; i != NULL; i = i->next) {
2207             SPObject *item = SP_OBJECT (i->data);
2208             item->deleteObject (false);
2209         }
2210     }
2212     // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2213     // without disturbing clones.
2214     // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2215     int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2216     prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2218     const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2219                                         NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r.min()[NR::X], r.max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2221     // restore compensation setting
2222     prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2224     if (apply) {
2225         Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2226         rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2228         NR::Point min = bounds.min() * parent_transform.inverse();
2229         NR::Point max = bounds.max() * parent_transform.inverse();
2231         sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2232         sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2233         sp_repr_set_svg_double(rect, "x", min[NR::X]);
2234         sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2236         // restore parent and position
2237         SP_OBJECT_REPR (parent)->appendChild(rect);
2238         rect->setPosition(pos > 0 ? pos : 0);
2239         SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2241         Inkscape::GC::release(rect);
2243         selection->clear();
2244         selection->set(rectangle);
2245     }
2247     g_slist_free (items);
2249     sp_document_done (document, SP_VERB_EDIT_TILE, 
2250                       _("Objects to pattern"));
2253 void
2254 sp_selection_untile()
2256     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2257     if (desktop == NULL)
2258         return;
2260     SPDocument *document = sp_desktop_document(desktop);
2262     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2264     // check if something is selected
2265     if (selection->isEmpty()) {
2266         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2267         return;
2268     }
2270     GSList *new_select = NULL;
2272     bool did = false;
2274     for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2275          items != NULL;
2276          items = items->next) {
2278         SPItem *item = (SPItem *) items->data;
2280         SPStyle *style = SP_OBJECT_STYLE (item);
2282         if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2283             continue;
2285         SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2287         if (!SP_IS_PATTERN(server))
2288             continue;
2290         did = true;
2292         SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2294         NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2295         pat_transform *= item->transform;
2297         for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2298             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2299             SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2301            // FIXME: relink clones to the new canvas objects
2302            // use SPObject::setid when mental finishes it to steal ids of
2304             // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2305             sp_document_ensure_up_to_date (document);
2307             NR::Matrix transform( i->transform * pat_transform );
2308             sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2310             new_select = g_slist_prepend(new_select, i);
2311         }
2313         SPCSSAttr *css = sp_repr_css_attr_new ();
2314         sp_repr_css_set_property (css, "fill", "none");
2315         sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2316     }
2318     if (!did) {
2319         desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2320     } else {
2321         sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE, 
2322                          _("Pattern to objects"));
2323         selection->setList(new_select);
2324     }
2327 void
2328 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi) 
2330     if (selection->isEmpty()) {
2331         return;
2332     }
2334     const GSList * reprlst = selection->reprList();
2335     bool filename_search = TRUE;
2336     bool xdpi_search = TRUE;
2337     bool ydpi_search = TRUE;
2339     for(; reprlst != NULL &&
2340             filename_search &&
2341             xdpi_search &&
2342             ydpi_search;
2343         reprlst = reprlst->next) {
2344         const gchar * dpi_string;
2345         Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2347         if (filename_search) {
2348             *filename = repr->attribute("inkscape:export-filename");
2349             if (*filename != NULL)
2350                 filename_search = FALSE;
2351         }
2353         if (xdpi_search) {
2354             dpi_string = NULL;
2355             dpi_string = repr->attribute("inkscape:export-xdpi");
2356             if (dpi_string != NULL) {
2357                 *xdpi = atof(dpi_string);
2358                 xdpi_search = FALSE;
2359             }
2360         }
2362         if (ydpi_search) {
2363             dpi_string = NULL;
2364             dpi_string = repr->attribute("inkscape:export-ydpi");
2365             if (dpi_string != NULL) {
2366                 *ydpi = atof(dpi_string);
2367                 ydpi_search = FALSE;
2368             }
2369         }
2370     }
2373 void
2374 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi) 
2376     Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2377     const gchar * dpi_string;
2379     *filename = repr->attribute("inkscape:export-filename");
2381     dpi_string = NULL;
2382     dpi_string = repr->attribute("inkscape:export-xdpi");
2383     if (dpi_string != NULL) {
2384         *xdpi = atof(dpi_string);
2385     }
2387     dpi_string = NULL;
2388     dpi_string = repr->attribute("inkscape:export-ydpi");
2389     if (dpi_string != NULL) {
2390         *ydpi = atof(dpi_string);
2391     }
2394 void
2395 sp_selection_create_bitmap_copy ()
2397     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2398     if (desktop == NULL)
2399         return;
2401     SPDocument *document = sp_desktop_document(desktop);
2402     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2404     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2406     // check if something is selected
2407     if (selection->isEmpty()) {
2408         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2409         return;
2410     }
2412     // Get the bounding box of the selection
2413     NRRect bbox;
2414     sp_document_ensure_up_to_date (document);
2415     selection->bounds(&bbox);
2416     if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2417         return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2418     }
2420     // List of the items to show; all others will be hidden
2421     GSList *items = g_slist_copy ((GSList *) selection->itemList());
2423     // Sort items so that the topmost comes last
2424     items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2426     // Generate a random value from the current time (you may create bitmap from the same object(s)
2427     // multiple times, and this is done so that they don't clash)
2428     GTimeVal cu;
2429     g_get_current_time (&cu);
2430     guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2432     // Create the filename
2433     gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2434     // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2435     // digits, and a few other chars, with "_"
2436     filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2437     // Build the complete path by adding document->base if set
2438     gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2440     //g_print ("%s\n", filepath);
2442     // Remember parent and z-order of the topmost one
2443     gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2444     SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2445     Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2447     // Calculate resolution
2448     double res;
2449     int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2450     int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2451     if (0 < prefs_res) {
2452         // If it's given explicitly in prefs, take it
2453         res = prefs_res;
2454     } else if (0 < prefs_min) {
2455         // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2456         res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2457     } else {
2458         float hint_xdpi = 0, hint_ydpi = 0;
2459         const char *hint_filename;
2460         // take resolution hint from the selected objects
2461         sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2462         if (hint_xdpi != 0) {
2463             res = hint_xdpi;
2464         } else {
2465             // take resolution hint from the document
2466             sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2467             if (hint_xdpi != 0) {
2468                 res = hint_xdpi;
2469             } else {
2470                 // if all else fails, take the default 90 dpi
2471                 res = PX_PER_IN;
2472             }
2473         }
2474     }
2476     // The width and height of the bitmap in pixels
2477     unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2478     unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2480     // Find out if we have to run a filter
2481     const gchar *run = NULL;
2482     const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2483     if (filter) {
2484         // filter command is given;
2485         // see if we have a parameter to pass to it
2486         const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2487         if (param1) {
2488             if (param1[strlen(param1) - 1] == '%') {
2489                 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2490                 gchar p1[256];
2491                 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2492                 // the first param is always the image filename, the second is param1
2493                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2494             } else {
2495                 // otherwise pass the param1 unchanged
2496                 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2497             }
2498         } else {
2499             // run without extra parameter
2500             run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2501         }
2502     }
2504     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2505     NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2506     NR::Matrix t;
2507     if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2508         t = NR::scale (1, -1) * NR::translate ((unsigned) (bbox.x0 + 0.5), (unsigned) (bbox.y1 + 0.5)) * eek.inverse();
2509     } else {
2510         t = NR::scale (1, -1) * NR::translate (bbox.x0, bbox.y1) * eek.inverse();
2511     }
2513     // Do the export
2514     sp_export_png_file(document, filepath,
2515                    bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2516                    width, height, res, res,
2517                    (guint32) 0xffffff00,
2518                    NULL, NULL,
2519                    true,  /*bool force_overwrite,*/
2520                    items);
2522     g_slist_free (items);
2524     // Run filter, if any
2525     if (run) {
2526         g_print ("Running external filter: %s\n", run);
2527         system (run);
2528     }
2530     // Import the image back
2531     GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2532     if (pb) {
2533         // Create the repr for the image
2534         Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2535         repr->setAttribute("xlink:href", filename);
2536         repr->setAttribute("sodipodi:absref", filepath);
2537         if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2538             sp_repr_set_svg_double(repr, "width", width);
2539             sp_repr_set_svg_double(repr, "height", height);
2540         } else {
2541             sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2542             sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2543         }
2545         // Write transform
2546         gchar *c=sp_svg_transform_write(t);
2547         repr->setAttribute("transform", c);
2548         g_free(t);
2550         // add the new repr to the parent
2551         parent->appendChild(repr);
2553         // move to the saved position
2554         repr->setPosition(pos > 0 ? pos + 1 : 1);
2556         // Set selection to the new image
2557         selection->clear();
2558         selection->add(repr);
2560         // Clean up
2561         Inkscape::GC::release(repr);
2562         gdk_pixbuf_unref (pb);
2564         // Complete undoable transaction
2565         sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2566                           _("Create bitmap"));
2567     }
2569     g_free (filename);
2570     g_free (filepath);
2573 /**
2574  * \brief sp_selection_set_mask
2575  *
2576  * This function creates a mask or clipPath from selection
2577  * Two different modes:
2578  *  if applyToLayer, all selection is moved to DEFS as mask/clippath
2579  *       and is applied to current layer
2580  *  otherwise, topmost object is used as mask for other objects
2581  * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2582  * 
2583  */
2584 void
2585 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2587     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2588     if (desktop == NULL)
2589         return;
2591     SPDocument *document = sp_desktop_document(desktop);
2592     
2593     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2595     // check if something is selected
2596     bool is_empty = selection->isEmpty();
2597     if ( apply_to_layer && is_empty) {
2598         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2599         return;
2600     } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2601         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2602         return;
2603     }
2605     // FIXME: temporary patch to prevent crash! 
2606     // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2607     bool clone_with_original = selection_contains_both_clone_and_original (selection);
2608     if (clone_with_original) {
2609         return; // in this version, you cannot clip/mask an object with its own clone
2610     }
2611     // /END FIXME
2612     
2613     sp_document_ensure_up_to_date(document);
2615     GSList *items = g_slist_copy((GSList *) selection->itemList());
2616     
2617     items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2619     // create a list of duplicates
2620     GSList *mask_items = NULL;
2621     GSList *apply_to_items = NULL;
2622     GSList *items_to_delete = NULL;
2623     bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2624     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2625     
2626     if (apply_to_layer) {
2627         // all selected items are used for mask, which is applied to a layer
2628         apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2630         for (GSList *i = items; i != NULL; i = i->next) {
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     } else if (!topmost) {
2640         // topmost item is used as a mask, which is applied to other items in a selection
2641         GSList *i = items;
2642         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2643         mask_items = g_slist_prepend (mask_items, dup);
2645         if (remove_original) {
2646             SPObject *item = SP_OBJECT (i->data);
2647             items_to_delete = g_slist_prepend (items_to_delete, item);
2648         }
2649         
2650         for (i = i->next; i != NULL; i = i->next) {
2651             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2652         }
2653     } else {
2654         GSList *i = NULL;
2655         for (i = items; NULL != i->next; i = i->next) {
2656             apply_to_items = g_slist_prepend (apply_to_items, i->data);
2657         }
2659         Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2660         mask_items = g_slist_prepend (mask_items, dup);
2662         if (remove_original) {
2663             SPObject *item = SP_OBJECT (i->data);
2664             items_to_delete = g_slist_prepend (items_to_delete, item);
2665         }
2666     }
2667     
2668     g_slist_free (items);
2669     items = NULL;
2670             
2671     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2672     for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2673         SPItem *item = reinterpret_cast<SPItem *>(i->data);
2674         // inverted object transform should be applied to a mask object,
2675         // as mask is calculated in user space (after applying transform)
2676         NR::Matrix maskTransform (item->transform.inverse());
2678         GSList *mask_items_dup = NULL;
2679         for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2680             Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2681             mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2682         }
2684         const gchar *mask_id = NULL;
2685         if (apply_clip_path) {
2686             mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2687         } else {
2688             mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2689         }
2691         g_slist_free (mask_items_dup);
2692         mask_items_dup = NULL;
2694         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2695     }
2697     g_slist_free (mask_items);
2698     g_slist_free (apply_to_items);
2700     for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2701         SPObject *item = SP_OBJECT (i->data);
2702         item->deleteObject (false);
2703     }
2704     g_slist_free (items_to_delete);
2706     if (apply_clip_path) 
2707         sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2708     else 
2709         sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2712 void sp_selection_unset_mask(bool apply_clip_path) {
2713     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2714     if (desktop == NULL)
2715         return;
2716     
2717     SPDocument *document = sp_desktop_document(desktop);    
2718     Inkscape::Selection *selection = sp_desktop_selection(desktop);
2720     // check if something is selected
2721     if (selection->isEmpty()) {
2722         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2723         return;
2724     }
2725     
2726     bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2727     sp_document_ensure_up_to_date(document);
2729     gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2730     std::map<SPObject*,SPItem*> referenced_objects;
2731     for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2732         if (remove_original) {
2733             // remember referenced mask/clippath, so orphaned masks can be moved back to document
2734             SPItem *item = reinterpret_cast<SPItem *>(i->data);
2735             Inkscape::URIReference *uri_ref = NULL;
2736         
2737             if (apply_clip_path) {
2738                 uri_ref = item->clip_ref;
2739             } else {
2740                 uri_ref = item->mask_ref;
2741             }
2743             // collect distinct mask object (and associate with item to apply transform)
2744             if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2745                 referenced_objects[uri_ref->getObject()] = item;
2746             }
2747         }
2749         SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2750     }
2752     // restore mask objects into a document
2753     for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2754         SPObject *obj = (*it).first;
2755         GSList *items_to_move = NULL;
2756         for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2757             Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2758             items_to_move = g_slist_prepend (items_to_move, copy);
2759         }
2761         if (!obj->isReferenced()) {
2762             // delete from defs if no other object references this mask
2763             obj->deleteObject(false);
2764         }
2766         // remember parent and position of the item to which the clippath/mask was applied
2767         Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2768         gint pos = SP_OBJECT_REPR((*it).second)->position();
2770         for (GSList *i = items_to_move; NULL != i; i = i->next) {
2771             Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2773             // insert into parent, restore pos
2774             parent->appendChild(repr);
2775             repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2777             SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2778             selection->add(repr);
2780             // transform mask, so it is moved the same spot where mask was applied
2781             NR::Matrix transform (mask_item->transform);
2782             transform *= (*it).second->transform;
2783             sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2784         }
2786         g_slist_free (items_to_move);
2787     }
2789     if (apply_clip_path) 
2790         sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2791     else 
2792         sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2795 void fit_canvas_to_selection(SPDesktop *desktop) {
2796     g_return_if_fail(desktop != NULL);
2797     SPDocument *doc = sp_desktop_document(desktop);
2799     g_return_if_fail(doc != NULL);
2800     g_return_if_fail(desktop->selection != NULL);
2801     g_return_if_fail(!desktop->selection->isEmpty());
2802     NRRect bbox = {0,0,0,0};
2804     desktop->selection->bounds(&bbox);
2805     if (!empty(bbox)) {
2806         doc->fitToRect(bbox);
2807     }
2808 };
2810 void fit_canvas_to_drawing(SPDocument *doc) {
2811     g_return_if_fail(doc != NULL);
2812     NRRect bbox = {0,0,0,0};
2814     sp_document_ensure_up_to_date (doc);
2815     sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2817     if (!empty(bbox)) {
2818         doc->fitToRect(bbox);
2819     }
2820 };
2822 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2823     g_return_if_fail(desktop != NULL);
2824     SPDocument *doc = sp_desktop_document(desktop);
2826     g_return_if_fail(doc != NULL);
2827     g_return_if_fail(desktop->selection != NULL);
2829     if (desktop->selection->isEmpty()) {
2830         fit_canvas_to_drawing(doc);
2831     } else {
2832         fit_canvas_to_selection(desktop);
2833     }
2835     sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING, 
2836                      _("Fit page to selection"));
2837 };
2839 /*
2840   Local Variables:
2841   mode:c++
2842   c-file-style:"stroustrup"
2843   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2844   indent-tabs-mode:nil
2845   fill-column:99
2846   End:
2847 */
2848 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :