591cc795dcb627cd6799e470c7efea7f816232b5
1 #define __SP_SELECTION_CHEMISTRY_C__
3 /** @file
4 * @brief 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 "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "desktop.h"
29 #include "desktop-style.h"
30 #include "selection.h"
31 #include "tools-switch.h"
32 #include "desktop-handles.h"
33 #include "message-stack.h"
34 #include "sp-item-transform.h"
35 #include "marker.h"
36 #include "sp-use.h"
37 #include "sp-textpath.h"
38 #include "sp-tspan.h"
39 #include "sp-tref.h"
40 #include "sp-flowtext.h"
41 #include "sp-flowregion.h"
42 #include "text-editing.h"
43 #include "text-context.h"
44 #include "connector-context.h"
45 #include "sp-path.h"
46 #include "sp-conn-end.h"
47 #include "dropper-context.h"
48 #include <glibmm/i18n.h>
49 #include "libnr/nr-matrix-rotate-ops.h"
50 #include "libnr/nr-matrix-translate-ops.h"
51 #include "libnr/nr-scale-ops.h"
52 #include <libnr/nr-matrix-ops.h>
53 #include <libnr/nr-rotate-ops.h>
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "libnr/nr-translate-matrix-ops.h"
56 #include "libnr/nr-translate-scale-ops.h"
57 #include "xml/repr.h"
58 #include "style.h"
59 #include "document-private.h"
60 #include "sp-gradient.h"
61 #include "sp-gradient-reference.h"
62 #include "sp-linear-gradient-fns.h"
63 #include "sp-pattern.h"
64 #include "sp-radial-gradient-fns.h"
65 #include "sp-namedview.h"
66 #include "preferences.h"
67 #include "sp-offset.h"
68 #include "sp-clippath.h"
69 #include "sp-mask.h"
70 #include "file.h"
71 #include "helper/png-write.h"
72 #include "layer-fns.h"
73 #include "context-fns.h"
74 #include <map>
75 #include <cstring>
76 #include <string>
77 #include "helper/units.h"
78 #include "sp-item.h"
79 #include "box3d.h"
80 #include "unit-constants.h"
81 #include "xml/simple-document.h"
82 #include "sp-filter-reference.h"
83 #include "gradient-drag.h"
84 #include "uri-references.h"
85 #include "libnr/nr-convert2geom.h"
86 #include "display/curve.h"
87 #include "display/canvas-bpath.h"
89 // For clippath editing
90 #include "tools-switch.h"
91 #include "shape-editor.h"
92 #include "node-context.h"
93 #include "nodepath.h"
95 #include "ui/clipboard.h"
97 using NR::X;
98 using NR::Y;
100 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
101 because the layer manipulation code uses them. It should be rewritten specifically
102 for that purpose. */
104 /**
105 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
106 * then prepends the copy to 'clip'.
107 */
108 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
109 {
110 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
112 // copy complete inherited style
113 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
114 sp_repr_css_set(copy, css, "style");
115 sp_repr_css_attr_unref(css);
117 // write the complete accumulated transform passed to us
118 // (we're dealing with unattached repr, so we write to its attr
119 // instead of using sp_item_set_transform)
120 gchar *affinestr=sp_svg_transform_write(full_t);
121 copy->setAttribute("transform", affinestr);
122 g_free(affinestr);
124 *clip = g_slist_prepend(*clip, copy);
125 }
127 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
128 {
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, xml_doc);
136 }
138 *clip = g_slist_reverse(*clip);
139 g_slist_free ((GSList *) sorted_items);
140 }
142 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
143 {
144 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
146 GSList *copied = NULL;
147 // add objects to document
148 for (GSList *l = *clip; l != NULL; l = l->next) {
149 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
150 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
152 // premultiply the item transform by the accumulated parent transform in the paste layer
153 NR::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
154 if (!local.test_identity()) {
155 gchar const *t_str = copy->attribute("transform");
156 Geom::Matrix item_t (Geom::identity());
157 if (t_str)
158 sp_svg_transform_read(t_str, &item_t);
159 item_t *= local.inverse();
160 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
161 gchar *affinestr=sp_svg_transform_write(item_t);
162 copy->setAttribute("transform", affinestr);
163 g_free(affinestr);
164 }
166 parent->appendChildRepr(copy);
167 copied = g_slist_prepend(copied, copy);
168 Inkscape::GC::release(copy);
169 }
170 return copied;
171 }
173 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
174 {
175 for (GSList const *i = items ; i ; i = i->next ) {
176 sp_object_ref((SPObject *)i->data, NULL);
177 }
178 for (GSList const *i = items; i != NULL; i = i->next) {
179 SPItem *item = (SPItem *) i->data;
180 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
181 sp_object_unref((SPObject *)item, NULL);
182 }
183 }
186 void sp_selection_delete(SPDesktop *desktop)
187 {
188 if (desktop == NULL) {
189 return;
190 }
192 if (tools_isactive (desktop, TOOLS_TEXT))
193 if (sp_text_delete_selection(desktop->event_context)) {
194 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
195 _("Delete text"));
196 return;
197 }
199 Inkscape::Selection *selection = sp_desktop_selection(desktop);
201 // check if something is selected
202 if (selection->isEmpty()) {
203 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
204 return;
205 }
207 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
208 selection->clear();
209 sp_selection_delete_impl (selected);
210 g_slist_free ((GSList *) selected);
212 /* a tool may have set up private information in it's selection context
213 * that depends on desktop items. I think the only sane way to deal with
214 * this currently is to reset the current tool, which will reset it's
215 * associated selection context. For example: deleting an object
216 * while moving it around the canvas.
217 */
218 tools_switch ( desktop, tools_active ( desktop ) );
220 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
221 _("Delete"));
222 }
224 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
225 {
226 if (!obj)
227 return;
229 ids.push_back(SP_OBJECT_ID(obj));
231 if (SP_IS_GROUP(obj)) {
232 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
233 add_ids_recursive (ids, child);
234 }
235 }
236 }
238 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
239 {
240 if (desktop == NULL)
241 return;
243 SPDocument *doc = desktop->doc();
244 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
245 Inkscape::Selection *selection = sp_desktop_selection(desktop);
247 // check if something is selected
248 if (selection->isEmpty()) {
249 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
250 return;
251 }
253 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
255 selection->clear();
257 // sorting items from different parents sorts each parent's subset without possibly mixing
258 // them, just what we need
259 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
261 GSList *newsel = NULL;
263 std::vector<const gchar *> old_ids;
264 std::vector<const gchar *> new_ids;
265 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
266 bool relink_clones = prefs->getBool("options.relinkclonesonduplicate", "value");
268 while (reprs) {
269 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
270 Inkscape::XML::Node *parent = old_repr->parent();
271 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
273 parent->appendChild(copy);
275 if (relink_clones) {
276 SPObject *old_obj = doc->getObjectByRepr(old_repr);
277 SPObject *new_obj = doc->getObjectByRepr(copy);
278 add_ids_recursive (old_ids, old_obj);
279 add_ids_recursive (new_ids, new_obj);
280 }
282 newsel = g_slist_prepend(newsel, copy);
283 reprs = g_slist_remove(reprs, reprs->data);
284 Inkscape::GC::release(copy);
285 }
287 if (relink_clones) {
289 g_assert (old_ids.size() == new_ids.size());
291 for(unsigned int i = 0; i < old_ids.size(); i++) {
292 const gchar *id = old_ids[i];
293 SPObject *old_clone = doc->getObjectById(id);
294 if (SP_IS_USE(old_clone)) {
295 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
296 for(unsigned int j = 0; j < old_ids.size(); j++) {
297 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
298 // we have both orig and clone in selection, relink
299 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
300 gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
301 SPObject *new_clone = doc->getObjectById(new_ids[i]);
302 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
303 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
304 g_free (newref);
305 }
306 }
307 }
308 }
309 }
312 if ( !suppressDone ) {
313 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
314 _("Duplicate"));
315 }
317 selection->setReprList(newsel);
319 g_slist_free(newsel);
320 }
322 void sp_edit_clear_all(SPDesktop *dt)
323 {
324 if (!dt)
325 return;
327 SPDocument *doc = sp_desktop_document(dt);
328 sp_desktop_selection(dt)->clear();
330 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
331 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
333 while (items) {
334 SP_OBJECT (items->data)->deleteObject();
335 items = g_slist_remove(items, items->data);
336 }
338 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
339 _("Delete all"));
340 }
342 GSList *
343 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
344 {
345 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
346 if (SP_IS_ITEM(child) &&
347 !desktop->isLayer(SP_ITEM(child)) &&
348 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
349 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
350 (!exclude || !g_slist_find ((GSList *) exclude, child))
351 )
352 {
353 list = g_slist_prepend (list, SP_ITEM(child));
354 }
356 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
357 list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
358 }
359 }
361 return list;
362 }
364 void sp_edit_select_all_full (SPDesktop *dt, bool force_all_layers, bool invert)
365 {
366 if (!dt)
367 return;
369 Inkscape::Selection *selection = sp_desktop_selection(dt);
371 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
373 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
374 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
375 bool onlyvisible = prefs->getBool("options.kbselection", "onlyvisible", true);
376 bool onlysensitive = prefs->getBool("options.kbselection", "onlysensitive", true);
378 GSList *items = NULL;
380 GSList const *exclude = NULL;
381 if (invert) {
382 exclude = selection->itemList();
383 }
385 if (force_all_layers)
386 inlayer = PREFS_SELECTION_ALL;
388 switch (inlayer) {
389 case PREFS_SELECTION_LAYER: {
390 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
391 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
392 return;
394 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
396 for (GSList *i = all_items; i; i = i->next) {
397 SPItem *item = SP_ITEM (i->data);
399 if (item && (!onlysensitive || !item->isLocked())) {
400 if (!onlyvisible || !dt->itemIsHidden(item)) {
401 if (!dt->isLayer(item)) {
402 if (!invert || !g_slist_find ((GSList *) exclude, item)) {
403 items = g_slist_prepend (items, item); // leave it in the list
404 }
405 }
406 }
407 }
408 }
410 g_slist_free (all_items);
411 break;
412 }
413 case PREFS_SELECTION_LAYER_RECURSIVE: {
414 items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
415 break;
416 }
417 default: {
418 items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
419 break;
420 }
421 }
423 selection->setList (items);
425 if (items) {
426 g_slist_free (items);
427 }
428 }
430 void sp_edit_select_all (SPDesktop *desktop)
431 {
432 sp_edit_select_all_full (desktop, false, false);
433 }
435 void sp_edit_select_all_in_all_layers (SPDesktop *desktop)
436 {
437 sp_edit_select_all_full (desktop, true, false);
438 }
440 void sp_edit_invert (SPDesktop *desktop)
441 {
442 sp_edit_select_all_full (desktop, false, true);
443 }
445 void sp_edit_invert_in_all_layers (SPDesktop *desktop)
446 {
447 sp_edit_select_all_full (desktop, true, true);
448 }
450 void sp_selection_group(SPDesktop *desktop)
451 {
452 if (desktop == NULL)
453 return;
455 SPDocument *doc = sp_desktop_document (desktop);
456 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
458 Inkscape::Selection *selection = sp_desktop_selection(desktop);
460 // Check if something is selected.
461 if (selection->isEmpty()) {
462 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
463 return;
464 }
466 GSList const *l = (GSList *) selection->reprList();
468 GSList *p = g_slist_copy((GSList *) l);
470 selection->clear();
472 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
474 // Remember the position and parent of the topmost object.
475 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
476 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
478 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
480 while (p) {
481 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
483 if (current->parent() == topmost_parent) {
484 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
485 sp_repr_unparent(current);
486 group->appendChild(spnew);
487 Inkscape::GC::release(spnew);
488 topmost --; // only reduce count for those items deleted from topmost_parent
489 } else { // move it to topmost_parent first
490 GSList *temp_clip = NULL;
492 // At this point, current may already have no item, due to its being a clone whose original is already moved away
493 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
494 gchar const *t_str = current->attribute("transform");
495 Geom::Matrix item_t (Geom::identity());
496 if (t_str)
497 sp_svg_transform_read(t_str, &item_t);
498 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
499 //FIXME: when moving both clone and original from a transformed group (either by
500 //grouping into another parent, or by cut/paste) the transform from the original's
501 //parent becomes embedded into original itself, and this affects its clones. Fix
502 //this by remembering the transform diffs we write to each item into an array and
503 //then, if this is clone, looking up its original in that array and pre-multiplying
504 //it by the inverse of that original's transform diff.
506 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
507 sp_repr_unparent(current);
509 // paste into topmost_parent (temporarily)
510 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
511 if (temp_clip) g_slist_free (temp_clip);
512 if (copied) { // if success,
513 // take pasted object (now in topmost_parent)
514 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
515 // make a copy
516 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
517 // remove pasted
518 sp_repr_unparent(in_topmost);
519 // put its copy into group
520 group->appendChild(spnew);
521 Inkscape::GC::release(spnew);
522 g_slist_free (copied);
523 }
524 }
525 p = g_slist_remove(p, current);
526 }
528 // Add the new group to the topmost members' parent
529 topmost_parent->appendChild(group);
531 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
532 group->setPosition(topmost + 1);
534 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
535 _("Group"));
537 selection->set(group);
538 Inkscape::GC::release(group);
539 }
541 void sp_selection_ungroup(SPDesktop *desktop)
542 {
543 if (desktop == NULL)
544 return;
546 Inkscape::Selection *selection = sp_desktop_selection(desktop);
548 if (selection->isEmpty()) {
549 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
550 return;
551 }
553 GSList *items = g_slist_copy((GSList *) selection->itemList());
554 selection->clear();
556 // Get a copy of current selection.
557 GSList *new_select = NULL;
558 bool ungrouped = false;
559 for (GSList *i = items;
560 i != NULL;
561 i = i->next)
562 {
563 SPItem *group = (SPItem *) i->data;
565 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
566 if (!SP_IS_OBJECT(group)) {
567 continue;
568 }
570 /* We do not allow ungrouping <svg> etc. (lauris) */
571 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
572 // keep the non-group item in the new selection
573 selection->add(group);
574 continue;
575 }
577 GSList *children = NULL;
578 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
579 sp_item_group_ungroup(SP_GROUP(group), &children, false);
580 ungrouped = true;
581 // Add ungrouped items to the new selection.
582 new_select = g_slist_concat(new_select, children);
583 }
585 if (new_select) { // Set new selection.
586 selection->addList(new_select);
587 g_slist_free(new_select);
588 }
589 if (!ungrouped) {
590 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
591 }
593 g_slist_free(items);
595 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
596 _("Ungroup"));
597 }
599 static SPGroup *
600 sp_item_list_common_parent_group(GSList const *items)
601 {
602 if (!items) {
603 return NULL;
604 }
605 SPObject *parent = SP_OBJECT_PARENT(items->data);
606 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
607 if (!SP_IS_GROUP(parent)) {
608 return NULL;
609 }
610 for (items = items->next; items; items = items->next) {
611 if (SP_OBJECT_PARENT(items->data) != parent) {
612 return NULL;
613 }
614 }
616 return SP_GROUP(parent);
617 }
619 /** Finds out the minimum common bbox of the selected items. */
620 static boost::optional<NR::Rect>
621 enclose_items(GSList const *items)
622 {
623 g_assert(items != NULL);
625 boost::optional<NR::Rect> r;
626 for (GSList const *i = items; i; i = i->next) {
627 r = NR::union_bounds(r, sp_item_bbox_desktop((SPItem *) i->data));
628 }
629 return r;
630 }
632 SPObject *
633 prev_sibling(SPObject *child)
634 {
635 SPObject *parent = SP_OBJECT_PARENT(child);
636 if (!SP_IS_GROUP(parent)) {
637 return NULL;
638 }
639 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
640 if (i->next == child)
641 return i;
642 }
643 return NULL;
644 }
646 void
647 sp_selection_raise(SPDesktop *desktop)
648 {
649 if (!desktop)
650 return;
652 Inkscape::Selection *selection = sp_desktop_selection(desktop);
654 GSList const *items = (GSList *) selection->itemList();
655 if (!items) {
656 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
657 return;
658 }
660 SPGroup const *group = sp_item_list_common_parent_group(items);
661 if (!group) {
662 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
663 return;
664 }
666 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
668 /* Construct reverse-ordered list of selected children. */
669 GSList *rev = g_slist_copy((GSList *) items);
670 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
672 // Determine the common bbox of the selected items.
673 boost::optional<NR::Rect> selected = enclose_items(items);
675 // Iterate over all objects in the selection (starting from top).
676 if (selected) {
677 while (rev) {
678 SPObject *child = SP_OBJECT(rev->data);
679 // for each selected object, find the next sibling
680 for (SPObject *newref = child->next; newref; newref = newref->next) {
681 // if the sibling is an item AND overlaps our selection,
682 if (SP_IS_ITEM(newref)) {
683 boost::optional<NR::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
684 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
685 // AND if it's not one of our selected objects,
686 if (!g_slist_find((GSList *) items, newref)) {
687 // move the selected object after that sibling
688 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
689 }
690 break;
691 }
692 }
693 }
694 rev = g_slist_remove(rev, child);
695 }
696 } else {
697 g_slist_free(rev);
698 }
700 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
701 //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
702 Q_("undo_action|Raise"));
703 }
705 void sp_selection_raise_to_top(SPDesktop *desktop)
706 {
707 if (desktop == NULL)
708 return;
710 SPDocument *document = sp_desktop_document(desktop);
711 Inkscape::Selection *selection = sp_desktop_selection(desktop);
713 if (selection->isEmpty()) {
714 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
715 return;
716 }
718 GSList const *items = (GSList *) selection->itemList();
720 SPGroup const *group = sp_item_list_common_parent_group(items);
721 if (!group) {
722 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
723 return;
724 }
726 GSList *rl = g_slist_copy((GSList *) selection->reprList());
727 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
729 for (GSList *l = rl; l != NULL; l = l->next) {
730 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
731 repr->setPosition(-1);
732 }
734 g_slist_free(rl);
736 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
737 _("Raise to top"));
738 }
740 void
741 sp_selection_lower(SPDesktop *desktop)
742 {
743 if (desktop == NULL)
744 return;
746 Inkscape::Selection *selection = sp_desktop_selection(desktop);
748 GSList const *items = (GSList *) selection->itemList();
749 if (!items) {
750 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
751 return;
752 }
754 SPGroup const *group = sp_item_list_common_parent_group(items);
755 if (!group) {
756 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
757 return;
758 }
760 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
762 // Determine the common bbox of the selected items.
763 boost::optional<NR::Rect> selected = enclose_items(items);
765 /* Construct direct-ordered list of selected children. */
766 GSList *rev = g_slist_copy((GSList *) items);
767 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
768 rev = g_slist_reverse(rev);
770 // Iterate over all objects in the selection (starting from top).
771 if (selected) {
772 while (rev) {
773 SPObject *child = SP_OBJECT(rev->data);
774 // for each selected object, find the prev sibling
775 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
776 // if the sibling is an item AND overlaps our selection,
777 if (SP_IS_ITEM(newref)) {
778 boost::optional<NR::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
779 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
780 // AND if it's not one of our selected objects,
781 if (!g_slist_find((GSList *) items, newref)) {
782 // move the selected object before that sibling
783 SPObject *put_after = prev_sibling(newref);
784 if (put_after)
785 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
786 else
787 SP_OBJECT_REPR(child)->setPosition(0);
788 }
789 break;
790 }
791 }
792 }
793 rev = g_slist_remove(rev, child);
794 }
795 } else {
796 g_slist_free(rev);
797 }
799 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
800 _("Lower"));
801 }
803 void sp_selection_lower_to_bottom(SPDesktop *desktop)
804 {
805 if (desktop == NULL)
806 return;
808 SPDocument *document = sp_desktop_document(desktop);
809 Inkscape::Selection *selection = sp_desktop_selection(desktop);
811 if (selection->isEmpty()) {
812 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
813 return;
814 }
816 GSList const *items = (GSList *) selection->itemList();
818 SPGroup const *group = sp_item_list_common_parent_group(items);
819 if (!group) {
820 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
821 return;
822 }
824 GSList *rl;
825 rl = g_slist_copy((GSList *) selection->reprList());
826 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
827 rl = g_slist_reverse(rl);
829 for (GSList *l = rl; l != NULL; l = l->next) {
830 gint minpos;
831 SPObject *pp, *pc;
832 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
833 pp = document->getObjectByRepr(sp_repr_parent(repr));
834 minpos = 0;
835 g_assert(SP_IS_GROUP(pp));
836 pc = sp_object_first_child(pp);
837 while (!SP_IS_ITEM(pc)) {
838 minpos += 1;
839 pc = pc->next;
840 }
841 repr->setPosition(minpos);
842 }
844 g_slist_free(rl);
846 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
847 _("Lower to bottom"));
848 }
850 void
851 sp_undo(SPDesktop *desktop, SPDocument *)
852 {
853 if (!sp_document_undo(sp_desktop_document(desktop)))
854 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
855 }
857 void
858 sp_redo(SPDesktop *desktop, SPDocument *)
859 {
860 if (!sp_document_redo(sp_desktop_document(desktop)))
861 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
862 }
864 void sp_selection_cut(SPDesktop *desktop)
865 {
866 sp_selection_copy();
867 sp_selection_delete(desktop);
868 }
870 /**
871 * \pre item != NULL
872 */
873 SPCSSAttr *
874 take_style_from_item (SPItem *item)
875 {
876 // write the complete cascaded style, context-free
877 SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
878 if (css == NULL)
879 return NULL;
881 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
882 (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
883 // if this is a text with exactly one tspan child, merge the style of that tspan as well
884 // If this is a group, merge the style of its topmost (last) child with style
885 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
886 if (SP_OBJECT_STYLE (last_element) != NULL) {
887 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
888 if (temp) {
889 sp_repr_css_merge (css, temp);
890 sp_repr_css_attr_unref (temp);
891 }
892 break;
893 }
894 }
895 }
896 if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
897 // do not copy text properties from non-text objects, it's confusing
898 css = sp_css_attr_unset_text (css);
899 }
901 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
902 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
903 if (ex != 1.0) {
904 css = sp_css_attr_scale (css, ex);
905 }
907 return css;
908 }
911 void sp_selection_copy()
912 {
913 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
914 cm->copy();
915 }
917 void sp_selection_paste(SPDesktop *desktop, bool in_place)
918 {
919 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
920 if(cm->paste(in_place))
921 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
922 }
924 void sp_selection_paste_style(SPDesktop *desktop)
925 {
926 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
927 if(cm->pasteStyle())
928 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
929 }
932 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
933 {
934 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
935 if(cm->pastePathEffect())
936 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
937 _("Paste live path effect"));
938 }
941 void sp_selection_remove_livepatheffect_impl(SPItem *item)
942 {
943 if ( item && SP_IS_LPE_ITEM(item) ) {
944 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
945 }
946 }
948 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
949 {
950 if (desktop == NULL) return;
952 Inkscape::Selection *selection = sp_desktop_selection(desktop);
954 // check if something is selected
955 if (selection->isEmpty()) {
956 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
957 return;
958 }
960 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
961 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
963 sp_selection_remove_livepatheffect_impl(item);
965 }
967 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
968 _("Remove live path effect"));
969 }
971 void sp_selection_remove_filter (SPDesktop *desktop)
972 {
973 if (desktop == NULL) return;
975 Inkscape::Selection *selection = sp_desktop_selection(desktop);
977 // check if something is selected
978 if (selection->isEmpty()) {
979 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
980 return;
981 }
983 SPCSSAttr *css = sp_repr_css_attr_new();
984 sp_repr_css_unset_property(css, "filter");
985 sp_desktop_set_style(desktop, css);
986 sp_repr_css_attr_unref(css);
988 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
989 _("Remove filter"));
990 }
993 void sp_selection_paste_size (SPDesktop *desktop, bool apply_x, bool apply_y)
994 {
995 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
996 if(cm->pasteSize(false, apply_x, apply_y))
997 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
998 _("Paste size"));
999 }
1001 void sp_selection_paste_size_separately (SPDesktop *desktop, bool apply_x, bool apply_y)
1002 {
1003 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1004 if(cm->pasteSize(true, apply_x, apply_y))
1005 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1006 _("Paste size separately"));
1007 }
1009 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1010 {
1011 Inkscape::Selection *selection = sp_desktop_selection(dt);
1013 // check if something is selected
1014 if (selection->isEmpty()) {
1015 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1016 return;
1017 }
1019 GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1021 bool no_more = false; // Set to true, if no more layers above
1022 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1023 if (next) {
1024 GSList *temp_clip = NULL;
1025 sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1026 sp_selection_delete_impl (items, false, false);
1027 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1028 GSList *copied;
1029 if(next) {
1030 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1031 } else {
1032 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1033 no_more = true;
1034 }
1035 selection->setReprList((GSList const *) copied);
1036 g_slist_free (copied);
1037 if (temp_clip) g_slist_free (temp_clip);
1038 if (next) dt->setCurrentLayer(next);
1039 if ( !suppressDone ) {
1040 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1041 _("Raise to next layer"));
1042 }
1043 } else {
1044 no_more = true;
1045 }
1047 if (no_more) {
1048 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1049 }
1051 g_slist_free ((GSList *) items);
1052 }
1054 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1055 {
1056 Inkscape::Selection *selection = sp_desktop_selection(dt);
1058 // check if something is selected
1059 if (selection->isEmpty()) {
1060 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1061 return;
1062 }
1064 GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1066 bool no_more = false; // Set to true, if no more layers below
1067 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1068 if (next) {
1069 GSList *temp_clip = NULL;
1070 sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1071 sp_selection_delete_impl (items, false, false);
1072 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1073 GSList *copied;
1074 if(next) {
1075 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1076 } else {
1077 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1078 no_more = true;
1079 }
1080 selection->setReprList((GSList const *) copied);
1081 g_slist_free (copied);
1082 if (temp_clip) g_slist_free (temp_clip);
1083 if (next) dt->setCurrentLayer(next);
1084 if ( !suppressDone ) {
1085 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1086 _("Lower to previous layer"));
1087 }
1088 } else {
1089 no_more = true;
1090 }
1092 if (no_more) {
1093 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1094 }
1096 g_slist_free ((GSList *) items);
1097 }
1099 bool
1100 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1101 {
1102 bool contains_original = false;
1104 bool is_use = SP_IS_USE(item);
1105 SPItem *item_use = item;
1106 SPItem *item_use_first = item;
1107 while (is_use && item_use && !contains_original)
1108 {
1109 item_use = sp_use_get_original (SP_USE(item_use));
1110 contains_original |= selection->includes(item_use);
1111 if (item_use == item_use_first)
1112 break;
1113 is_use = SP_IS_USE(item_use);
1114 }
1116 // If it's a tref, check whether the object containing the character
1117 // data is part of the selection
1118 if (!contains_original && SP_IS_TREF(item)) {
1119 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1120 }
1122 return contains_original;
1123 }
1126 bool
1127 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1128 {
1129 bool clone_with_original = false;
1130 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1131 SPItem *item = SP_ITEM(l->data);
1132 clone_with_original |= selection_contains_original(item, selection);
1133 if (clone_with_original)
1134 break;
1135 }
1136 return clone_with_original;
1137 }
1140 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1141 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1142 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1143 that case, items are already in the new position, but the repr is in the old, and this function
1144 then simply updates the repr from item->transform.
1145 */
1146 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1147 {
1148 if (selection->isEmpty())
1149 return;
1151 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1152 SPItem *item = SP_ITEM(l->data);
1154 Geom::Point old_center(0,0);
1155 if (set_i2d && item->isCenterSet())
1156 old_center = item->getCenter();
1158 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1159 At the time of writing, this is the only place to re-enable. */
1160 sp_item_update_cns(*item, selection->desktop());
1161 #endif
1163 // we're moving both a clone and its original or any ancestor in clone chain?
1164 bool transform_clone_with_original = selection_contains_original(item, selection);
1165 // ...both a text-on-path and its path?
1166 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)))) ));
1167 // ...both a flowtext and its frame?
1168 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)
1169 // ...both an offset and its source?
1170 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1172 // If we're moving a connector, we want to detach it
1173 // from shapes that aren't part of the selection, but
1174 // leave it attached if they are
1175 if (cc_item_is_connector(item)) {
1176 SPItem *attItem[2];
1177 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1179 for (int n = 0; n < 2; ++n) {
1180 if (!selection->includes(attItem[n])) {
1181 sp_conn_end_detach(item, n);
1182 }
1183 }
1184 }
1186 // "clones are unmoved when original is moved" preference
1187 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1188 int compensation = prefs->getInt("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
1189 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1190 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1192 // If this is a clone and it's selected along with its original, do not move it; it will feel the
1193 // transform of its original and respond to it itself. Without this, a clone is doubly
1194 // transformed, very unintuitive.
1195 // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1196 // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1197 // Same for linked offset if we are also moving its source: do not move it.
1198 if (transform_textpath_with_path || transform_offset_with_source) {
1199 // restore item->transform field from the repr, in case it was changed by seltrans
1200 sp_object_read_attr (SP_OBJECT (item), "transform");
1202 } else if (transform_flowtext_with_frame) {
1203 // apply the inverse of the region's transform to the <use> so that the flow remains
1204 // the same (even though the output itself gets transformed)
1205 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1206 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1207 continue;
1208 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1209 if (!SP_IS_USE(use)) continue;
1210 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1211 }
1212 }
1213 } else if (transform_clone_with_original) {
1214 // We are transforming a clone along with its original. The below matrix juggling is
1215 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1216 // transform and its move compensation are both cancelled out.
1218 // restore item->transform field from the repr, in case it was changed by seltrans
1219 sp_object_read_attr (SP_OBJECT (item), "transform");
1221 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1222 Geom::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1223 Geom::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1224 NR::Matrix t_nr = from_2geom(t);
1225 Geom::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1226 Geom::Matrix result = t_inv * item->transform * t;
1228 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1229 // we need to cancel out the move compensation, too
1231 // find out the clone move, same as in sp_use_move_compensate
1232 Geom::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1233 Geom::Matrix clone_move = parent.inverse() * t * parent;
1235 if (prefs_parallel) {
1236 Geom::Matrix move = result * clone_move * t_inv;
1237 NR::Matrix move_nr = from_2geom(move);
1238 sp_item_write_transform(item, SP_OBJECT_REPR(item), from_2geom(move), &move_nr);
1240 } else if (prefs_unmoved) {
1241 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1242 // clone_move = NR::identity();
1243 Geom::Matrix move = result * clone_move;
1244 sp_item_write_transform(item, SP_OBJECT_REPR(item), from_2geom(move), &t_nr);
1245 }
1247 } else {
1248 // just apply the result
1249 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t_nr);
1250 }
1252 } else {
1253 if (set_i2d) {
1254 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1255 }
1256 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1257 }
1259 // if we're moving the actual object, not just updating the repr, we can transform the
1260 // center by the same matrix (only necessary for non-translations)
1261 if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1262 item->setCenter(old_center * affine);
1263 SP_OBJECT(item)->updateRepr();
1264 }
1265 }
1266 }
1268 void sp_selection_remove_transform(SPDesktop *desktop)
1269 {
1270 if (desktop == NULL)
1271 return;
1273 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1275 GSList const *l = (GSList *) selection->reprList();
1276 while (l != NULL) {
1277 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1278 l = l->next;
1279 }
1281 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1282 _("Remove transform"));
1283 }
1285 void
1286 sp_selection_scale_absolute(Inkscape::Selection *selection,
1287 double const x0, double const x1,
1288 double const y0, double const y1)
1289 {
1290 if (selection->isEmpty())
1291 return;
1293 boost::optional<NR::Rect> const bbox(selection->bounds());
1294 if ( !bbox || bbox->isEmpty() ) {
1295 return;
1296 }
1298 NR::translate const p2o(-bbox->min());
1300 NR::scale const newSize(x1 - x0,
1301 y1 - y0);
1302 NR::scale const scale( newSize / NR::scale(bbox->dimensions()) );
1303 NR::translate const o2n(x0, y0);
1304 NR::Matrix const final( p2o * scale * o2n );
1306 sp_selection_apply_affine(selection, final);
1307 }
1310 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1311 {
1312 if (selection->isEmpty())
1313 return;
1315 boost::optional<NR::Rect> const bbox(selection->bounds());
1317 if ( !bbox || bbox->isEmpty() ) {
1318 return;
1319 }
1321 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1322 if ( bbox->extent(NR::X) * scale[Geom::X] > 1e6 ||
1323 bbox->extent(NR::Y) * scale[Geom::Y] > 1e6 )
1324 {
1325 return;
1326 }
1328 Geom::Translate const n2d(-align);
1329 Geom::Translate const d2n(align);
1330 Geom::Matrix const final( n2d * scale * d2n );
1331 sp_selection_apply_affine(selection, final);
1332 }
1334 void
1335 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1336 {
1337 Geom::Translate const d2n(center);
1338 Geom::Translate const n2d(-center);
1339 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1340 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1341 sp_selection_apply_affine(selection, final);
1342 }
1344 void
1345 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1346 {
1347 Geom::Translate const d2n(align);
1348 Geom::Translate const n2d(-align);
1349 Geom::Matrix const skew(1, dy,
1350 dx, 1,
1351 0, 0);
1352 Geom::Matrix const final( n2d * skew * d2n );
1353 sp_selection_apply_affine(selection, final);
1354 }
1356 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1357 {
1358 sp_selection_apply_affine(selection, NR::Matrix(NR::translate(move)));
1359 }
1361 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1362 {
1363 sp_selection_apply_affine(selection, NR::Matrix(NR::translate(dx, dy)));
1364 }
1366 /**
1367 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1368 */
1369 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1370 {
1371 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1373 if (selection->isEmpty())
1374 return;
1376 GSList const *l = selection->itemList();
1377 Geom::Rotate const rot_90(NR::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1378 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1379 SPItem *item = SP_ITEM(l2->data);
1380 sp_item_rotate_rel(item, rot_90);
1381 }
1383 sp_document_done(sp_desktop_document(desktop),
1384 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1385 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1386 }
1388 void
1389 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1390 {
1391 if (selection->isEmpty())
1392 return;
1394 boost::optional<Geom::Point> center = selection->center();
1395 if (!center) {
1396 return;
1397 }
1399 sp_selection_rotate_relative(selection, *center, angle_degrees);
1401 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1402 ( ( angle_degrees > 0 )
1403 ? "selector:rotate:ccw"
1404 : "selector:rotate:cw" ),
1405 SP_VERB_CONTEXT_SELECT,
1406 _("Rotate"));
1407 }
1409 /**
1410 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1411 */
1412 void
1413 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1414 {
1415 if (selection->isEmpty())
1416 return;
1418 boost::optional<NR::Rect> const bbox(selection->bounds());
1419 boost::optional<Geom::Point> center = selection->center();
1421 if ( !bbox || !center ) {
1422 return;
1423 }
1425 gdouble const zoom = selection->desktop()->current_zoom();
1426 gdouble const zmove = angle / zoom;
1427 gdouble const r = NR::L2(bbox->cornerFarthestFrom(*center) - *center);
1429 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1431 sp_selection_rotate_relative(selection, *center, zangle);
1433 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1434 ( (angle > 0)
1435 ? "selector:rotate:ccw"
1436 : "selector:rotate:cw" ),
1437 SP_VERB_CONTEXT_SELECT,
1438 _("Rotate by pixels"));
1439 }
1441 void
1442 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1443 {
1444 if (selection->isEmpty())
1445 return;
1447 boost::optional<NR::Rect> const bbox(selection->bounds());
1448 if (!bbox) {
1449 return;
1450 }
1452 NR::Point const center(bbox->midpoint());
1454 // you can't scale "do nizhe pola" (below zero)
1455 double const max_len = bbox->maxExtent();
1456 if ( max_len + grow <= 1e-3 ) {
1457 return;
1458 }
1460 double const times = 1.0 + grow / max_len;
1461 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1463 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1464 ( (grow > 0)
1465 ? "selector:scale:larger"
1466 : "selector:scale:smaller" ),
1467 SP_VERB_CONTEXT_SELECT,
1468 _("Scale"));
1469 }
1471 void
1472 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1473 {
1474 sp_selection_scale(selection,
1475 grow_pixels / selection->desktop()->current_zoom());
1476 }
1478 void
1479 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1480 {
1481 if (selection->isEmpty())
1482 return;
1484 boost::optional<NR::Rect> sel_bbox = selection->bounds();
1486 if (!sel_bbox) {
1487 return;
1488 }
1490 NR::Point const center(sel_bbox->midpoint());
1491 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1492 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1493 _("Scale by whole factor"));
1494 }
1496 void
1497 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1498 {
1499 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1500 if (selection->isEmpty()) {
1501 return;
1502 }
1504 sp_selection_move_relative(selection, dx, dy);
1506 if (dx == 0) {
1507 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1508 _("Move vertically"));
1509 } else if (dy == 0) {
1510 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1511 _("Move horizontally"));
1512 } else {
1513 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1514 _("Move"));
1515 }
1516 }
1518 void
1519 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1520 {
1521 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1522 if (selection->isEmpty()) {
1523 return;
1524 }
1526 // same as sp_selection_move but divide deltas by zoom factor
1527 gdouble const zoom = desktop->current_zoom();
1528 gdouble const zdx = dx / zoom;
1529 gdouble const zdy = dy / zoom;
1530 sp_selection_move_relative(selection, zdx, zdy);
1532 if (dx == 0) {
1533 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1534 _("Move vertically by pixels"));
1535 } else if (dy == 0) {
1536 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1537 _("Move horizontally by pixels"));
1538 } else {
1539 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1540 _("Move"));
1541 }
1542 }
1544 namespace {
1546 template <typename D>
1547 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1548 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1550 template <typename D>
1551 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1552 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1554 struct Forward {
1555 typedef SPObject *Iterator;
1557 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1558 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1559 static void dispose(Iterator /*i*/) {}
1561 static SPObject *object(Iterator i) { return i; }
1562 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1563 };
1565 struct Reverse {
1566 typedef GSList *Iterator;
1568 static Iterator children(SPObject *o) {
1569 return make_list(o->firstChild(), NULL);
1570 }
1571 static Iterator siblings_after(SPObject *o) {
1572 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1573 }
1574 static void dispose(Iterator i) {
1575 g_slist_free(i);
1576 }
1578 static SPObject *object(Iterator i) {
1579 return reinterpret_cast<SPObject *>(i->data);
1580 }
1581 static Iterator next(Iterator i) { return i->next; }
1583 private:
1584 static GSList *make_list(SPObject *object, SPObject *limit) {
1585 GSList *list=NULL;
1586 while ( object != limit ) {
1587 list = g_slist_prepend(list, object);
1588 object = SP_OBJECT_NEXT(object);
1589 }
1590 return list;
1591 }
1592 };
1594 }
1596 void
1597 sp_selection_item_next(SPDesktop *desktop)
1598 {
1599 g_return_if_fail(desktop != NULL);
1600 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1602 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1603 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1604 bool onlyvisible = prefs->getBool("options.kbselection", "onlyvisible", true);
1605 bool onlysensitive = prefs->getBool("options.kbselection", "onlysensitive", true);
1607 SPObject *root;
1608 if (PREFS_SELECTION_ALL != inlayer) {
1609 root = selection->activeContext();
1610 } else {
1611 root = desktop->currentRoot();
1612 }
1614 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1616 if (item) {
1617 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1618 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1619 scroll_to_show_item(desktop, item);
1620 }
1621 }
1622 }
1624 void
1625 sp_selection_item_prev(SPDesktop *desktop)
1626 {
1627 SPDocument *document = sp_desktop_document(desktop);
1628 g_return_if_fail(document != NULL);
1629 g_return_if_fail(desktop != NULL);
1630 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1632 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1633 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("options.kbselection", "inlayer", PREFS_SELECTION_LAYER);
1634 bool onlyvisible = prefs->getBool("options.kbselection", "onlyvisible", true);
1635 bool onlysensitive = prefs->getBool("options.kbselection", "onlysensitive", true);
1637 SPObject *root;
1638 if (PREFS_SELECTION_ALL != inlayer) {
1639 root = selection->activeContext();
1640 } else {
1641 root = desktop->currentRoot();
1642 }
1644 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1646 if (item) {
1647 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1648 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1649 scroll_to_show_item(desktop, item);
1650 }
1651 }
1652 }
1654 void sp_selection_next_patheffect_param(SPDesktop * dt)
1655 {
1656 if (!dt) return;
1658 Inkscape::Selection *selection = sp_desktop_selection(dt);
1659 if ( selection && !selection->isEmpty() ) {
1660 SPItem *item = selection->singleItem();
1661 if ( item && SP_IS_SHAPE(item)) {
1662 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1663 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1664 } else {
1665 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1666 }
1667 }
1668 }
1669 }
1671 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1672 {
1673 if (!dt) return;
1675 Inkscape::Selection *selection = sp_desktop_selection(dt);
1676 if ( selection && !selection->isEmpty() ) {
1677 SPItem *item = selection->singleItem();
1678 if ( item ) {
1679 SPObject *obj = NULL;
1680 if (clip)
1681 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1682 else
1683 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1685 if (obj) {
1686 // obj is a group object, the children are the actual clippers
1687 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1688 if ( SP_IS_ITEM(child) ) {
1689 // If not already in nodecontext, goto it!
1690 if (!tools_isactive(dt, TOOLS_NODES)) {
1691 tools_switch(dt, TOOLS_NODES);
1692 }
1694 ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
1695 // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1696 shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1697 shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1698 Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1699 if (np) {
1700 // take colors from prefs (same as used in outline mode)
1701 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1702 np->helperpath_rgba = clip ?
1703 prefs->getInt("options.wireframecolors", "clips", 0x00ff00ff) :
1704 prefs->getInt("options.wireframecolors", "masks", 0x0000ffff);
1705 np->helperpath_width = 1.0;
1706 sp_nodepath_show_helperpath(np, true);
1707 }
1708 break; // break out of for loop after 1st encountered item
1709 }
1710 }
1711 } else if (clip) {
1712 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1713 } else {
1714 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1715 }
1716 }
1717 }
1718 }
1721 namespace {
1723 template <typename D>
1724 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1725 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1726 {
1727 SPObject *current=root;
1728 while (items) {
1729 SPItem *item=SP_ITEM(items->data);
1730 if ( root->isAncestorOf(item) &&
1731 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1732 {
1733 current = item;
1734 break;
1735 }
1736 items = items->next;
1737 }
1739 GSList *path=NULL;
1740 while ( current != root ) {
1741 path = g_slist_prepend(path, current);
1742 current = SP_OBJECT_PARENT(current);
1743 }
1745 SPItem *next;
1746 // first, try from the current object
1747 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1748 g_slist_free(path);
1750 if (!next) { // if we ran out of objects, start over at the root
1751 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1752 }
1754 return next;
1755 }
1757 template <typename D>
1758 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1759 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1760 {
1761 typename D::Iterator children;
1762 typename D::Iterator iter;
1764 SPItem *found=NULL;
1766 if (path) {
1767 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1768 g_assert(SP_OBJECT_PARENT(object) == root);
1769 if (desktop->isLayer(object)) {
1770 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1771 }
1772 iter = children = D::siblings_after(object);
1773 } else {
1774 iter = children = D::children(root);
1775 }
1777 while ( iter && !found ) {
1778 SPObject *object=D::object(iter);
1779 if (desktop->isLayer(object)) {
1780 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1781 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1782 }
1783 } else if ( SP_IS_ITEM(object) &&
1784 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1785 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1786 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1787 !desktop->isLayer(SP_ITEM(object)) )
1788 {
1789 found = SP_ITEM(object);
1790 }
1791 iter = D::next(iter);
1792 }
1794 D::dispose(children);
1796 return found;
1797 }
1799 }
1801 /**
1802 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1803 * \a item.
1804 */
1805 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1806 {
1807 Geom::Rect dbox = desktop->get_display_area();
1808 boost::optional<Geom::Rect> sbox = to_2geom(sp_item_bbox_desktop(item));
1810 if ( sbox && dbox.contains(*sbox) == false ) {
1811 Geom::Point const s_dt = sbox->midpoint();
1812 Geom::Point const s_w = desktop->d2w(s_dt);
1813 Geom::Point const d_dt = dbox.midpoint();
1814 Geom::Point const d_w = desktop->d2w(d_dt);
1815 Geom::Point const moved_w( d_w - s_w );
1816 gint const dx = (gint) moved_w[X];
1817 gint const dy = (gint) moved_w[Y];
1818 desktop->scroll_world(dx, dy);
1819 }
1820 }
1823 void
1824 sp_selection_clone(SPDesktop *desktop)
1825 {
1826 if (desktop == NULL)
1827 return;
1829 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1831 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1833 // check if something is selected
1834 if (selection->isEmpty()) {
1835 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1836 return;
1837 }
1839 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1841 selection->clear();
1843 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1844 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1846 GSList *newsel = NULL;
1848 while (reprs) {
1849 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1850 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1852 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1853 clone->setAttribute("x", "0", false);
1854 clone->setAttribute("y", "0", false);
1855 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1857 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1858 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1860 // add the new clone to the top of the original's parent
1861 parent->appendChild(clone);
1863 newsel = g_slist_prepend(newsel, clone);
1864 reprs = g_slist_remove(reprs, sel_repr);
1865 Inkscape::GC::release(clone);
1866 }
1868 // TRANSLATORS: only translate "string" in "context|string".
1869 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1870 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1871 Q_("action|Clone"));
1873 selection->setReprList(newsel);
1875 g_slist_free(newsel);
1876 }
1878 void
1879 sp_selection_relink(SPDesktop *desktop)
1880 {
1881 if (!desktop)
1882 return;
1884 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1886 if (selection->isEmpty()) {
1887 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1888 return;
1889 }
1891 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1892 const gchar *newid = cm->getFirstObjectID();
1893 if (!newid) {
1894 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1895 return;
1896 }
1897 gchar *newref = g_strdup_printf ("#%s", newid);
1899 // Get a copy of current selection.
1900 bool relinked = false;
1901 for (GSList *items = (GSList *) selection->itemList();
1902 items != NULL;
1903 items = items->next)
1904 {
1905 SPItem *item = (SPItem *) items->data;
1907 if (!SP_IS_USE(item))
1908 continue;
1910 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1911 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1912 relinked = true;
1913 }
1915 g_free(newref);
1917 if (!relinked) {
1918 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1919 } else {
1920 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1921 _("Relink clone"));
1922 }
1923 }
1926 void
1927 sp_selection_unlink(SPDesktop *desktop)
1928 {
1929 if (!desktop)
1930 return;
1932 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1934 if (selection->isEmpty()) {
1935 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1936 return;
1937 }
1939 // Get a copy of current selection.
1940 GSList *new_select = NULL;
1941 bool unlinked = false;
1942 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1943 items != NULL;
1944 items = items->next)
1945 {
1946 SPItem *item = (SPItem *) items->data;
1948 if (SP_IS_TEXT(item)) {
1949 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1951 if (tspan) {
1952 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1953 }
1955 // Set unlink to true, and fall into the next if which
1956 // will include this text item in the new selection
1957 unlinked = true;
1958 }
1960 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
1961 // keep the non-use item in the new selection
1962 new_select = g_slist_prepend(new_select, item);
1963 continue;
1964 }
1966 SPItem *unlink;
1967 if (SP_IS_USE(item)) {
1968 unlink = sp_use_unlink(SP_USE(item));
1969 } else /*if (SP_IS_TREF(use))*/ {
1970 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
1971 }
1973 unlinked = true;
1974 // Add ungrouped items to the new selection.
1975 new_select = g_slist_prepend(new_select, unlink);
1976 }
1978 if (new_select) { // set new selection
1979 selection->clear();
1980 selection->setList(new_select);
1981 g_slist_free(new_select);
1982 }
1983 if (!unlinked) {
1984 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1985 }
1987 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1988 _("Unlink clone"));
1989 }
1991 void
1992 sp_select_clone_original(SPDesktop *desktop)
1993 {
1994 if (desktop == NULL)
1995 return;
1997 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1999 SPItem *item = selection->singleItem();
2001 gchar const *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.");
2003 // Check if other than two objects are selected
2004 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2005 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2006 return;
2007 }
2009 SPItem *original = NULL;
2010 if (SP_IS_USE(item)) {
2011 original = sp_use_get_original (SP_USE(item));
2012 } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2013 original = sp_offset_get_source (SP_OFFSET(item));
2014 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2015 original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2016 } else if (SP_IS_FLOWTEXT(item)) {
2017 original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2018 } else { // it's an object that we don't know what to do with
2019 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2020 return;
2021 }
2023 if (!original) {
2024 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2025 return;
2026 }
2028 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2029 if (SP_IS_DEFS (o)) {
2030 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2031 return;
2032 }
2033 }
2035 if (original) {
2036 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2037 bool highlight = prefs->getBool("options.highlightoriginal", "value");
2038 if (highlight) {
2039 boost::optional<NR::Rect> a = item->getBounds(sp_item_i2d_affine(item));
2040 boost::optional<NR::Rect> b = original->getBounds(sp_item_i2d_affine(original));
2041 if ( a && b ) {
2042 // draw a flashing line between the objects
2043 SPCurve *curve = new SPCurve();
2044 curve->moveto(a->midpoint());
2045 curve->lineto(b->midpoint());
2047 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2048 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2049 sp_canvas_item_show(canvasitem);
2050 curve->unref();
2051 desktop->add_temporary_canvasitem (canvasitem, 1000);
2052 }
2053 }
2055 selection->clear();
2056 selection->set(original);
2057 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2058 scroll_to_show_item(desktop, original);
2059 }
2060 }
2061 }
2064 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2065 {
2066 if (desktop == NULL)
2067 return;
2069 SPDocument *doc = sp_desktop_document(desktop);
2070 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2072 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2074 // check if something is selected
2075 if (selection->isEmpty()) {
2076 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2077 return;
2078 }
2080 sp_document_ensure_up_to_date(doc);
2081 boost::optional<NR::Rect> r = selection->bounds();
2082 boost::optional<Geom::Point> c = selection->center();
2083 if ( !r || !c || r->isEmpty() ) {
2084 return;
2085 }
2087 // calculate the transform to be applied to objects to move them to 0,0
2088 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2089 move_p[Geom::Y] = -move_p[Geom::Y];
2090 Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2092 GSList *items = g_slist_copy((GSList *) selection->itemList());
2094 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2096 // bottommost object, after sorting
2097 SPObject *parent = SP_OBJECT_PARENT (items->data);
2099 Geom::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2101 // remember the position of the first item
2102 gint pos = SP_OBJECT_REPR (items->data)->position();
2103 (void)pos; // TODO check why this was remembered
2105 // create a list of duplicates
2106 GSList *repr_copies = NULL;
2107 for (GSList *i = items; i != NULL; i = i->next) {
2108 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2109 repr_copies = g_slist_prepend (repr_copies, dup);
2110 }
2112 NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2114 if (apply) {
2115 // delete objects so that their clones don't get alerted; this object will be restored shortly
2116 for (GSList *i = items; i != NULL; i = i->next) {
2117 SPObject *item = SP_OBJECT (i->data);
2118 item->deleteObject (false);
2119 }
2120 }
2122 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2123 // without disturbing clones.
2124 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2125 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2126 int saved_compensation = prefs->getInt("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2127 prefs->setInt("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2129 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2130 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2131 Geom::Point(r->min()[Geom::X],
2132 r->max()[Geom::Y]))))
2133 * parent_transform.inverse() ),
2134 parent_transform * move);
2135 (void)mark_id;
2137 // restore compensation setting
2138 prefs->setInt("options.clonecompensation", "value", saved_compensation);
2141 g_slist_free (items);
2143 sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2144 _("Objects to marker"));
2145 }
2147 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2148 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2149 for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2150 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2151 }
2152 } else {
2153 sp_item_convert_item_to_guides(item);
2155 if (deleteitem) {
2156 SP_OBJECT(item)->deleteObject(true);
2157 }
2158 }
2159 }
2161 void sp_selection_to_guides(SPDesktop *desktop)
2162 {
2163 if (desktop == NULL)
2164 return;
2166 SPDocument *doc = sp_desktop_document(desktop);
2167 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2168 // we need to copy the list because it gets reset when objects are deleted
2169 GSList *items = g_slist_copy((GSList *) selection->itemList());
2171 if (!items) {
2172 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2173 return;
2174 }
2176 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2177 bool deleteitem = !prefs->getBool("tools", "cvg_keep_objects", 0);
2178 bool wholegroups = prefs->getBool("tools", "cvg_convert_whole_groups", 0);
2180 for (GSList const *i = items; i != NULL; i = i->next) {
2181 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2182 }
2184 sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2185 }
2187 void
2188 sp_selection_tile(SPDesktop *desktop, bool apply)
2189 {
2190 if (desktop == NULL)
2191 return;
2193 SPDocument *doc = sp_desktop_document(desktop);
2194 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2196 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2198 // check if something is selected
2199 if (selection->isEmpty()) {
2200 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2201 return;
2202 }
2204 sp_document_ensure_up_to_date(doc);
2205 boost::optional<NR::Rect> r = selection->bounds();
2206 if ( !r || r->isEmpty() ) {
2207 return;
2208 }
2210 // calculate the transform to be applied to objects to move them to 0,0
2211 NR::Point move_p = NR::Point(0, sp_document_height(doc)) - (r->min() + NR::Point (0, r->extent(NR::Y)));
2212 move_p[NR::Y] = -move_p[NR::Y];
2213 NR::Matrix move = NR::Matrix (NR::translate (move_p));
2215 GSList *items = g_slist_copy((GSList *) selection->itemList());
2217 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2219 // bottommost object, after sorting
2220 SPObject *parent = SP_OBJECT_PARENT (items->data);
2222 NR::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2224 // remember the position of the first item
2225 gint pos = SP_OBJECT_REPR (items->data)->position();
2227 // create a list of duplicates
2228 GSList *repr_copies = NULL;
2229 for (GSList *i = items; i != NULL; i = i->next) {
2230 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2231 repr_copies = g_slist_prepend (repr_copies, dup);
2232 }
2233 // restore the z-order after prepends
2234 repr_copies = g_slist_reverse (repr_copies);
2236 NR::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2238 if (apply) {
2239 // delete objects so that their clones don't get alerted; this object will be restored shortly
2240 for (GSList *i = items; i != NULL; i = i->next) {
2241 SPObject *item = SP_OBJECT (i->data);
2242 item->deleteObject (false);
2243 }
2244 }
2246 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2247 // without disturbing clones.
2248 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2249 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2250 int saved_compensation = prefs->getInt("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2251 prefs->setInt("options.clonecompensation", "value", SP_CLONE_COMPENSATION_UNMOVED);
2253 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2254 ( NR::Matrix(NR::translate(desktop->dt2doc(NR::Point(r->min()[NR::X],
2255 r->max()[NR::Y]))))
2256 * parent_transform.inverse() ),
2257 parent_transform * move);
2259 // restore compensation setting
2260 prefs->setInt("options.clonecompensation", "value", saved_compensation);
2262 if (apply) {
2263 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2264 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2266 NR::Point min = bounds.min() * parent_transform.inverse();
2267 NR::Point max = bounds.max() * parent_transform.inverse();
2269 sp_repr_set_svg_double(rect, "width", max[NR::X] - min[NR::X]);
2270 sp_repr_set_svg_double(rect, "height", max[NR::Y] - min[NR::Y]);
2271 sp_repr_set_svg_double(rect, "x", min[NR::X]);
2272 sp_repr_set_svg_double(rect, "y", min[NR::Y]);
2274 // restore parent and position
2275 SP_OBJECT_REPR (parent)->appendChild(rect);
2276 rect->setPosition(pos > 0 ? pos : 0);
2277 SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2279 Inkscape::GC::release(rect);
2281 selection->clear();
2282 selection->set(rectangle);
2283 }
2285 g_slist_free (items);
2287 sp_document_done (doc, SP_VERB_EDIT_TILE,
2288 _("Objects to pattern"));
2289 }
2291 void
2292 sp_selection_untile(SPDesktop *desktop)
2293 {
2294 if (desktop == NULL)
2295 return;
2297 SPDocument *doc = sp_desktop_document(desktop);
2298 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2300 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2302 // check if something is selected
2303 if (selection->isEmpty()) {
2304 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2305 return;
2306 }
2308 GSList *new_select = NULL;
2310 bool did = false;
2312 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2313 items != NULL;
2314 items = items->next) {
2316 SPItem *item = (SPItem *) items->data;
2318 SPStyle *style = SP_OBJECT_STYLE (item);
2320 if (!style || !style->fill.isPaintserver())
2321 continue;
2323 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2325 if (!SP_IS_PATTERN(server))
2326 continue;
2328 did = true;
2330 SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2332 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform (SP_PATTERN (server)));
2333 pat_transform *= item->transform;
2335 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2336 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2337 SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2339 // FIXME: relink clones to the new canvas objects
2340 // use SPObject::setid when mental finishes it to steal ids of
2342 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2343 sp_document_ensure_up_to_date (doc);
2345 Geom::Matrix transform( i->transform * pat_transform );
2346 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2348 new_select = g_slist_prepend(new_select, i);
2349 }
2351 SPCSSAttr *css = sp_repr_css_attr_new ();
2352 sp_repr_css_set_property (css, "fill", "none");
2353 sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2354 }
2356 if (!did) {
2357 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2358 } else {
2359 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2360 _("Pattern to objects"));
2361 selection->setList(new_select);
2362 }
2363 }
2365 void
2366 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2367 {
2368 if (selection->isEmpty()) {
2369 return;
2370 }
2372 GSList const *reprlst = selection->reprList();
2373 bool filename_search = TRUE;
2374 bool xdpi_search = TRUE;
2375 bool ydpi_search = TRUE;
2377 for(; reprlst != NULL &&
2378 filename_search &&
2379 xdpi_search &&
2380 ydpi_search;
2381 reprlst = reprlst->next) {
2382 gchar const *dpi_string;
2383 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2385 if (filename_search) {
2386 *filename = repr->attribute("inkscape:export-filename");
2387 if (*filename != NULL)
2388 filename_search = FALSE;
2389 }
2391 if (xdpi_search) {
2392 dpi_string = NULL;
2393 dpi_string = repr->attribute("inkscape:export-xdpi");
2394 if (dpi_string != NULL) {
2395 *xdpi = atof(dpi_string);
2396 xdpi_search = FALSE;
2397 }
2398 }
2400 if (ydpi_search) {
2401 dpi_string = NULL;
2402 dpi_string = repr->attribute("inkscape:export-ydpi");
2403 if (dpi_string != NULL) {
2404 *ydpi = atof(dpi_string);
2405 ydpi_search = FALSE;
2406 }
2407 }
2408 }
2409 }
2411 void
2412 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2413 {
2414 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2415 gchar const *dpi_string;
2417 *filename = repr->attribute("inkscape:export-filename");
2419 dpi_string = NULL;
2420 dpi_string = repr->attribute("inkscape:export-xdpi");
2421 if (dpi_string != NULL) {
2422 *xdpi = atof(dpi_string);
2423 }
2425 dpi_string = NULL;
2426 dpi_string = repr->attribute("inkscape:export-ydpi");
2427 if (dpi_string != NULL) {
2428 *ydpi = atof(dpi_string);
2429 }
2430 }
2432 void
2433 sp_selection_create_bitmap_copy (SPDesktop *desktop)
2434 {
2435 if (desktop == NULL)
2436 return;
2438 SPDocument *document = sp_desktop_document(desktop);
2439 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2441 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2443 // check if something is selected
2444 if (selection->isEmpty()) {
2445 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2446 return;
2447 }
2449 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2450 // set "busy" cursor
2451 desktop->setWaitingCursor();
2453 // Get the bounding box of the selection
2454 NRRect bbox;
2455 sp_document_ensure_up_to_date (document);
2456 selection->bounds(&bbox);
2457 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2458 desktop->clearWaitingCursor();
2459 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2460 }
2462 // List of the items to show; all others will be hidden
2463 GSList *items = g_slist_copy ((GSList *) selection->itemList());
2465 // Sort items so that the topmost comes last
2466 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2468 // Generate a random value from the current time (you may create bitmap from the same object(s)
2469 // multiple times, and this is done so that they don't clash)
2470 GTimeVal cu;
2471 g_get_current_time (&cu);
2472 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2474 // Create the filename
2475 gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2476 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2477 // digits, and a few other chars, with "_"
2478 filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2479 // Build the complete path by adding document->base if set
2480 gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2482 //g_print ("%s\n", filepath);
2484 // Remember parent and z-order of the topmost one
2485 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2486 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2487 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2489 // Calculate resolution
2490 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2491 double res;
2492 int const prefs_res = prefs->getInt("options.createbitmap", "resolution", 0);
2493 int const prefs_min = prefs->getInt("options.createbitmap", "minsize", 0);
2494 if (0 < prefs_res) {
2495 // If it's given explicitly in prefs, take it
2496 res = prefs_res;
2497 } else if (0 < prefs_min) {
2498 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2499 res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2500 } else {
2501 float hint_xdpi = 0, hint_ydpi = 0;
2502 char const *hint_filename;
2503 // take resolution hint from the selected objects
2504 sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2505 if (hint_xdpi != 0) {
2506 res = hint_xdpi;
2507 } else {
2508 // take resolution hint from the document
2509 sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2510 if (hint_xdpi != 0) {
2511 res = hint_xdpi;
2512 } else {
2513 // if all else fails, take the default 90 dpi
2514 res = PX_PER_IN;
2515 }
2516 }
2517 }
2519 // The width and height of the bitmap in pixels
2520 unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2521 unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2523 // Find out if we have to run an external filter
2524 gchar const *run = NULL;
2525 Glib::ustring filter = prefs->getString("options.createbitmap", "filter");
2526 if (!filter.empty()) {
2527 // filter command is given;
2528 // see if we have a parameter to pass to it
2529 Glib::ustring param1 = prefs->getString("options.createbitmap", "filter_param1");
2530 if (!param1.empty()) {
2531 if (param1[param1.length() - 1] == '%') {
2532 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2533 gchar p1[256];
2534 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1.data(), NULL) * MAX(width, height) / 100));
2535 // the first param is always the image filename, the second is param1
2536 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, p1);
2537 } else {
2538 // otherwise pass the param1 unchanged
2539 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, param1.data());
2540 }
2541 } else {
2542 // run without extra parameter
2543 run = g_strdup_printf ("%s \"%s\"", filter.data(), filepath);
2544 }
2545 }
2547 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2548 NR::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2549 NR::Matrix t;
2551 double shift_x = bbox.x0;
2552 double shift_y = bbox.y1;
2553 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2554 shift_x = round (shift_x);
2555 shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2556 }
2557 t = NR::scale(1, -1) * NR::translate (shift_x, shift_y) * eek.inverse();
2559 // Do the export
2560 sp_export_png_file(document, filepath,
2561 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2562 width, height, res, res,
2563 (guint32) 0xffffff00,
2564 NULL, NULL,
2565 true, /*bool force_overwrite,*/
2566 items);
2568 g_slist_free (items);
2570 // Run filter, if any
2571 if (run) {
2572 g_print ("Running external filter: %s\n", run);
2573 int retval;
2574 retval = system (run);
2575 }
2577 // Import the image back
2578 GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2579 if (pb) {
2580 // Create the repr for the image
2581 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2582 repr->setAttribute("xlink:href", filename);
2583 repr->setAttribute("sodipodi:absref", filepath);
2584 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2585 sp_repr_set_svg_double(repr, "width", width);
2586 sp_repr_set_svg_double(repr, "height", height);
2587 } else {
2588 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2589 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2590 }
2592 // Write transform
2593 gchar *c=sp_svg_transform_write(t);
2594 repr->setAttribute("transform", c);
2595 g_free(c);
2597 // add the new repr to the parent
2598 parent->appendChild(repr);
2600 // move to the saved position
2601 repr->setPosition(pos > 0 ? pos + 1 : 1);
2603 // Set selection to the new image
2604 selection->clear();
2605 selection->add(repr);
2607 // Clean up
2608 Inkscape::GC::release(repr);
2609 gdk_pixbuf_unref (pb);
2611 // Complete undoable transaction
2612 sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2613 _("Create bitmap"));
2614 }
2616 desktop->clearWaitingCursor();
2618 g_free (filename);
2619 g_free (filepath);
2620 }
2622 /**
2623 * \brief Creates a mask or clipPath from selection
2624 * Two different modes:
2625 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2626 * and is applied to current layer
2627 * otherwise, topmost object is used as mask for other objects
2628 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2629 *
2630 */
2631 void
2632 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2633 {
2634 if (desktop == NULL)
2635 return;
2637 SPDocument *doc = sp_desktop_document(desktop);
2638 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2640 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2642 // check if something is selected
2643 bool is_empty = selection->isEmpty();
2644 if ( apply_to_layer && is_empty) {
2645 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2646 return;
2647 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2648 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2649 return;
2650 }
2652 // FIXME: temporary patch to prevent crash!
2653 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2654 bool clone_with_original = selection_contains_both_clone_and_original (selection);
2655 if (clone_with_original) {
2656 return; // in this version, you cannot clip/mask an object with its own clone
2657 }
2658 // /END FIXME
2660 sp_document_ensure_up_to_date(doc);
2662 GSList *items = g_slist_copy((GSList *) selection->itemList());
2664 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2666 // create a list of duplicates
2667 GSList *mask_items = NULL;
2668 GSList *apply_to_items = NULL;
2669 GSList *items_to_delete = NULL;
2670 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2671 bool topmost = prefs->getBool("options.maskobject", "topmost", true);
2672 bool remove_original = prefs->getBool("options.maskobject", "remove", true);
2674 if (apply_to_layer) {
2675 // all selected items are used for mask, which is applied to a layer
2676 apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2678 for (GSList *i = items; i != NULL; i = i->next) {
2679 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2680 mask_items = g_slist_prepend (mask_items, dup);
2682 if (remove_original) {
2683 SPObject *item = SP_OBJECT (i->data);
2684 items_to_delete = g_slist_prepend (items_to_delete, item);
2685 }
2686 }
2687 } else if (!topmost) {
2688 // topmost item is used as a mask, which is applied to other items in a selection
2689 GSList *i = items;
2690 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2691 mask_items = g_slist_prepend (mask_items, dup);
2693 if (remove_original) {
2694 SPObject *item = SP_OBJECT (i->data);
2695 items_to_delete = g_slist_prepend (items_to_delete, item);
2696 }
2698 for (i = i->next; i != NULL; i = i->next) {
2699 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2700 }
2701 } else {
2702 GSList *i = NULL;
2703 for (i = items; NULL != i->next; i = i->next) {
2704 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2705 }
2707 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2708 mask_items = g_slist_prepend (mask_items, dup);
2710 if (remove_original) {
2711 SPObject *item = SP_OBJECT (i->data);
2712 items_to_delete = g_slist_prepend (items_to_delete, item);
2713 }
2714 }
2716 g_slist_free (items);
2717 items = NULL;
2719 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2720 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2721 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2722 // inverted object transform should be applied to a mask object,
2723 // as mask is calculated in user space (after applying transform)
2724 NR::Matrix maskTransform (item->transform.inverse());
2726 GSList *mask_items_dup = NULL;
2727 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2728 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2729 mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2730 }
2732 gchar const *mask_id = NULL;
2733 if (apply_clip_path) {
2734 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2735 } else {
2736 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2737 }
2739 g_slist_free (mask_items_dup);
2740 mask_items_dup = NULL;
2742 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2743 }
2745 g_slist_free (mask_items);
2746 g_slist_free (apply_to_items);
2748 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2749 SPObject *item = SP_OBJECT (i->data);
2750 item->deleteObject (false);
2751 }
2752 g_slist_free (items_to_delete);
2754 if (apply_clip_path)
2755 sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2756 else
2757 sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2758 }
2760 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2761 if (desktop == NULL)
2762 return;
2764 SPDocument *doc = sp_desktop_document(desktop);
2765 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2766 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2768 // check if something is selected
2769 if (selection->isEmpty()) {
2770 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2771 return;
2772 }
2774 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2775 bool remove_original = prefs->getBool("options.maskobject", "remove", true);
2776 sp_document_ensure_up_to_date(doc);
2778 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2779 std::map<SPObject*,SPItem*> referenced_objects;
2780 // SPObject* refers to a group containing the clipped path or mask itself,
2781 // whereas SPItem* refers to the item being clipped or masked
2782 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2783 if (remove_original) {
2784 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2785 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2786 Inkscape::URIReference *uri_ref = NULL;
2788 if (apply_clip_path) {
2789 uri_ref = item->clip_ref;
2790 } else {
2791 uri_ref = item->mask_ref;
2792 }
2794 // collect distinct mask object (and associate with item to apply transform)
2795 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2796 referenced_objects[uri_ref->getObject()] = item;
2797 }
2798 }
2800 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2801 }
2803 // restore mask objects into a document
2804 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2805 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2806 GSList *items_to_move = NULL;
2807 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2808 // Collect all clipped paths and masks within a single group
2809 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2810 items_to_move = g_slist_prepend (items_to_move, copy);
2811 }
2813 if (!obj->isReferenced()) {
2814 // delete from defs if no other object references this mask
2815 obj->deleteObject(false);
2816 }
2818 // remember parent and position of the item to which the clippath/mask was applied
2819 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2820 gint pos = SP_OBJECT_REPR((*it).second)->position();
2822 // Iterate through all clipped paths / masks
2823 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2824 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2826 // insert into parent, restore pos
2827 parent->appendChild(repr);
2828 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2830 SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2831 selection->add(repr);
2833 // transform mask, so it is moved the same spot where mask was applied
2834 NR::Matrix transform (mask_item->transform);
2835 transform *= (*it).second->transform;
2836 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2837 }
2839 g_slist_free (items_to_move);
2840 }
2842 if (apply_clip_path)
2843 sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2844 else
2845 sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2846 }
2848 /**
2849 * Returns true if an undoable change should be recorded.
2850 */
2851 bool
2852 fit_canvas_to_selection(SPDesktop *desktop)
2853 {
2854 g_return_val_if_fail(desktop != NULL, false);
2855 SPDocument *doc = sp_desktop_document(desktop);
2857 g_return_val_if_fail(doc != NULL, false);
2858 g_return_val_if_fail(desktop->selection != NULL, false);
2860 if (desktop->selection->isEmpty()) {
2861 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2862 return false;
2863 }
2864 boost::optional<Geom::Rect> const bbox(to_2geom(desktop->selection->bounds()));
2865 if (bbox && !bbox->isEmpty()) {
2866 doc->fitToRect(*bbox);
2867 return true;
2868 } else {
2869 return false;
2870 }
2871 }
2873 /**
2874 * Fit canvas to the bounding box of the selection, as an undoable action.
2875 */
2876 void
2877 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2878 {
2879 if (fit_canvas_to_selection(desktop)) {
2880 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2881 _("Fit Page to Selection"));
2882 }
2883 }
2885 bool
2886 fit_canvas_to_drawing(SPDocument *doc)
2887 {
2888 g_return_val_if_fail(doc != NULL, false);
2890 sp_document_ensure_up_to_date(doc);
2891 SPItem const *const root = SP_ITEM(doc->root);
2892 boost::optional<Geom::Rect> const bbox(to_2geom(root->getBounds(sp_item_i2r_affine(root))));
2893 if (bbox && !bbox->isEmpty()) {
2894 doc->fitToRect(*bbox);
2895 return true;
2896 } else {
2897 return false;
2898 }
2899 }
2901 void
2902 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2903 {
2904 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2905 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2906 _("Fit Page to Drawing"));
2907 }
2908 }
2910 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2911 g_return_if_fail(desktop != NULL);
2912 SPDocument *doc = sp_desktop_document(desktop);
2914 g_return_if_fail(doc != NULL);
2915 g_return_if_fail(desktop->selection != NULL);
2917 bool const changed = ( desktop->selection->isEmpty()
2918 ? fit_canvas_to_drawing(doc)
2919 : fit_canvas_to_selection(desktop) );
2920 if (changed) {
2921 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2922 _("Fit Page to Selection or Drawing"));
2923 }
2924 };
2926 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2927 // don't operate on layers
2928 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2929 f(SP_ITEM(root), desktop);
2930 }
2931 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2932 //don't recurse into locked layers
2933 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2934 itemtree_map(f, iter, desktop);
2935 }
2936 }
2937 }
2939 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2940 if (item->isLocked()) {
2941 item->setLocked(FALSE);
2942 }
2943 }
2945 static void unhide(SPItem *item, SPDesktop *desktop) {
2946 if (desktop->itemIsHidden(item)) {
2947 item->setExplicitlyHidden(FALSE);
2948 }
2949 }
2951 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2952 if (!dt) return;
2954 SPObject *root;
2955 if (layer_only) {
2956 root = dt->currentLayer();
2957 } else {
2958 root = dt->currentRoot();
2959 }
2961 itemtree_map(f, root, dt);
2962 }
2964 void unlock_all(SPDesktop *dt) {
2965 process_all(&unlock, dt, true);
2966 }
2968 void unlock_all_in_all_layers(SPDesktop *dt) {
2969 process_all(&unlock, dt, false);
2970 }
2972 void unhide_all(SPDesktop *dt) {
2973 process_all(&unhide, dt, true);
2974 }
2976 void unhide_all_in_all_layers(SPDesktop *dt) {
2977 process_all(&unhide, dt, false);
2978 }
2981 /*
2982 Local Variables:
2983 mode:c++
2984 c-file-style:"stroustrup"
2985 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2986 indent-tabs-mode:nil
2987 fill-column:99
2988 End:
2989 */
2990 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :