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::Maybe<NR::Rect> size_clipboard;
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);
109 }
111 void sp_selection_copy_impl (const GSList *items, GSList **clip, GSList **defs_clip, SPCSSAttr **style_clip)
112 {
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 }
141 }
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)
150 {
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 }
164 }
166 GSList *sp_selection_paste_impl (SPDocument *document, SPObject *parent, GSList **clip, GSList **defs_clip)
167 {
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;
195 }
197 void sp_selection_delete_impl(const GSList *items)
198 {
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 }
207 }
210 void sp_selection_delete()
211 {
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"));
247 }
249 /* fixme: sequencing */
250 void sp_selection_duplicate()
251 {
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);
290 }
292 void sp_edit_clear_all()
293 {
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"));
311 }
313 GSList *
314 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, const GSList *exclude)
315 {
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;
333 }
335 void sp_edit_select_all_full (bool force_all_layers, bool invert)
336 {
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 }
399 }
401 void sp_edit_select_all ()
402 {
403 sp_edit_select_all_full (false, false);
404 }
406 void sp_edit_select_all_in_all_layers ()
407 {
408 sp_edit_select_all_full (true, false);
409 }
411 void sp_edit_invert ()
412 {
413 sp_edit_select_all_full (false, true);
414 }
416 void sp_edit_invert_in_all_layers ()
417 {
418 sp_edit_select_all_full (true, true);
419 }
421 void sp_selection_group()
422 {
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);
511 }
513 void sp_selection_ungroup()
514 {
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"));
570 }
572 static SPGroup *
573 sp_item_list_common_parent_group(const GSList *items)
574 {
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);
590 }
592 /** Finds out the minimum common bbox of the selected items
593 */
594 static NR::Maybe<NR::Rect>
595 enclose_items(const GSList *items)
596 {
597 g_assert(items != NULL);
599 NR::Maybe<NR::Rect> r = NR::Nothing();
600 for (GSList const *i = items; i; i = i->next) {
601 r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
602 }
603 return r;
604 }
606 SPObject *
607 prev_sibling(SPObject *child)
608 {
609 SPObject *parent = SP_OBJECT_PARENT(child);
610 if (!SP_IS_GROUP(parent)) {
611 return NULL;
612 }
613 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
614 if (i->next == child)
615 return i;
616 }
617 return NULL;
618 }
620 void
621 sp_selection_raise()
622 {
623 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
624 if (!desktop)
625 return;
627 Inkscape::Selection *selection = sp_desktop_selection(desktop);
629 GSList const *items = (GSList *) selection->itemList();
630 if (!items) {
631 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
632 return;
633 }
635 SPGroup const *group = sp_item_list_common_parent_group(items);
636 if (!group) {
637 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
638 return;
639 }
641 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
643 /* construct reverse-ordered list of selected children */
644 GSList *rev = g_slist_copy((GSList *) items);
645 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
647 // find out the common bbox of the selected items
648 NR::Maybe<NR::Rect> selected = enclose_items(items);
650 // for all objects in the selection (starting from top)
651 if (selected) {
652 while (rev) {
653 SPObject *child = SP_OBJECT(rev->data);
654 // for each selected object, find the next sibling
655 for (SPObject *newref = child->next; newref; newref = newref->next) {
656 // if the sibling is an item AND overlaps our selection,
657 if (SP_IS_ITEM(newref)) {
658 NR::Maybe<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
659 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
660 // AND if it's not one of our selected objects,
661 if (!g_slist_find((GSList *) items, newref)) {
662 // move the selected object after that sibling
663 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
664 }
665 break;
666 }
667 }
668 }
669 rev = g_slist_remove(rev, child);
670 }
671 } else {
672 g_slist_free(rev);
673 }
675 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
676 _("Raise"));
677 }
679 void sp_selection_raise_to_top()
680 {
681 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
682 if (desktop == NULL)
683 return;
685 SPDocument *document = sp_desktop_document(desktop);
686 Inkscape::Selection *selection = sp_desktop_selection(desktop);
688 if (selection->isEmpty()) {
689 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
690 return;
691 }
693 GSList const *items = (GSList *) selection->itemList();
695 SPGroup const *group = sp_item_list_common_parent_group(items);
696 if (!group) {
697 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
698 return;
699 }
701 GSList *rl = g_slist_copy((GSList *) selection->reprList());
702 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
704 for (GSList *l = rl; l != NULL; l = l->next) {
705 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
706 repr->setPosition(-1);
707 }
709 g_slist_free(rl);
711 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
712 _("Raise to top"));
713 }
715 void
716 sp_selection_lower()
717 {
718 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
719 if (desktop == NULL)
720 return;
722 Inkscape::Selection *selection = sp_desktop_selection(desktop);
724 GSList const *items = (GSList *) selection->itemList();
725 if (!items) {
726 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
727 return;
728 }
730 SPGroup const *group = sp_item_list_common_parent_group(items);
731 if (!group) {
732 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
733 return;
734 }
736 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
738 // find out the common bbox of the selected items
739 NR::Maybe<NR::Rect> selected = enclose_items(items);
741 /* construct direct-ordered list of selected children */
742 GSList *rev = g_slist_copy((GSList *) items);
743 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
744 rev = g_slist_reverse(rev);
746 // for all objects in the selection (starting from top)
747 if (selected) {
748 while (rev) {
749 SPObject *child = SP_OBJECT(rev->data);
750 // for each selected object, find the prev sibling
751 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
752 // if the sibling is an item AND overlaps our selection,
753 if (SP_IS_ITEM(newref)) {
754 NR::Maybe<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
755 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
756 // AND if it's not one of our selected objects,
757 if (!g_slist_find((GSList *) items, newref)) {
758 // move the selected object before that sibling
759 SPObject *put_after = prev_sibling(newref);
760 if (put_after)
761 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
762 else
763 SP_OBJECT_REPR(child)->setPosition(0);
764 }
765 break;
766 }
767 }
768 }
769 rev = g_slist_remove(rev, child);
770 }
771 } else {
772 g_slist_free(rev);
773 }
775 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
776 _("Lower"));
777 }
779 void sp_selection_lower_to_bottom()
780 {
781 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
782 if (desktop == NULL)
783 return;
785 SPDocument *document = sp_desktop_document(desktop);
786 Inkscape::Selection *selection = sp_desktop_selection(desktop);
788 if (selection->isEmpty()) {
789 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
790 return;
791 }
793 GSList const *items = (GSList *) selection->itemList();
795 SPGroup const *group = sp_item_list_common_parent_group(items);
796 if (!group) {
797 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
798 return;
799 }
801 GSList *rl;
802 rl = g_slist_copy((GSList *) selection->reprList());
803 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
804 rl = g_slist_reverse(rl);
806 for (GSList *l = rl; l != NULL; l = l->next) {
807 gint minpos;
808 SPObject *pp, *pc;
809 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
810 pp = document->getObjectByRepr(sp_repr_parent(repr));
811 minpos = 0;
812 g_assert(SP_IS_GROUP(pp));
813 pc = sp_object_first_child(pp);
814 while (!SP_IS_ITEM(pc)) {
815 minpos += 1;
816 pc = pc->next;
817 }
818 repr->setPosition(minpos);
819 }
821 g_slist_free(rl);
823 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
824 _("Lower to bottom"));
825 }
827 void
828 sp_undo(SPDesktop *desktop, SPDocument *)
829 {
830 if (!sp_document_undo(sp_desktop_document(desktop)))
831 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
832 }
834 void
835 sp_redo(SPDesktop *desktop, SPDocument *)
836 {
837 if (!sp_document_redo(sp_desktop_document(desktop)))
838 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
839 }
841 void sp_selection_cut()
842 {
843 sp_selection_copy();
844 sp_selection_delete();
845 }
847 void sp_copy_gradient (GSList **defs_clip, SPGradient *gradient)
848 {
849 SPGradient *ref = gradient;
851 while (ref) {
852 // climb up the refs, copying each one in the chain
853 Inkscape::XML::Node *grad_repr = SP_OBJECT_REPR(ref)->duplicate();
854 *defs_clip = g_slist_prepend (*defs_clip, grad_repr);
856 ref = ref->ref->getObject();
857 }
858 }
860 void sp_copy_pattern (GSList **defs_clip, SPPattern *pattern)
861 {
862 SPPattern *ref = pattern;
864 while (ref) {
865 // climb up the refs, copying each one in the chain
866 Inkscape::XML::Node *pattern_repr = SP_OBJECT_REPR(ref)->duplicate();
867 *defs_clip = g_slist_prepend (*defs_clip, pattern_repr);
869 // items in the pattern may also use gradients and other patterns, so we need to recurse here as well
870 for (SPObject *child = sp_object_first_child(SP_OBJECT(ref)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
871 if (!SP_IS_ITEM (child))
872 continue;
873 sp_copy_stuff_used_by_item (defs_clip, (SPItem *) child, NULL);
874 }
876 ref = ref->ref->getObject();
877 }
878 }
880 void sp_copy_single (GSList **defs_clip, SPObject *thing)
881 {
882 Inkscape::XML::Node *duplicate_repr = SP_OBJECT_REPR(thing)->duplicate();
883 *defs_clip = g_slist_prepend (*defs_clip, duplicate_repr);
884 }
887 void sp_copy_textpath_path (GSList **defs_clip, SPTextPath *tp, const GSList *items)
888 {
889 SPItem *path = sp_textpath_get_path_item (tp);
890 if (!path)
891 return;
892 if (items && g_slist_find ((GSList *) items, path)) // do not copy it to defs if it is already in the list of items copied
893 return;
894 Inkscape::XML::Node *repr = SP_OBJECT_REPR(path)->duplicate();
895 *defs_clip = g_slist_prepend (*defs_clip, repr);
896 }
898 /**
899 * Copies things like patterns, markers, gradients, etc.
900 */
901 void sp_copy_stuff_used_by_item (GSList **defs_clip, SPItem *item, const GSList *items)
902 {
903 SPStyle *style = SP_OBJECT_STYLE (item);
905 if (style && (style->fill.type == SP_PAINT_TYPE_PAINTSERVER)) {
906 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
907 if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
908 sp_copy_gradient (defs_clip, SP_GRADIENT(server));
909 if (SP_IS_PATTERN (server))
910 sp_copy_pattern (defs_clip, SP_PATTERN(server));
911 }
913 if (style && (style->stroke.type == SP_PAINT_TYPE_PAINTSERVER)) {
914 SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
915 if (SP_IS_LINEARGRADIENT (server) || SP_IS_RADIALGRADIENT (server))
916 sp_copy_gradient (defs_clip, SP_GRADIENT(server));
917 if (SP_IS_PATTERN (server))
918 sp_copy_pattern (defs_clip, SP_PATTERN(server));
919 }
921 // For shapes, copy all of the shape's markers into defs_clip
922 if (SP_IS_SHAPE (item)) {
923 SPShape *shape = SP_SHAPE (item);
924 for (int i = 0 ; i < SP_MARKER_LOC_QTY ; i++) {
925 if (shape->marker[i]) {
926 sp_copy_single (defs_clip, SP_OBJECT (shape->marker[i]));
927 }
928 }
929 }
931 if (SP_IS_TEXT_TEXTPATH (item)) {
932 sp_copy_textpath_path (defs_clip, SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))), items);
933 }
935 if (item->clip_ref->getObject()) {
936 sp_copy_single (defs_clip, item->clip_ref->getObject());
937 }
939 if (item->mask_ref->getObject()) {
940 SPObject *mask = item->mask_ref->getObject();
941 sp_copy_single (defs_clip, mask);
942 // recurse into the mask for its gradients etc.
943 for (SPObject *o = SP_OBJECT(mask)->children; o != NULL; o = o->next) {
944 if (SP_IS_ITEM(o))
945 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
946 }
947 }
949 if (style->filter.filter) {
950 SPObject *filter = style->filter.filter;
951 if (SP_IS_FILTER(filter)) {
952 sp_copy_single (defs_clip, filter);
953 }
954 }
956 // recurse
957 for (SPObject *o = SP_OBJECT(item)->children; o != NULL; o = o->next) {
958 if (SP_IS_ITEM(o))
959 sp_copy_stuff_used_by_item (defs_clip, SP_ITEM (o), items);
960 }
961 }
963 /**
964 * \pre item != NULL
965 */
966 SPCSSAttr *
967 take_style_from_item (SPItem *item)
968 {
969 // write the complete cascaded style, context-free
970 SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
971 if (css == NULL)
972 return NULL;
974 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
975 (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
976 // if this is a text with exactly one tspan child, merge the style of that tspan as well
977 // If this is a group, merge the style of its topmost (last) child with style
978 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
979 if (SP_OBJECT_STYLE (last_element) != NULL) {
980 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
981 if (temp) {
982 sp_repr_css_merge (css, temp);
983 sp_repr_css_attr_unref (temp);
984 }
985 break;
986 }
987 }
988 }
989 if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_STRING (item))) {
990 // do not copy text properties from non-text objects, it's confusing
991 css = sp_css_attr_unset_text (css);
992 }
994 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
995 double ex = NR::expansion(sp_item_i2doc_affine(item));
996 if (ex != 1.0) {
997 css = sp_css_attr_scale (css, ex);
998 }
1000 return css;
1001 }
1004 void sp_selection_copy()
1005 {
1006 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1007 if (desktop == NULL)
1008 return;
1010 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1012 if (tools_isactive (desktop, TOOLS_DROPPER)) {
1013 sp_dropper_context_copy(desktop->event_context);
1014 return; // copied color under cursor, nothing else to do
1015 }
1017 // check if something is selected
1018 if (selection->isEmpty()) {
1019 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing was copied."));
1020 return;
1021 }
1023 const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1025 // 0. Copy text to system clipboard
1026 // FIXME: for non-texts, put serialized XML as text to the clipboard;
1027 //for this sp_repr_write_stream needs to be rewritten with iostream instead of FILE
1028 Glib::ustring text;
1029 if (tools_isactive (desktop, TOOLS_TEXT)) {
1030 text = sp_text_get_selected_text(desktop->event_context);
1031 }
1033 if (text.empty()) {
1034 guint texts = 0;
1035 for (GSList *i = (GSList *) items; i; i = i->next) {
1036 SPItem *item = SP_ITEM (i->data);
1037 if (SP_IS_TEXT (item) || SP_IS_FLOWTEXT(item)) {
1038 if (texts > 0) // if more than one text object is copied, separate them by spaces
1039 text += " ";
1040 gchar *this_text = sp_te_get_string_multiline (item);
1041 if (this_text) {
1042 text += this_text;
1043 g_free(this_text);
1044 }
1045 texts++;
1046 }
1047 }
1048 }
1049 if (!text.empty()) {
1050 Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
1051 refClipboard->set_text(text);
1052 }
1054 // clear old defs clipboard
1055 while (defs_clipboard) {
1056 Inkscape::GC::release((Inkscape::XML::Node *) defs_clipboard->data);
1057 defs_clipboard = g_slist_remove (defs_clipboard, defs_clipboard->data);
1058 }
1060 // clear style clipboard
1061 if (style_clipboard) {
1062 sp_repr_css_attr_unref (style_clipboard);
1063 style_clipboard = NULL;
1064 }
1066 //clear main clipboard
1067 while (clipboard) {
1068 Inkscape::GC::release((Inkscape::XML::Node *) clipboard->data);
1069 clipboard = g_slist_remove(clipboard, clipboard->data);
1070 }
1072 sp_selection_copy_impl (items, &clipboard, &defs_clipboard, &style_clipboard);
1074 if (tools_isactive (desktop, TOOLS_TEXT)) { // take style from cursor/text selection, overwriting the style just set by copy_impl
1075 SPStyle *const query = sp_style_new();
1076 if (sp_desktop_query_style_all (desktop, query)) {
1077 SPCSSAttr *css = sp_css_attr_from_style (query, SP_STYLE_FLAG_ALWAYS);
1078 if (css != NULL) {
1079 // clear style clipboard
1080 if (style_clipboard) {
1081 sp_repr_css_attr_unref (style_clipboard);
1082 style_clipboard = NULL;
1083 }
1084 //sp_repr_css_print (css);
1085 style_clipboard = css;
1086 }
1087 }
1088 g_free (query);
1089 }
1091 size_clipboard = selection->bounds();
1093 g_slist_free ((GSList *) items);
1094 }
1096 void sp_selection_paste(bool in_place)
1097 {
1098 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1100 if (desktop == NULL) {
1101 return;
1102 }
1104 SPDocument *document = sp_desktop_document(desktop);
1106 if (Inkscape::have_viable_layer(desktop, desktop->messageStack()) == false) {
1107 return;
1108 }
1110 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1112 if (tools_isactive (desktop, TOOLS_TEXT)) {
1113 if (sp_text_paste_inline(desktop->event_context))
1114 return; // pasted from system clipboard into text, nothing else to do
1115 }
1117 // check if something is in the clipboard
1118 if (clipboard == NULL) {
1119 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1120 return;
1121 }
1123 GSList *copied = sp_selection_paste_impl(document, desktop->currentLayer(), &clipboard, &defs_clipboard);
1124 // add pasted objects to selection
1125 selection->setReprList((GSList const *) copied);
1126 g_slist_free (copied);
1128 if (!in_place) {
1129 sp_document_ensure_up_to_date(document);
1131 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1132 NR::Point m( desktop->point() );
1133 if (sel_bbox) {
1134 m -= sel_bbox->midpoint();
1135 }
1137 /* Snap the offset of the new item(s) to the grid */
1138 /* FIXME: this gridsnap fiddling is a hack. */
1139 Inkscape::GridSnapper &s = desktop->namedview->snap_manager.grid;
1140 gdouble const curr_gridsnap = s.getDistance();
1141 s.setDistance(NR_HUGE);
1142 m = s.freeSnap(Inkscape::Snapper::SNAP_POINT, m, NULL).getPoint();
1143 s.setDistance(curr_gridsnap);
1144 sp_selection_move_relative(selection, m);
1145 }
1147 sp_document_done(document, SP_VERB_EDIT_PASTE,
1148 _("Paste"));
1149 }
1151 void sp_selection_paste_style()
1152 {
1153 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1154 if (desktop == NULL) return;
1156 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1158 // check if something is in the clipboard
1159 if (clipboard == NULL) {
1160 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1161 return;
1162 }
1164 // check if something is selected
1165 if (selection->isEmpty()) {
1166 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste style to."));
1167 return;
1168 }
1170 paste_defs (&defs_clipboard, sp_desktop_document(desktop));
1172 sp_desktop_set_style (desktop, style_clipboard);
1174 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_STYLE,
1175 _("Paste style"));
1176 }
1178 void sp_selection_paste_size (bool apply_x, bool apply_y)
1179 {
1180 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1181 if (desktop == NULL) return;
1183 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1185 // check if something is in the clipboard
1186 if (!size_clipboard) {
1187 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1188 return;
1189 }
1191 // check if something is selected
1192 if (selection->isEmpty()) {
1193 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1194 return;
1195 }
1197 NR::Maybe<NR::Rect> current = selection->bounds();
1198 if ( !current || current->extent(NR::X) < 1e-6 || current->extent(NR::Y) < 1e-6 ) {
1199 return;
1200 }
1202 double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1203 double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1205 sp_selection_scale_relative (selection, current->midpoint(),
1206 NR::scale(
1207 apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1208 apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1210 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE,
1211 _("Paste size"));
1212 }
1214 void sp_selection_paste_size_separately (bool apply_x, bool apply_y)
1215 {
1216 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1217 if (desktop == NULL) return;
1219 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1221 // check if something is in the clipboard
1222 if ( !size_clipboard ) {
1223 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing on the clipboard."));
1224 return;
1225 }
1227 // check if something is selected
1228 if (selection->isEmpty()) {
1229 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to paste size to."));
1230 return;
1231 }
1233 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1234 SPItem *item = SP_ITEM(l->data);
1236 NR::Maybe<NR::Rect> current = sp_item_bbox_desktop(item);
1237 if ( !current || current->extent(NR::X) < 1e-6 || current->extent(NR::Y) < 1e-6 ) {
1238 continue;
1239 }
1241 double scale_x = size_clipboard->extent(NR::X) / current->extent(NR::X);
1242 double scale_y = size_clipboard->extent(NR::Y) / current->extent(NR::Y);
1244 sp_item_scale_rel (item,
1245 NR::scale(
1246 apply_x? scale_x : (desktop->isToolboxButtonActive ("lock")? scale_y : 1.0),
1247 apply_y? scale_y : (desktop->isToolboxButtonActive ("lock")? scale_x : 1.0)));
1249 }
1251 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1252 _("Paste size separately"));
1253 }
1255 void sp_selection_to_next_layer ()
1256 {
1257 SPDesktop *dt = SP_ACTIVE_DESKTOP;
1259 Inkscape::Selection *selection = sp_desktop_selection(dt);
1261 // check if something is selected
1262 if (selection->isEmpty()) {
1263 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1264 return;
1265 }
1267 const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1269 bool no_more = false; // Set to true, if no more layers above
1270 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1271 if (next) {
1272 GSList *temp_clip = NULL;
1273 sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1274 sp_selection_delete_impl (items);
1275 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1276 GSList *copied;
1277 if(next) {
1278 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1279 } else {
1280 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1281 no_more = true;
1282 }
1283 selection->setReprList((GSList const *) copied);
1284 g_slist_free (copied);
1285 if (temp_clip) g_slist_free (temp_clip);
1286 if (next) dt->setCurrentLayer(next);
1287 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1288 _("Raise to next layer"));
1289 } else {
1290 no_more = true;
1291 }
1293 if (no_more) {
1294 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1295 }
1297 g_slist_free ((GSList *) items);
1298 }
1300 void sp_selection_to_prev_layer ()
1301 {
1302 SPDesktop *dt = SP_ACTIVE_DESKTOP;
1304 Inkscape::Selection *selection = sp_desktop_selection(dt);
1306 // check if something is selected
1307 if (selection->isEmpty()) {
1308 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1309 return;
1310 }
1312 const GSList *items = g_slist_copy ((GSList *) selection->itemList());
1314 bool no_more = false; // Set to true, if no more layers below
1315 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1316 if (next) {
1317 GSList *temp_clip = NULL;
1318 sp_selection_copy_impl (items, &temp_clip, NULL, NULL); // we're in the same doc, so no need to copy defs
1319 sp_selection_delete_impl (items);
1320 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1321 GSList *copied;
1322 if(next) {
1323 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip, NULL);
1324 } else {
1325 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip, NULL);
1326 no_more = true;
1327 }
1328 selection->setReprList((GSList const *) copied);
1329 g_slist_free (copied);
1330 if (temp_clip) g_slist_free (temp_clip);
1331 if (next) dt->setCurrentLayer(next);
1332 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1333 _("Lower to previous layer"));
1334 } else {
1335 no_more = true;
1336 }
1338 if (no_more) {
1339 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1340 }
1342 g_slist_free ((GSList *) items);
1343 }
1345 bool
1346 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1347 {
1348 bool contains_original = false;
1349 bool is_use = SP_IS_USE(item);
1350 SPItem *item_use = item;
1351 SPItem *item_use_first = item;
1352 while (is_use && item_use && !contains_original)
1353 {
1354 item_use = sp_use_get_original (SP_USE(item_use));
1355 contains_original |= selection->includes(item_use);
1356 if (item_use == item_use_first)
1357 break;
1358 is_use = SP_IS_USE(item_use);
1359 }
1360 return contains_original;
1361 }
1364 bool
1365 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1366 {
1367 bool clone_with_original = false;
1368 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1369 SPItem *item = SP_ITEM(l->data);
1370 clone_with_original |= selection_contains_original(item, selection);
1371 if (clone_with_original)
1372 break;
1373 }
1374 return clone_with_original;
1375 }
1378 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1379 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1380 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1381 that case, items are already in the new position, but the repr is in the old, and this function
1382 then simply updates the repr from item->transform.
1383 */
1384 void sp_selection_apply_affine(Inkscape::Selection *selection, NR::Matrix const &affine, bool set_i2d)
1385 {
1386 if (selection->isEmpty())
1387 return;
1389 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1390 SPItem *item = SP_ITEM(l->data);
1392 NR::Point old_center(0,0);
1393 if (set_i2d && item->isCenterSet())
1394 old_center = item->getCenter();
1396 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1397 At the time of writing, this is the only place to re-enable. */
1398 sp_item_update_cns(*item, selection->desktop());
1399 #endif
1401 // we're moving both a clone and its original or any ancestor in clone chain?
1402 bool transform_clone_with_original = selection_contains_original(item, selection);
1403 // ...both a text-on-path and its path?
1404 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)))) ));
1405 // ...both a flowtext and its frame?
1406 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)
1407 // ...both an offset and its source?
1408 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1410 // If we're moving a connector, we want to detach it
1411 // from shapes that aren't part of the selection, but
1412 // leave it attached if they are
1413 if (cc_item_is_connector(item)) {
1414 SPItem *attItem[2];
1415 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1417 for (int n = 0; n < 2; ++n) {
1418 if (!selection->includes(attItem[n])) {
1419 sp_conn_end_detach(item, n);
1420 }
1421 }
1422 }
1424 // "clones are unmoved when original is moved" preference
1425 int compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1426 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1427 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1429 // If this is a clone and it's selected along with its original, do not move it; it will feel the
1430 // transform of its original and respond to it itself. Without this, a clone is doubly
1431 // transformed, very unintuitive.
1432 // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1433 // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1434 // Same for linked offset if we are also moving its source: do not move it.
1435 if (transform_textpath_with_path || transform_offset_with_source) {
1436 // restore item->transform field from the repr, in case it was changed by seltrans
1437 sp_object_read_attr (SP_OBJECT (item), "transform");
1439 } else if (transform_flowtext_with_frame) {
1440 // apply the inverse of the region's transform to the <use> so that the flow remains
1441 // the same (even though the output itself gets transformed)
1442 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1443 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1444 continue;
1445 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1446 if (!SP_IS_USE(use)) continue;
1447 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1448 }
1449 }
1450 } else if (transform_clone_with_original) {
1451 // We are transforming a clone along with its original. The below matrix juggling is
1452 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1453 // transform and its move compensation are both cancelled out.
1455 // restore item->transform field from the repr, in case it was changed by seltrans
1456 sp_object_read_attr (SP_OBJECT (item), "transform");
1458 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1459 NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1460 NR::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1461 NR::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1462 NR::Matrix result = t_inv * item->transform * t;
1464 if ((prefs_parallel || prefs_unmoved) && affine.is_translation()) {
1465 // we need to cancel out the move compensation, too
1467 // find out the clone move, same as in sp_use_move_compensate
1468 NR::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1469 NR::Matrix clone_move = parent.inverse() * t * parent;
1471 if (prefs_parallel) {
1472 NR::Matrix move = result * clone_move * t_inv;
1473 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1475 } else if (prefs_unmoved) {
1476 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1477 // clone_move = NR::identity();
1478 NR::Matrix move = result * clone_move;
1479 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1480 }
1482 } else {
1483 // just apply the result
1484 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1485 }
1487 } else {
1488 if (set_i2d) {
1489 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * affine);
1490 }
1491 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1492 }
1494 // if we're moving the actual object, not just updating the repr, we can transform the
1495 // center by the same matrix (only necessary for non-translations)
1496 if (set_i2d && item->isCenterSet() && !affine.is_translation()) {
1497 item->setCenter(old_center * affine);
1498 SP_OBJECT(item)->updateRepr();
1499 }
1500 }
1501 }
1503 void sp_selection_remove_transform()
1504 {
1505 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1506 if (desktop == NULL)
1507 return;
1509 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1511 GSList const *l = (GSList *) selection->reprList();
1512 while (l != NULL) {
1513 sp_repr_set_attr((Inkscape::XML::Node*)l->data, "transform", NULL);
1514 l = l->next;
1515 }
1517 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1518 _("Remove transform"));
1519 }
1521 void
1522 sp_selection_scale_absolute(Inkscape::Selection *selection,
1523 double const x0, double const x1,
1524 double const y0, double const y1)
1525 {
1526 if (selection->isEmpty())
1527 return;
1529 NR::Maybe<NR::Rect> const bbox(selection->bounds());
1530 if ( !bbox ) {
1531 return;
1532 }
1534 NR::translate const p2o(-bbox->min());
1536 NR::scale const newSize(x1 - x0,
1537 y1 - y0);
1538 NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1539 NR::translate const o2n(x0, y0);
1540 NR::Matrix const final( p2o * scale * o2n );
1542 sp_selection_apply_affine(selection, final);
1543 }
1546 void sp_selection_scale_relative(Inkscape::Selection *selection, NR::Point const &align, NR::scale const &scale)
1547 {
1548 if (selection->isEmpty())
1549 return;
1551 NR::Maybe<NR::Rect> const bbox(selection->bounds());
1553 if ( !bbox ) {
1554 return;
1555 }
1557 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1558 if ( bbox->extent(NR::X) * scale[NR::X] > 1e6 ||
1559 bbox->extent(NR::Y) * scale[NR::Y] > 1e6 )
1560 {
1561 return;
1562 }
1564 NR::translate const n2d(-align);
1565 NR::translate const d2n(align);
1566 NR::Matrix const final( n2d * scale * d2n );
1567 sp_selection_apply_affine(selection, final);
1568 }
1570 void
1571 sp_selection_rotate_relative(Inkscape::Selection *selection, NR::Point const ¢er, gdouble const angle_degrees)
1572 {
1573 NR::translate const d2n(center);
1574 NR::translate const n2d(-center);
1575 NR::rotate const rotate(rotate_degrees(angle_degrees));
1576 NR::Matrix const final( NR::Matrix(n2d) * rotate * d2n );
1577 sp_selection_apply_affine(selection, final);
1578 }
1580 void
1581 sp_selection_skew_relative(Inkscape::Selection *selection, NR::Point const &align, double dx, double dy)
1582 {
1583 NR::translate const d2n(align);
1584 NR::translate const n2d(-align);
1585 NR::Matrix const skew(1, dy,
1586 dx, 1,
1587 0, 0);
1588 NR::Matrix const final( n2d * skew * d2n );
1589 sp_selection_apply_affine(selection, final);
1590 }
1592 void sp_selection_move_relative(Inkscape::Selection *selection, NR::Point const &move)
1593 {
1594 sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1595 }
1597 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1598 {
1599 sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1600 }
1603 /**
1604 * \brief sp_selection_rotate_90
1605 *
1606 * This function rotates selected objects 90 degrees clockwise.
1607 *
1608 */
1610 void sp_selection_rotate_90_cw()
1611 {
1612 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1614 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1616 if (selection->isEmpty())
1617 return;
1619 GSList const *l = selection->itemList();
1620 NR::rotate const rot_neg_90(NR::Point(0, -1));
1621 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1622 SPItem *item = SP_ITEM(l2->data);
1623 sp_item_rotate_rel(item, rot_neg_90);
1624 }
1626 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CCW,
1627 _("Rotate 90° CW"));
1628 }
1631 /**
1632 * \brief sp_selection_rotate_90_ccw
1633 *
1634 * This function rotates selected objects 90 degrees counter-clockwise.
1635 *
1636 */
1638 void sp_selection_rotate_90_ccw()
1639 {
1640 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1642 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1644 if (selection->isEmpty())
1645 return;
1647 GSList const *l = selection->itemList();
1648 NR::rotate const rot_neg_90(NR::Point(0, 1));
1649 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1650 SPItem *item = SP_ITEM(l2->data);
1651 sp_item_rotate_rel(item, rot_neg_90);
1652 }
1654 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_ROTATE_90_CW,
1655 _("Rotate 90° CCW"));
1656 }
1658 void
1659 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1660 {
1661 if (selection->isEmpty())
1662 return;
1664 NR::Maybe<NR::Point> center = selection->center();
1665 if (!center) {
1666 return;
1667 }
1669 sp_selection_rotate_relative(selection, *center, angle_degrees);
1671 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1672 ( ( angle_degrees > 0 )
1673 ? "selector:rotate:ccw"
1674 : "selector:rotate:cw" ),
1675 SP_VERB_CONTEXT_SELECT,
1676 _("Rotate"));
1677 }
1679 /**
1680 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1681 */
1682 void
1683 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1684 {
1685 if (selection->isEmpty())
1686 return;
1688 NR::Maybe<NR::Rect> const bbox(selection->bounds());
1689 NR::Maybe<NR::Point> center = selection->center();
1691 if ( !bbox || !center ) {
1692 return;
1693 }
1695 gdouble const zoom = selection->desktop()->current_zoom();
1696 gdouble const zmove = angle / zoom;
1697 gdouble const r = NR::L2(bbox->max() - *center);
1699 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1701 sp_selection_rotate_relative(selection, *center, zangle);
1703 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1704 ( (angle > 0)
1705 ? "selector:rotate:ccw"
1706 : "selector:rotate:cw" ),
1707 SP_VERB_CONTEXT_SELECT,
1708 _("Rotate by pixels"));
1709 }
1711 void
1712 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1713 {
1714 if (selection->isEmpty())
1715 return;
1717 NR::Maybe<NR::Rect> const bbox(selection->bounds());
1718 if (!bbox) {
1719 return;
1720 }
1722 NR::Point const center(bbox->midpoint());
1724 // you can't scale "do nizhe pola" (below zero)
1725 double const max_len = bbox->maxExtent();
1726 if ( max_len + grow <= 1e-3 ) {
1727 return;
1728 }
1730 double const times = 1.0 + grow / max_len;
1731 sp_selection_scale_relative(selection, center, NR::scale(times, times));
1733 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1734 ( (grow > 0)
1735 ? "selector:scale:larger"
1736 : "selector:scale:smaller" ),
1737 SP_VERB_CONTEXT_SELECT,
1738 _("Scale"));
1739 }
1741 void
1742 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1743 {
1744 sp_selection_scale(selection,
1745 grow_pixels / selection->desktop()->current_zoom());
1746 }
1748 void
1749 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1750 {
1751 if (selection->isEmpty())
1752 return;
1754 NR::Maybe<NR::Rect> sel_bbox = selection->bounds();
1756 if (!sel_bbox) {
1757 return;
1758 }
1760 NR::Point const center(sel_bbox->midpoint());
1761 sp_selection_scale_relative(selection, center, NR::scale(times, times));
1762 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1763 _("Scale by whole factor"));
1764 }
1766 void
1767 sp_selection_move(gdouble dx, gdouble dy)
1768 {
1769 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1770 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1771 if (selection->isEmpty()) {
1772 return;
1773 }
1775 sp_selection_move_relative(selection, dx, dy);
1777 if (dx == 0) {
1778 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1779 _("Move vertically"));
1780 } else if (dy == 0) {
1781 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1782 _("Move horizontally"));
1783 } else {
1784 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1785 _("Move"));
1786 }
1787 }
1789 void
1790 sp_selection_move_screen(gdouble dx, gdouble dy)
1791 {
1792 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1794 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1795 if (selection->isEmpty()) {
1796 return;
1797 }
1799 // same as sp_selection_move but divide deltas by zoom factor
1800 gdouble const zoom = desktop->current_zoom();
1801 gdouble const zdx = dx / zoom;
1802 gdouble const zdy = dy / zoom;
1803 sp_selection_move_relative(selection, zdx, zdy);
1805 if (dx == 0) {
1806 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1807 _("Move vertically by pixels"));
1808 } else if (dy == 0) {
1809 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1810 _("Move horizontally by pixels"));
1811 } else {
1812 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1813 _("Move"));
1814 }
1815 }
1817 namespace {
1819 template <typename D>
1820 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1821 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1823 template <typename D>
1824 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1825 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1827 struct Forward {
1828 typedef SPObject *Iterator;
1830 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1831 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1832 static void dispose(Iterator i) {}
1834 static SPObject *object(Iterator i) { return i; }
1835 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1836 };
1838 struct Reverse {
1839 typedef GSList *Iterator;
1841 static Iterator children(SPObject *o) {
1842 return make_list(o->firstChild(), NULL);
1843 }
1844 static Iterator siblings_after(SPObject *o) {
1845 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1846 }
1847 static void dispose(Iterator i) {
1848 g_slist_free(i);
1849 }
1851 static SPObject *object(Iterator i) {
1852 return reinterpret_cast<SPObject *>(i->data);
1853 }
1854 static Iterator next(Iterator i) { return i->next; }
1856 private:
1857 static GSList *make_list(SPObject *object, SPObject *limit) {
1858 GSList *list=NULL;
1859 while ( object != limit ) {
1860 list = g_slist_prepend(list, object);
1861 object = SP_OBJECT_NEXT(object);
1862 }
1863 return list;
1864 }
1865 };
1867 }
1869 void
1870 sp_selection_item_next(void)
1871 {
1872 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1873 g_return_if_fail(desktop != NULL);
1874 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1876 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1877 bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1878 bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1880 SPObject *root;
1881 if (PREFS_SELECTION_ALL != inlayer) {
1882 root = selection->activeContext();
1883 } else {
1884 root = desktop->currentRoot();
1885 }
1887 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1889 if (item) {
1890 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1891 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1892 scroll_to_show_item(desktop, item);
1893 }
1894 }
1895 }
1897 void
1898 sp_selection_item_prev(void)
1899 {
1900 SPDocument *document = SP_ACTIVE_DOCUMENT;
1901 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
1902 g_return_if_fail(document != NULL);
1903 g_return_if_fail(desktop != NULL);
1904 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1906 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs_get_int_attribute ("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1907 bool onlyvisible = prefs_get_int_attribute ("options.kbselection", "onlyvisible", 1);
1908 bool onlysensitive = prefs_get_int_attribute ("options.kbselection", "onlysensitive", 1);
1910 SPObject *root;
1911 if (PREFS_SELECTION_ALL != inlayer) {
1912 root = selection->activeContext();
1913 } else {
1914 root = desktop->currentRoot();
1915 }
1917 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1919 if (item) {
1920 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1921 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1922 scroll_to_show_item(desktop, item);
1923 }
1924 }
1925 }
1927 namespace {
1929 template <typename D>
1930 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1931 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1932 {
1933 SPObject *current=root;
1934 while (items) {
1935 SPItem *item=SP_ITEM(items->data);
1936 if ( root->isAncestorOf(item) &&
1937 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1938 {
1939 current = item;
1940 break;
1941 }
1942 items = items->next;
1943 }
1945 GSList *path=NULL;
1946 while ( current != root ) {
1947 path = g_slist_prepend(path, current);
1948 current = SP_OBJECT_PARENT(current);
1949 }
1951 SPItem *next;
1952 // first, try from the current object
1953 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1954 g_slist_free(path);
1956 if (!next) { // if we ran out of objects, start over at the root
1957 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1958 }
1960 return next;
1961 }
1963 template <typename D>
1964 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1965 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1966 {
1967 typename D::Iterator children;
1968 typename D::Iterator iter;
1970 SPItem *found=NULL;
1972 if (path) {
1973 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1974 g_assert(SP_OBJECT_PARENT(object) == root);
1975 if (desktop->isLayer(object)) {
1976 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1977 }
1978 iter = children = D::siblings_after(object);
1979 } else {
1980 iter = children = D::children(root);
1981 }
1983 while ( iter && !found ) {
1984 SPObject *object=D::object(iter);
1985 if (desktop->isLayer(object)) {
1986 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1987 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1988 }
1989 } else if ( SP_IS_ITEM(object) &&
1990 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1991 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1992 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1993 !desktop->isLayer(SP_ITEM(object)) )
1994 {
1995 found = SP_ITEM(object);
1996 }
1997 iter = D::next(iter);
1998 }
2000 D::dispose(children);
2002 return found;
2003 }
2005 }
2007 /**
2008 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2009 * \a item.
2010 */
2011 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2012 {
2013 NR::Rect dbox = desktop->get_display_area();
2014 NR::Maybe<NR::Rect> sbox = sp_item_bbox_desktop(item);
2016 if ( sbox && dbox.contains(*sbox) == false ) {
2017 NR::Point const s_dt = sbox->midpoint();
2018 NR::Point const s_w = desktop->d2w(s_dt);
2019 NR::Point const d_dt = dbox.midpoint();
2020 NR::Point const d_w = desktop->d2w(d_dt);
2021 NR::Point const moved_w( d_w - s_w );
2022 gint const dx = (gint) moved_w[X];
2023 gint const dy = (gint) moved_w[Y];
2024 desktop->scroll_world(dx, dy);
2025 }
2026 }
2029 void
2030 sp_selection_clone()
2031 {
2032 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2033 if (desktop == NULL)
2034 return;
2036 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2038 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2040 // check if something is selected
2041 if (selection->isEmpty()) {
2042 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2043 return;
2044 }
2046 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2048 selection->clear();
2050 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2051 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2053 GSList *newsel = NULL;
2055 while (reprs) {
2056 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2057 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2059 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2060 sp_repr_set_attr(clone, "x", "0");
2061 sp_repr_set_attr(clone, "y", "0");
2062 sp_repr_set_attr(clone, "xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")));
2064 sp_repr_set_attr(clone, "inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"));
2065 sp_repr_set_attr(clone, "inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"));
2067 // add the new clone to the top of the original's parent
2068 parent->appendChild(clone);
2070 newsel = g_slist_prepend(newsel, clone);
2071 reprs = g_slist_remove(reprs, sel_repr);
2072 Inkscape::GC::release(clone);
2073 }
2075 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2076 _("Clone"));
2078 selection->setReprList(newsel);
2080 g_slist_free(newsel);
2081 }
2083 void
2084 sp_selection_unlink()
2085 {
2086 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2087 if (!desktop)
2088 return;
2090 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2092 if (selection->isEmpty()) {
2093 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>clone</b> to unlink."));
2094 return;
2095 }
2097 // Get a copy of current selection.
2098 GSList *new_select = NULL;
2099 bool unlinked = false;
2100 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2101 items != NULL;
2102 items = items->next)
2103 {
2104 SPItem *use = (SPItem *) items->data;
2106 if (!SP_IS_USE(use)) {
2107 // keep the non-yse item in the new selection
2108 new_select = g_slist_prepend(new_select, use);
2109 continue;
2110 }
2112 SPItem *unlink = sp_use_unlink(SP_USE(use));
2113 unlinked = true;
2114 // Add ungrouped items to the new selection.
2115 new_select = g_slist_prepend(new_select, unlink);
2116 }
2118 if (new_select) { // set new selection
2119 selection->clear();
2120 selection->setList(new_select);
2121 g_slist_free(new_select);
2122 }
2123 if (!unlinked) {
2124 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2125 }
2127 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2128 _("Unlink clone"));
2129 }
2131 void
2132 sp_select_clone_original()
2133 {
2134 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2135 if (desktop == NULL)
2136 return;
2138 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2140 SPItem *item = selection->singleItem();
2142 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.");
2144 // Check if other than two objects are selected
2145 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2146 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2147 return;
2148 }
2150 SPItem *original = NULL;
2151 if (SP_IS_USE(item)) {
2152 original = sp_use_get_original (SP_USE(item));
2153 } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2154 original = sp_offset_get_source (SP_OFFSET(item));
2155 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2156 original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2157 } else if (SP_IS_FLOWTEXT(item)) {
2158 original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2159 } else { // it's an object that we don't know what to do with
2160 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2161 return;
2162 }
2164 if (!original) {
2165 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2166 return;
2167 }
2169 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2170 if (SP_IS_DEFS (o)) {
2171 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2172 return;
2173 }
2174 }
2176 if (original) {
2177 selection->clear();
2178 selection->set(original);
2179 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2180 scroll_to_show_item(desktop, original);
2181 }
2182 }
2183 }
2185 void
2186 sp_selection_tile(bool apply)
2187 {
2188 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2189 if (desktop == NULL)
2190 return;
2192 SPDocument *document = sp_desktop_document(desktop);
2193 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2195 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2197 // check if something is selected
2198 if (selection->isEmpty()) {
2199 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2200 return;
2201 }
2203 sp_document_ensure_up_to_date(document);
2204 NR::Maybe<NR::Rect> r = selection->bounds();
2205 if ( !r ) {
2206 return;
2207 }
2209 // calculate the transform to be applied to objects to move them to 0,0
2210 NR::Point move_p = NR::Point(0, sp_document_height(document)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2211 move_p[NR::Y] = -move_p[NR::Y];
2212 NR::Matrix move = NR::Matrix (NR::translate (move_p));
2214 GSList *items = g_slist_copy((GSList *) selection->itemList());
2216 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2218 // bottommost object, after sorting
2219 SPObject *parent = SP_OBJECT_PARENT (items->data);
2221 NR::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(parent));
2223 // remember the position of the first item
2224 gint pos = SP_OBJECT_REPR (items->data)->position();
2226 // create a list of duplicates
2227 GSList *repr_copies = NULL;
2228 for (GSList *i = items; i != NULL; i = i->next) {
2229 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2230 repr_copies = g_slist_prepend (repr_copies, dup);
2231 }
2233 NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2235 if (apply) {
2236 // delete objects so that their clones don't get alerted; this object will be restored shortly
2237 for (GSList *i = items; i != NULL; i = i->next) {
2238 SPObject *item = SP_OBJECT (i->data);
2239 item->deleteObject (false);
2240 }
2241 }
2243 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2244 // without disturbing clones.
2245 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2246 int saved_compensation = prefs_get_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2247 prefs_set_int_attribute("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2249 const gchar *pat_id = pattern_tile (repr_copies, bounds, document,
2250 NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X], r->max()[NR::Y])))) * parent_transform.inverse(), parent_transform * move);
2252 // restore compensation setting
2253 prefs_set_int_attribute("options.clonecompensation", "value", saved_compensation);
2255 if (apply) {
2256 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2257 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2259 NR::Point min = bounds.min() * parent_transform.inverse();
2260 NR::Point max = bounds.max() * parent_transform.inverse();
2262 sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2263 sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2264 sp_repr_set_svg_double(rect, "x", min[NR::X]);
2265 sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2267 // restore parent and position
2268 SP_OBJECT_REPR (parent)->appendChild(rect);
2269 rect->setPosition(pos > 0 ? pos : 0);
2270 SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2272 Inkscape::GC::release(rect);
2274 selection->clear();
2275 selection->set(rectangle);
2276 }
2278 g_slist_free (items);
2280 sp_document_done (document, SP_VERB_EDIT_TILE,
2281 _("Objects to pattern"));
2282 }
2284 void
2285 sp_selection_untile()
2286 {
2287 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2288 if (desktop == NULL)
2289 return;
2291 SPDocument *document = sp_desktop_document(desktop);
2293 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2295 // check if something is selected
2296 if (selection->isEmpty()) {
2297 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2298 return;
2299 }
2301 GSList *new_select = NULL;
2303 bool did = false;
2305 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2306 items != NULL;
2307 items = items->next) {
2309 SPItem *item = (SPItem *) items->data;
2311 SPStyle *style = SP_OBJECT_STYLE (item);
2313 if (!style || style->fill.type != SP_PAINT_TYPE_PAINTSERVER)
2314 continue;
2316 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2318 if (!SP_IS_PATTERN(server))
2319 continue;
2321 did = true;
2323 SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2325 NR::Matrix pat_transform = pattern_patternTransform (SP_PATTERN (server));
2326 pat_transform *= item->transform;
2328 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2329 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2330 SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2332 // FIXME: relink clones to the new canvas objects
2333 // use SPObject::setid when mental finishes it to steal ids of
2335 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2336 sp_document_ensure_up_to_date (document);
2338 NR::Matrix transform( i->transform * pat_transform );
2339 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2341 new_select = g_slist_prepend(new_select, i);
2342 }
2344 SPCSSAttr *css = sp_repr_css_attr_new ();
2345 sp_repr_css_set_property (css, "fill", "none");
2346 sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2347 }
2349 if (!did) {
2350 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2351 } else {
2352 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2353 _("Pattern to objects"));
2354 selection->setList(new_select);
2355 }
2356 }
2358 void
2359 sp_selection_get_export_hints (Inkscape::Selection *selection, const char **filename, float *xdpi, float *ydpi)
2360 {
2361 if (selection->isEmpty()) {
2362 return;
2363 }
2365 const GSList * reprlst = selection->reprList();
2366 bool filename_search = TRUE;
2367 bool xdpi_search = TRUE;
2368 bool ydpi_search = TRUE;
2370 for(; reprlst != NULL &&
2371 filename_search &&
2372 xdpi_search &&
2373 ydpi_search;
2374 reprlst = reprlst->next) {
2375 const gchar * dpi_string;
2376 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2378 if (filename_search) {
2379 *filename = repr->attribute("inkscape:export-filename");
2380 if (*filename != NULL)
2381 filename_search = FALSE;
2382 }
2384 if (xdpi_search) {
2385 dpi_string = NULL;
2386 dpi_string = repr->attribute("inkscape:export-xdpi");
2387 if (dpi_string != NULL) {
2388 *xdpi = atof(dpi_string);
2389 xdpi_search = FALSE;
2390 }
2391 }
2393 if (ydpi_search) {
2394 dpi_string = NULL;
2395 dpi_string = repr->attribute("inkscape:export-ydpi");
2396 if (dpi_string != NULL) {
2397 *ydpi = atof(dpi_string);
2398 ydpi_search = FALSE;
2399 }
2400 }
2401 }
2402 }
2404 void
2405 sp_document_get_export_hints (SPDocument * doc, const char **filename, float *xdpi, float *ydpi)
2406 {
2407 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2408 const gchar * dpi_string;
2410 *filename = repr->attribute("inkscape:export-filename");
2412 dpi_string = NULL;
2413 dpi_string = repr->attribute("inkscape:export-xdpi");
2414 if (dpi_string != NULL) {
2415 *xdpi = atof(dpi_string);
2416 }
2418 dpi_string = NULL;
2419 dpi_string = repr->attribute("inkscape:export-ydpi");
2420 if (dpi_string != NULL) {
2421 *ydpi = atof(dpi_string);
2422 }
2423 }
2425 void
2426 sp_selection_create_bitmap_copy ()
2427 {
2428 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2429 if (desktop == NULL)
2430 return;
2432 SPDocument *document = sp_desktop_document(desktop);
2433 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2435 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2437 // check if something is selected
2438 if (selection->isEmpty()) {
2439 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2440 return;
2441 }
2443 // Get the bounding box of the selection
2444 NRRect bbox;
2445 sp_document_ensure_up_to_date (document);
2446 selection->bounds(&bbox);
2447 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2448 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2449 }
2451 // List of the items to show; all others will be hidden
2452 GSList *items = g_slist_copy ((GSList *) selection->itemList());
2454 // Sort items so that the topmost comes last
2455 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2457 // Generate a random value from the current time (you may create bitmap from the same object(s)
2458 // multiple times, and this is done so that they don't clash)
2459 GTimeVal cu;
2460 g_get_current_time (&cu);
2461 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2463 // Create the filename
2464 gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2465 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2466 // digits, and a few other chars, with "_"
2467 filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2468 // Build the complete path by adding document->base if set
2469 gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2471 //g_print ("%s\n", filepath);
2473 // Remember parent and z-order of the topmost one
2474 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2475 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2476 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2478 // Calculate resolution
2479 double res;
2480 int const prefs_res = prefs_get_int_attribute ("options.createbitmap", "resolution", 0);
2481 int const prefs_min = prefs_get_int_attribute ("options.createbitmap", "minsize", 0);
2482 if (0 < prefs_res) {
2483 // If it's given explicitly in prefs, take it
2484 res = prefs_res;
2485 } else if (0 < prefs_min) {
2486 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2487 res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2488 } else {
2489 float hint_xdpi = 0, hint_ydpi = 0;
2490 const char *hint_filename;
2491 // take resolution hint from the selected objects
2492 sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2493 if (hint_xdpi != 0) {
2494 res = hint_xdpi;
2495 } else {
2496 // take resolution hint from the document
2497 sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2498 if (hint_xdpi != 0) {
2499 res = hint_xdpi;
2500 } else {
2501 // if all else fails, take the default 90 dpi
2502 res = PX_PER_IN;
2503 }
2504 }
2505 }
2507 // The width and height of the bitmap in pixels
2508 unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2509 unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2511 // Find out if we have to run a filter
2512 const gchar *run = NULL;
2513 const gchar *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
2514 if (filter) {
2515 // filter command is given;
2516 // see if we have a parameter to pass to it
2517 const gchar *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
2518 if (param1) {
2519 if (param1[strlen(param1) - 1] == '%') {
2520 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2521 gchar p1[256];
2522 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
2523 // the first param is always the image filename, the second is param1
2524 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
2525 } else {
2526 // otherwise pass the param1 unchanged
2527 run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
2528 }
2529 } else {
2530 // run without extra parameter
2531 run = g_strdup_printf ("%s \"%s\"", filter, filepath);
2532 }
2533 }
2535 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2536 NR::Matrix eek = sp_item_i2d_affine (SP_ITEM(parent_object));
2537 NR::Matrix t;
2539 double shift_x = bbox.x0;
2540 double shift_y = bbox.y1;
2541 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2542 shift_x = round (shift_x);
2543 shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2544 }
2545 t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2547 // Do the export
2548 sp_export_png_file(document, filepath,
2549 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2550 width, height, res, res,
2551 (guint32) 0xffffff00,
2552 NULL, NULL,
2553 true, /*bool force_overwrite,*/
2554 items);
2556 g_slist_free (items);
2558 // Run filter, if any
2559 if (run) {
2560 g_print ("Running external filter: %s\n", run);
2561 system (run);
2562 }
2564 // Import the image back
2565 GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2566 if (pb) {
2567 // Create the repr for the image
2568 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2569 repr->setAttribute("xlink:href", filename);
2570 repr->setAttribute("sodipodi:absref", filepath);
2571 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2572 sp_repr_set_svg_double(repr, "width", width);
2573 sp_repr_set_svg_double(repr, "height", height);
2574 } else {
2575 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2576 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2577 }
2579 // Write transform
2580 gchar *c=sp_svg_transform_write(t);
2581 repr->setAttribute("transform", c);
2582 g_free(c);
2584 // add the new repr to the parent
2585 parent->appendChild(repr);
2587 // move to the saved position
2588 repr->setPosition(pos > 0 ? pos + 1 : 1);
2590 // Set selection to the new image
2591 selection->clear();
2592 selection->add(repr);
2594 // Clean up
2595 Inkscape::GC::release(repr);
2596 gdk_pixbuf_unref (pb);
2598 // Complete undoable transaction
2599 sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2600 _("Create bitmap"));
2601 }
2603 g_free (filename);
2604 g_free (filepath);
2605 }
2607 /**
2608 * \brief sp_selection_set_mask
2609 *
2610 * This function creates a mask or clipPath from selection
2611 * Two different modes:
2612 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2613 * and is applied to current layer
2614 * otherwise, topmost object is used as mask for other objects
2615 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2616 *
2617 */
2618 void
2619 sp_selection_set_mask(bool apply_clip_path, bool apply_to_layer)
2620 {
2621 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2622 if (desktop == NULL)
2623 return;
2625 SPDocument *document = sp_desktop_document(desktop);
2627 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2629 // check if something is selected
2630 bool is_empty = selection->isEmpty();
2631 if ( apply_to_layer && is_empty) {
2632 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2633 return;
2634 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2635 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2636 return;
2637 }
2639 // FIXME: temporary patch to prevent crash!
2640 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2641 bool clone_with_original = selection_contains_both_clone_and_original (selection);
2642 if (clone_with_original) {
2643 return; // in this version, you cannot clip/mask an object with its own clone
2644 }
2645 // /END FIXME
2647 sp_document_ensure_up_to_date(document);
2649 GSList *items = g_slist_copy((GSList *) selection->itemList());
2651 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2653 // create a list of duplicates
2654 GSList *mask_items = NULL;
2655 GSList *apply_to_items = NULL;
2656 GSList *items_to_delete = NULL;
2657 bool topmost = prefs_get_int_attribute ("options.maskobject", "topmost", 1);
2658 bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2660 if (apply_to_layer) {
2661 // all selected items are used for mask, which is applied to a layer
2662 apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2664 for (GSList *i = items; i != NULL; i = i->next) {
2665 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2666 mask_items = g_slist_prepend (mask_items, dup);
2668 if (remove_original) {
2669 SPObject *item = SP_OBJECT (i->data);
2670 items_to_delete = g_slist_prepend (items_to_delete, item);
2671 }
2672 }
2673 } else if (!topmost) {
2674 // topmost item is used as a mask, which is applied to other items in a selection
2675 GSList *i = items;
2676 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2677 mask_items = g_slist_prepend (mask_items, dup);
2679 if (remove_original) {
2680 SPObject *item = SP_OBJECT (i->data);
2681 items_to_delete = g_slist_prepend (items_to_delete, item);
2682 }
2684 for (i = i->next; i != NULL; i = i->next) {
2685 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2686 }
2687 } else {
2688 GSList *i = NULL;
2689 for (i = items; NULL != i->next; i = i->next) {
2690 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2691 }
2693 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate();
2694 mask_items = g_slist_prepend (mask_items, dup);
2696 if (remove_original) {
2697 SPObject *item = SP_OBJECT (i->data);
2698 items_to_delete = g_slist_prepend (items_to_delete, item);
2699 }
2700 }
2702 g_slist_free (items);
2703 items = NULL;
2705 gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2706 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2707 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2708 // inverted object transform should be applied to a mask object,
2709 // as mask is calculated in user space (after applying transform)
2710 NR::Matrix maskTransform (item->transform.inverse());
2712 GSList *mask_items_dup = NULL;
2713 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2714 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate();
2715 mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2716 }
2718 const gchar *mask_id = NULL;
2719 if (apply_clip_path) {
2720 mask_id = sp_clippath_create(mask_items_dup, document, &maskTransform);
2721 } else {
2722 mask_id = sp_mask_create(mask_items_dup, document, &maskTransform);
2723 }
2725 g_slist_free (mask_items_dup);
2726 mask_items_dup = NULL;
2728 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2729 }
2731 g_slist_free (mask_items);
2732 g_slist_free (apply_to_items);
2734 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2735 SPObject *item = SP_OBJECT (i->data);
2736 item->deleteObject (false);
2737 }
2738 g_slist_free (items_to_delete);
2740 if (apply_clip_path)
2741 sp_document_done (document, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2742 else
2743 sp_document_done (document, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2744 }
2746 void sp_selection_unset_mask(bool apply_clip_path) {
2747 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
2748 if (desktop == NULL)
2749 return;
2751 SPDocument *document = sp_desktop_document(desktop);
2752 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2754 // check if something is selected
2755 if (selection->isEmpty()) {
2756 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2757 return;
2758 }
2760 bool remove_original = prefs_get_int_attribute ("options.maskobject", "remove", 1);
2761 sp_document_ensure_up_to_date(document);
2763 gchar const* attributeName = apply_clip_path ? "clip-path" : "mask";
2764 std::map<SPObject*,SPItem*> referenced_objects;
2765 for (GSList const*i = selection->itemList(); NULL != i; i = i->next) {
2766 if (remove_original) {
2767 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2768 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2769 Inkscape::URIReference *uri_ref = NULL;
2771 if (apply_clip_path) {
2772 uri_ref = item->clip_ref;
2773 } else {
2774 uri_ref = item->mask_ref;
2775 }
2777 // collect distinct mask object (and associate with item to apply transform)
2778 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2779 referenced_objects[uri_ref->getObject()] = item;
2780 }
2781 }
2783 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2784 }
2786 // restore mask objects into a document
2787 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2788 SPObject *obj = (*it).first;
2789 GSList *items_to_move = NULL;
2790 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2791 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate();
2792 items_to_move = g_slist_prepend (items_to_move, copy);
2793 }
2795 if (!obj->isReferenced()) {
2796 // delete from defs if no other object references this mask
2797 obj->deleteObject(false);
2798 }
2800 // remember parent and position of the item to which the clippath/mask was applied
2801 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2802 gint pos = SP_OBJECT_REPR((*it).second)->position();
2804 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2805 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2807 // insert into parent, restore pos
2808 parent->appendChild(repr);
2809 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2811 SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2812 selection->add(repr);
2814 // transform mask, so it is moved the same spot where mask was applied
2815 NR::Matrix transform (mask_item->transform);
2816 transform *= (*it).second->transform;
2817 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2818 }
2820 g_slist_free (items_to_move);
2821 }
2823 if (apply_clip_path)
2824 sp_document_done (document, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2825 else
2826 sp_document_done (document, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2827 }
2829 void fit_canvas_to_selection(SPDesktop *desktop) {
2830 g_return_if_fail(desktop != NULL);
2831 SPDocument *doc = sp_desktop_document(desktop);
2833 g_return_if_fail(doc != NULL);
2834 g_return_if_fail(desktop->selection != NULL);
2835 g_return_if_fail(!desktop->selection->isEmpty());
2836 NRRect bbox(0, 0, 0, 0);
2838 desktop->selection->bounds(&bbox);
2839 if (!nr_rect_d_test_empty(&bbox)) {
2840 doc->fitToRect(bbox);
2841 }
2842 };
2844 void fit_canvas_to_drawing(SPDocument *doc) {
2845 g_return_if_fail(doc != NULL);
2846 NRRect bbox(0, 0, 0, 0);
2848 sp_document_ensure_up_to_date (doc);
2849 sp_item_invoke_bbox(SP_ITEM(doc->root), &bbox, sp_item_i2r_affine(SP_ITEM(doc->root)), TRUE);
2851 if (!nr_rect_d_test_empty(&bbox)) {
2852 doc->fitToRect(bbox);
2853 }
2854 };
2856 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2857 g_return_if_fail(desktop != NULL);
2858 SPDocument *doc = sp_desktop_document(desktop);
2860 g_return_if_fail(doc != NULL);
2861 g_return_if_fail(desktop->selection != NULL);
2863 if (desktop->selection->isEmpty()) {
2864 fit_canvas_to_drawing(doc);
2865 } else {
2866 fit_canvas_to_selection(desktop);
2867 }
2869 sp_document_done(doc, SP_VERB_FIT_CANVAS_TO_DRAWING,
2870 _("Fit page to selection"));
2871 };
2873 /*
2874 Local Variables:
2875 mode:c++
2876 c-file-style:"stroustrup"
2877 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2878 indent-tabs-mode:nil
2879 fill-column:99
2880 End:
2881 */
2882 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :