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 "dir-util.h"
31 #include "selection.h"
32 #include "tools-switch.h"
33 #include "desktop-handles.h"
34 #include "message-stack.h"
35 #include "sp-item-transform.h"
36 #include "marker.h"
37 #include "sp-use.h"
38 #include "sp-textpath.h"
39 #include "sp-tspan.h"
40 #include "sp-tref.h"
41 #include "sp-flowtext.h"
42 #include "sp-flowregion.h"
43 #include "text-editing.h"
44 #include "text-context.h"
45 #include "connector-context.h"
46 #include "sp-path.h"
47 #include "sp-conn-end.h"
48 #include "dropper-context.h"
49 #include <glibmm/i18n.h>
50 #include "libnr/nr-matrix-rotate-ops.h"
51 #include "libnr/nr-matrix-translate-ops.h"
52 #include "libnr/nr-scale-ops.h"
53 #include <libnr/nr-matrix-ops.h>
54 #include <2geom/transforms.h>
55 #include "xml/repr.h"
56 #include "xml/rebase-hrefs.h"
57 #include "style.h"
58 #include "document-private.h"
59 #include "sp-gradient.h"
60 #include "sp-gradient-reference.h"
61 #include "sp-linear-gradient-fns.h"
62 #include "sp-pattern.h"
63 #include "sp-radial-gradient-fns.h"
64 #include "sp-namedview.h"
65 #include "preferences.h"
66 #include "sp-offset.h"
67 #include "sp-clippath.h"
68 #include "sp-mask.h"
69 #include "file.h"
70 #include "helper/png-write.h"
71 #include "layer-fns.h"
72 #include "context-fns.h"
73 #include <map>
74 #include <cstring>
75 #include <string>
76 #include "helper/units.h"
77 #include "sp-item.h"
78 #include "box3d.h"
79 #include "persp3d.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"
88 #include "inkscape-private.h"
90 // For clippath editing
91 #include "tools-switch.h"
92 #include "ui/tool/node-tool.h"
94 #include "ui/clipboard.h"
96 using Geom::X;
97 using Geom::Y;
99 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
100 because the layer manipulation code uses them. It should be rewritten specifically
101 for that purpose. */
103 /**
104 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
105 * then prepends the copy to 'clip'.
106 */
107 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
108 {
109 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
111 // copy complete inherited style
112 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
113 sp_repr_css_set(copy, css, "style");
114 sp_repr_css_attr_unref(css);
116 // write the complete accumulated transform passed to us
117 // (we're dealing with unattached repr, so we write to its attr
118 // instead of using sp_item_set_transform)
119 gchar *affinestr=sp_svg_transform_write(full_t);
120 copy->setAttribute("transform", affinestr);
121 g_free(affinestr);
123 *clip = g_slist_prepend(*clip, copy);
124 }
126 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
127 {
128 // Sort items:
129 GSList *sorted_items = g_slist_copy((GSList *) items);
130 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
132 // Copy item reprs:
133 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
134 sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
135 }
137 *clip = g_slist_reverse(*clip);
138 g_slist_free((GSList *) sorted_items);
139 }
141 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
142 {
143 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
145 GSList *copied = NULL;
146 // add objects to document
147 for (GSList *l = *clip; l != NULL; l = l->next) {
148 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
149 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
151 // premultiply the item transform by the accumulated parent transform in the paste layer
152 Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
153 if (!local.isIdentity()) {
154 gchar const *t_str = copy->attribute("transform");
155 Geom::Matrix item_t(Geom::identity());
156 if (t_str)
157 sp_svg_transform_read(t_str, &item_t);
158 item_t *= local.inverse();
159 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
160 gchar *affinestr=sp_svg_transform_write(item_t);
161 copy->setAttribute("transform", affinestr);
162 g_free(affinestr);
163 }
165 parent->appendChildRepr(copy);
166 copied = g_slist_prepend(copied, copy);
167 Inkscape::GC::release(copy);
168 }
169 return copied;
170 }
172 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
173 {
174 for (GSList const *i = items ; i ; i = i->next ) {
175 sp_object_ref((SPObject *)i->data, NULL);
176 }
177 for (GSList const *i = items; i != NULL; i = i->next) {
178 SPItem *item = (SPItem *) i->data;
179 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
180 sp_object_unref((SPObject *)item, NULL);
181 }
182 }
185 void sp_selection_delete(SPDesktop *desktop)
186 {
187 if (desktop == NULL) {
188 return;
189 }
191 if (tools_isactive(desktop, TOOLS_TEXT))
192 if (sp_text_delete_selection(desktop->event_context)) {
193 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
194 _("Delete text"));
195 return;
196 }
198 Inkscape::Selection *selection = sp_desktop_selection(desktop);
200 // check if something is selected
201 if (selection->isEmpty()) {
202 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
203 return;
204 }
206 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
207 selection->clear();
208 sp_selection_delete_impl(selected);
209 g_slist_free((GSList *) selected);
211 /* a tool may have set up private information in it's selection context
212 * that depends on desktop items. I think the only sane way to deal with
213 * this currently is to reset the current tool, which will reset it's
214 * associated selection context. For example: deleting an object
215 * while moving it around the canvas.
216 */
217 tools_switch( desktop, tools_active( desktop ) );
219 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
220 _("Delete"));
221 }
223 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
224 {
225 if (!obj)
226 return;
228 ids.push_back(SP_OBJECT_ID(obj));
230 if (SP_IS_GROUP(obj)) {
231 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
232 add_ids_recursive(ids, child);
233 }
234 }
235 }
237 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
238 {
239 if (desktop == NULL)
240 return;
242 SPDocument *doc = desktop->doc();
243 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
244 Inkscape::Selection *selection = sp_desktop_selection(desktop);
246 // check if something is selected
247 if (selection->isEmpty()) {
248 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
249 return;
250 }
252 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
254 selection->clear();
256 // sorting items from different parents sorts each parent's subset without possibly mixing
257 // them, just what we need
258 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
260 GSList *newsel = NULL;
262 std::vector<const gchar *> old_ids;
263 std::vector<const gchar *> new_ids;
264 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
265 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
267 while (reprs) {
268 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
269 Inkscape::XML::Node *parent = old_repr->parent();
270 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
272 parent->appendChild(copy);
274 if (relink_clones) {
275 SPObject *old_obj = doc->getObjectByRepr(old_repr);
276 SPObject *new_obj = doc->getObjectByRepr(copy);
277 add_ids_recursive(old_ids, old_obj);
278 add_ids_recursive(new_ids, new_obj);
279 }
281 newsel = g_slist_prepend(newsel, copy);
282 reprs = g_slist_remove(reprs, reprs->data);
283 Inkscape::GC::release(copy);
284 }
286 if (relink_clones) {
288 g_assert(old_ids.size() == new_ids.size());
290 for (unsigned int i = 0; i < old_ids.size(); i++) {
291 const gchar *id = old_ids[i];
292 SPObject *old_clone = doc->getObjectById(id);
293 if (SP_IS_USE(old_clone)) {
294 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
295 if (!orig) // orphaned
296 continue;
297 for (unsigned int j = 0; j < old_ids.size(); j++) {
298 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
299 // we have both orig and clone in selection, relink
300 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
301 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
302 SPObject *new_clone = doc->getObjectById(new_ids[i]);
303 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
304 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
305 g_free(newref);
306 }
307 }
308 }
309 }
310 }
313 if ( !suppressDone ) {
314 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
315 _("Duplicate"));
316 }
318 selection->setReprList(newsel);
320 g_slist_free(newsel);
321 }
323 void sp_edit_clear_all(SPDesktop *dt)
324 {
325 if (!dt)
326 return;
328 SPDocument *doc = sp_desktop_document(dt);
329 sp_desktop_selection(dt)->clear();
331 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
332 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
334 while (items) {
335 SP_OBJECT(items->data)->deleteObject();
336 items = g_slist_remove(items, items->data);
337 }
339 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
340 _("Delete all"));
341 }
343 GSList *
344 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
345 {
346 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
347 if (SP_IS_ITEM(child) &&
348 !desktop->isLayer(SP_ITEM(child)) &&
349 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
350 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
351 (!exclude || !g_slist_find((GSList *) exclude, child))
352 )
353 {
354 list = g_slist_prepend(list, SP_ITEM(child));
355 }
357 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
358 list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
359 }
360 }
362 return list;
363 }
365 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
366 {
367 if (!dt)
368 return;
370 Inkscape::Selection *selection = sp_desktop_selection(dt);
372 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
374 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
375 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
376 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
377 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
379 GSList *items = NULL;
381 GSList const *exclude = NULL;
382 if (invert) {
383 exclude = selection->itemList();
384 }
386 if (force_all_layers)
387 inlayer = PREFS_SELECTION_ALL;
389 switch (inlayer) {
390 case PREFS_SELECTION_LAYER: {
391 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
392 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
393 return;
395 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
397 for (GSList *i = all_items; i; i = i->next) {
398 SPItem *item = SP_ITEM(i->data);
400 if (item && (!onlysensitive || !item->isLocked())) {
401 if (!onlyvisible || !dt->itemIsHidden(item)) {
402 if (!dt->isLayer(item)) {
403 if (!invert || !g_slist_find((GSList *) exclude, item)) {
404 items = g_slist_prepend(items, item); // leave it in the list
405 }
406 }
407 }
408 }
409 }
411 g_slist_free(all_items);
412 break;
413 }
414 case PREFS_SELECTION_LAYER_RECURSIVE: {
415 items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
416 break;
417 }
418 default: {
419 items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
420 break;
421 }
422 }
424 selection->setList(items);
426 if (items) {
427 g_slist_free(items);
428 }
429 }
431 void sp_edit_select_all(SPDesktop *desktop)
432 {
433 sp_edit_select_all_full(desktop, false, false);
434 }
436 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
437 {
438 sp_edit_select_all_full(desktop, true, false);
439 }
441 void sp_edit_invert(SPDesktop *desktop)
442 {
443 sp_edit_select_all_full(desktop, false, true);
444 }
446 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
447 {
448 sp_edit_select_all_full(desktop, true, true);
449 }
451 void sp_selection_group(SPDesktop *desktop)
452 {
453 if (desktop == NULL)
454 return;
456 SPDocument *doc = sp_desktop_document(desktop);
457 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
459 Inkscape::Selection *selection = sp_desktop_selection(desktop);
461 // Check if something is selected.
462 if (selection->isEmpty()) {
463 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
464 return;
465 }
467 GSList const *l = (GSList *) selection->reprList();
469 GSList *p = g_slist_copy((GSList *) l);
471 selection->clear();
473 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
475 // Remember the position and parent of the topmost object.
476 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
477 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
479 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
481 while (p) {
482 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
484 if (current->parent() == topmost_parent) {
485 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
486 sp_repr_unparent(current);
487 group->appendChild(spnew);
488 Inkscape::GC::release(spnew);
489 topmost --; // only reduce count for those items deleted from topmost_parent
490 } else { // move it to topmost_parent first
491 GSList *temp_clip = NULL;
493 // At this point, current may already have no item, due to its being a clone whose original is already moved away
494 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
495 gchar const *t_str = current->attribute("transform");
496 Geom::Matrix item_t(Geom::identity());
497 if (t_str)
498 sp_svg_transform_read(t_str, &item_t);
499 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
500 // FIXME: when moving both clone and original from a transformed group (either by
501 // grouping into another parent, or by cut/paste) the transform from the original's
502 // parent becomes embedded into original itself, and this affects its clones. Fix
503 // this by remembering the transform diffs we write to each item into an array and
504 // then, if this is clone, looking up its original in that array and pre-multiplying
505 // it by the inverse of that original's transform diff.
507 sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
508 sp_repr_unparent(current);
510 // paste into topmost_parent (temporarily)
511 GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
512 if (temp_clip) g_slist_free(temp_clip);
513 if (copied) { // if success,
514 // take pasted object (now in topmost_parent)
515 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
516 // make a copy
517 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
518 // remove pasted
519 sp_repr_unparent(in_topmost);
520 // put its copy into group
521 group->appendChild(spnew);
522 Inkscape::GC::release(spnew);
523 g_slist_free(copied);
524 }
525 }
526 p = g_slist_remove(p, current);
527 }
529 // Add the new group to the topmost members' parent
530 topmost_parent->appendChild(group);
532 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
533 group->setPosition(topmost + 1);
535 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
536 _("Group"));
538 selection->set(group);
539 Inkscape::GC::release(group);
540 }
542 void sp_selection_ungroup(SPDesktop *desktop)
543 {
544 if (desktop == NULL)
545 return;
547 Inkscape::Selection *selection = sp_desktop_selection(desktop);
549 if (selection->isEmpty()) {
550 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
551 return;
552 }
554 GSList *items = g_slist_copy((GSList *) selection->itemList());
555 selection->clear();
557 // Get a copy of current selection.
558 GSList *new_select = NULL;
559 bool ungrouped = false;
560 for (GSList *i = items;
561 i != NULL;
562 i = i->next)
563 {
564 SPItem *group = (SPItem *) i->data;
566 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
567 if (!SP_IS_OBJECT(group)) {
568 continue;
569 }
571 /* We do not allow ungrouping <svg> etc. (lauris) */
572 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
573 // keep the non-group item in the new selection
574 selection->add(group);
575 continue;
576 }
578 GSList *children = NULL;
579 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
580 sp_item_group_ungroup(SP_GROUP(group), &children, false);
581 ungrouped = true;
582 // Add ungrouped items to the new selection.
583 new_select = g_slist_concat(new_select, children);
584 }
586 if (new_select) { // Set new selection.
587 selection->addList(new_select);
588 g_slist_free(new_select);
589 }
590 if (!ungrouped) {
591 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
592 }
594 g_slist_free(items);
596 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
597 _("Ungroup"));
598 }
600 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
601 GSList *
602 sp_degroup_list(GSList *items)
603 {
604 GSList *out = NULL;
605 bool has_groups = false;
606 for (GSList *item = items; item; item = item->next) {
607 if (!SP_IS_GROUP(item->data)) {
608 out = g_slist_prepend(out, item->data);
609 } else {
610 has_groups = true;
611 GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
612 for (GSList *member = members; member; member = member->next) {
613 out = g_slist_prepend(out, member->data);
614 }
615 g_slist_free(members);
616 }
617 }
618 out = g_slist_reverse(out);
619 g_slist_free(items);
621 if (has_groups) { // recurse if we unwrapped a group - it may have contained others
622 out = sp_degroup_list(out);
623 }
625 return out;
626 }
629 /** If items in the list have a common parent, return it, otherwise return NULL */
630 static SPGroup *
631 sp_item_list_common_parent_group(GSList const *items)
632 {
633 if (!items) {
634 return NULL;
635 }
636 SPObject *parent = SP_OBJECT_PARENT(items->data);
637 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
638 if (!SP_IS_GROUP(parent)) {
639 return NULL;
640 }
641 for (items = items->next; items; items = items->next) {
642 if (SP_OBJECT_PARENT(items->data) != parent) {
643 return NULL;
644 }
645 }
647 return SP_GROUP(parent);
648 }
650 /** Finds out the minimum common bbox of the selected items. */
651 static Geom::OptRect
652 enclose_items(GSList const *items)
653 {
654 g_assert(items != NULL);
656 Geom::OptRect r;
657 for (GSList const *i = items; i; i = i->next) {
658 r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
659 }
660 return r;
661 }
663 SPObject *
664 prev_sibling(SPObject *child)
665 {
666 SPObject *parent = SP_OBJECT_PARENT(child);
667 if (!SP_IS_GROUP(parent)) {
668 return NULL;
669 }
670 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
671 if (i->next == child)
672 return i;
673 }
674 return NULL;
675 }
677 void
678 sp_selection_raise(SPDesktop *desktop)
679 {
680 if (!desktop)
681 return;
683 Inkscape::Selection *selection = sp_desktop_selection(desktop);
685 GSList const *items = (GSList *) selection->itemList();
686 if (!items) {
687 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
688 return;
689 }
691 SPGroup const *group = sp_item_list_common_parent_group(items);
692 if (!group) {
693 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
694 return;
695 }
697 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
699 /* Construct reverse-ordered list of selected children. */
700 GSList *rev = g_slist_copy((GSList *) items);
701 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
703 // Determine the common bbox of the selected items.
704 Geom::OptRect selected = enclose_items(items);
706 // Iterate over all objects in the selection (starting from top).
707 if (selected) {
708 while (rev) {
709 SPObject *child = SP_OBJECT(rev->data);
710 // for each selected object, find the next sibling
711 for (SPObject *newref = child->next; newref; newref = newref->next) {
712 // if the sibling is an item AND overlaps our selection,
713 if (SP_IS_ITEM(newref)) {
714 Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
715 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
716 // AND if it's not one of our selected objects,
717 if (!g_slist_find((GSList *) items, newref)) {
718 // move the selected object after that sibling
719 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
720 }
721 break;
722 }
723 }
724 }
725 rev = g_slist_remove(rev, child);
726 }
727 } else {
728 g_slist_free(rev);
729 }
731 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
732 //TRANSLATORS: only translate "string" in "context|string".
733 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
734 // "Raise" means "to raise an object" in the undo history
735 Q_("undo_action|Raise"));
736 }
738 void sp_selection_raise_to_top(SPDesktop *desktop)
739 {
740 if (desktop == NULL)
741 return;
743 SPDocument *document = sp_desktop_document(desktop);
744 Inkscape::Selection *selection = sp_desktop_selection(desktop);
746 if (selection->isEmpty()) {
747 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
748 return;
749 }
751 GSList const *items = (GSList *) selection->itemList();
753 SPGroup const *group = sp_item_list_common_parent_group(items);
754 if (!group) {
755 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
756 return;
757 }
759 GSList *rl = g_slist_copy((GSList *) selection->reprList());
760 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
762 for (GSList *l = rl; l != NULL; l = l->next) {
763 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
764 repr->setPosition(-1);
765 }
767 g_slist_free(rl);
769 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
770 _("Raise to top"));
771 }
773 void
774 sp_selection_lower(SPDesktop *desktop)
775 {
776 if (desktop == NULL)
777 return;
779 Inkscape::Selection *selection = sp_desktop_selection(desktop);
781 GSList const *items = (GSList *) selection->itemList();
782 if (!items) {
783 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
784 return;
785 }
787 SPGroup const *group = sp_item_list_common_parent_group(items);
788 if (!group) {
789 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
790 return;
791 }
793 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
795 // Determine the common bbox of the selected items.
796 Geom::OptRect selected = enclose_items(items);
798 /* Construct direct-ordered list of selected children. */
799 GSList *rev = g_slist_copy((GSList *) items);
800 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
801 rev = g_slist_reverse(rev);
803 // Iterate over all objects in the selection (starting from top).
804 if (selected) {
805 while (rev) {
806 SPObject *child = SP_OBJECT(rev->data);
807 // for each selected object, find the prev sibling
808 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
809 // if the sibling is an item AND overlaps our selection,
810 if (SP_IS_ITEM(newref)) {
811 Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
812 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
813 // AND if it's not one of our selected objects,
814 if (!g_slist_find((GSList *) items, newref)) {
815 // move the selected object before that sibling
816 SPObject *put_after = prev_sibling(newref);
817 if (put_after)
818 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
819 else
820 SP_OBJECT_REPR(child)->setPosition(0);
821 }
822 break;
823 }
824 }
825 }
826 rev = g_slist_remove(rev, child);
827 }
828 } else {
829 g_slist_free(rev);
830 }
832 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
833 _("Lower"));
834 }
836 void sp_selection_lower_to_bottom(SPDesktop *desktop)
837 {
838 if (desktop == NULL)
839 return;
841 SPDocument *document = sp_desktop_document(desktop);
842 Inkscape::Selection *selection = sp_desktop_selection(desktop);
844 if (selection->isEmpty()) {
845 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
846 return;
847 }
849 GSList const *items = (GSList *) selection->itemList();
851 SPGroup const *group = sp_item_list_common_parent_group(items);
852 if (!group) {
853 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
854 return;
855 }
857 GSList *rl;
858 rl = g_slist_copy((GSList *) selection->reprList());
859 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
860 rl = g_slist_reverse(rl);
862 for (GSList *l = rl; l != NULL; l = l->next) {
863 gint minpos;
864 SPObject *pp, *pc;
865 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
866 pp = document->getObjectByRepr(sp_repr_parent(repr));
867 minpos = 0;
868 g_assert(SP_IS_GROUP(pp));
869 pc = sp_object_first_child(pp);
870 while (!SP_IS_ITEM(pc)) {
871 minpos += 1;
872 pc = pc->next;
873 }
874 repr->setPosition(minpos);
875 }
877 g_slist_free(rl);
879 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
880 _("Lower to bottom"));
881 }
883 void
884 sp_undo(SPDesktop *desktop, SPDocument *)
885 {
886 if (!sp_document_undo(sp_desktop_document(desktop)))
887 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
888 }
890 void
891 sp_redo(SPDesktop *desktop, SPDocument *)
892 {
893 if (!sp_document_redo(sp_desktop_document(desktop)))
894 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
895 }
897 void sp_selection_cut(SPDesktop *desktop)
898 {
899 sp_selection_copy();
900 sp_selection_delete(desktop);
901 }
903 /**
904 * \pre item != NULL
905 */
906 SPCSSAttr *
907 take_style_from_item(SPItem *item)
908 {
909 // write the complete cascaded style, context-free
910 SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
911 if (css == NULL)
912 return NULL;
914 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
915 (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
916 // if this is a text with exactly one tspan child, merge the style of that tspan as well
917 // If this is a group, merge the style of its topmost (last) child with style
918 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
919 if (SP_OBJECT_STYLE(last_element) != NULL) {
920 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
921 if (temp) {
922 sp_repr_css_merge(css, temp);
923 sp_repr_css_attr_unref(temp);
924 }
925 break;
926 }
927 }
928 }
929 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
930 // do not copy text properties from non-text objects, it's confusing
931 css = sp_css_attr_unset_text(css);
932 }
934 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
935 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
936 if (ex != 1.0) {
937 css = sp_css_attr_scale(css, ex);
938 }
940 return css;
941 }
944 void sp_selection_copy()
945 {
946 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
947 cm->copy();
948 }
950 void sp_selection_paste(SPDesktop *desktop, bool in_place)
951 {
952 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
953 if (cm->paste(in_place))
954 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
955 }
957 void sp_selection_paste_style(SPDesktop *desktop)
958 {
959 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
960 if (cm->pasteStyle())
961 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
962 }
965 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
966 {
967 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
968 if (cm->pastePathEffect())
969 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
970 _("Paste live path effect"));
971 }
974 void sp_selection_remove_livepatheffect_impl(SPItem *item)
975 {
976 if ( item && SP_IS_LPE_ITEM(item) &&
977 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
978 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
979 }
980 }
982 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
983 {
984 if (desktop == NULL) return;
986 Inkscape::Selection *selection = sp_desktop_selection(desktop);
988 // check if something is selected
989 if (selection->isEmpty()) {
990 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
991 return;
992 }
994 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
995 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
997 sp_selection_remove_livepatheffect_impl(item);
999 }
1001 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1002 _("Remove live path effect"));
1003 }
1005 void sp_selection_remove_filter(SPDesktop *desktop)
1006 {
1007 if (desktop == NULL) return;
1009 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1011 // check if something is selected
1012 if (selection->isEmpty()) {
1013 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1014 return;
1015 }
1017 SPCSSAttr *css = sp_repr_css_attr_new();
1018 sp_repr_css_unset_property(css, "filter");
1019 sp_desktop_set_style(desktop, css);
1020 sp_repr_css_attr_unref(css);
1022 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1023 _("Remove filter"));
1024 }
1027 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1028 {
1029 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1030 if (cm->pasteSize(false, apply_x, apply_y))
1031 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1032 _("Paste size"));
1033 }
1035 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1036 {
1037 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1038 if (cm->pasteSize(true, apply_x, apply_y))
1039 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1040 _("Paste size separately"));
1041 }
1043 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1044 {
1045 Inkscape::Selection *selection = sp_desktop_selection(dt);
1047 // check if something is selected
1048 if (selection->isEmpty()) {
1049 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1050 return;
1051 }
1053 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1055 bool no_more = false; // Set to true, if no more layers above
1056 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1057 if (next) {
1058 GSList *temp_clip = NULL;
1059 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1060 sp_selection_delete_impl(items, false, false);
1061 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1062 GSList *copied;
1063 if (next) {
1064 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1065 } else {
1066 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1067 no_more = true;
1068 }
1069 selection->setReprList((GSList const *) copied);
1070 g_slist_free(copied);
1071 if (temp_clip) g_slist_free(temp_clip);
1072 if (next) dt->setCurrentLayer(next);
1073 if ( !suppressDone ) {
1074 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1075 _("Raise to next layer"));
1076 }
1077 } else {
1078 no_more = true;
1079 }
1081 if (no_more) {
1082 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1083 }
1085 g_slist_free((GSList *) items);
1086 }
1088 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1089 {
1090 Inkscape::Selection *selection = sp_desktop_selection(dt);
1092 // check if something is selected
1093 if (selection->isEmpty()) {
1094 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1095 return;
1096 }
1098 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1100 bool no_more = false; // Set to true, if no more layers below
1101 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1102 if (next) {
1103 GSList *temp_clip = NULL;
1104 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
1105 sp_selection_delete_impl(items, false, false);
1106 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1107 GSList *copied;
1108 if (next) {
1109 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1110 } else {
1111 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1112 no_more = true;
1113 }
1114 selection->setReprList((GSList const *) copied);
1115 g_slist_free(copied);
1116 if (temp_clip) g_slist_free(temp_clip);
1117 if (next) dt->setCurrentLayer(next);
1118 if ( !suppressDone ) {
1119 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1120 _("Lower to previous layer"));
1121 }
1122 } else {
1123 no_more = true;
1124 }
1126 if (no_more) {
1127 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1128 }
1130 g_slist_free((GSList *) items);
1131 }
1133 bool
1134 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1135 {
1136 bool contains_original = false;
1138 bool is_use = SP_IS_USE(item);
1139 SPItem *item_use = item;
1140 SPItem *item_use_first = item;
1141 while (is_use && item_use && !contains_original)
1142 {
1143 item_use = sp_use_get_original(SP_USE(item_use));
1144 contains_original |= selection->includes(item_use);
1145 if (item_use == item_use_first)
1146 break;
1147 is_use = SP_IS_USE(item_use);
1148 }
1150 // If it's a tref, check whether the object containing the character
1151 // data is part of the selection
1152 if (!contains_original && SP_IS_TREF(item)) {
1153 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1154 }
1156 return contains_original;
1157 }
1160 bool
1161 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1162 {
1163 bool clone_with_original = false;
1164 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1165 SPItem *item = SP_ITEM(l->data);
1166 clone_with_original |= selection_contains_original(item, selection);
1167 if (clone_with_original)
1168 break;
1169 }
1170 return clone_with_original;
1171 }
1173 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1174 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1175 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1176 that case, items are already in the new position, but the repr is in the old, and this function
1177 then simply updates the repr from item->transform.
1178 */
1179 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1180 {
1181 if (selection->isEmpty())
1182 return;
1184 // For each perspective with a box in selection, check whether all boxes are selected and
1185 // unlink all non-selected boxes.
1186 Persp3D *persp;
1187 Persp3D *transf_persp;
1188 std::list<Persp3D *> plist = selection->perspList();
1189 for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1190 persp = (Persp3D *) (*i);
1192 if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1193 std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1195 // create a new perspective as a copy of the current one and link the selected boxes to it
1196 transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1198 for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1199 box3d_switch_perspectives(*b, persp, transf_persp);
1200 } else {
1201 transf_persp = persp;
1202 }
1204 persp3d_apply_affine_transformation(transf_persp, affine);
1205 }
1207 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1208 SPItem *item = SP_ITEM(l->data);
1210 Geom::Point old_center(0,0);
1211 if (set_i2d && item->isCenterSet())
1212 old_center = item->getCenter();
1214 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1215 At the time of writing, this is the only place to re-enable. */
1216 sp_item_update_cns(*item, selection->desktop());
1217 #endif
1219 // we're moving both a clone and its original or any ancestor in clone chain?
1220 bool transform_clone_with_original = selection_contains_original(item, selection);
1221 // ...both a text-on-path and its path?
1222 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)))) ));
1223 // ...both a flowtext and its frame?
1224 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)
1225 // ...both an offset and its source?
1226 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1228 // If we're moving a connector, we want to detach it
1229 // from shapes that aren't part of the selection, but
1230 // leave it attached if they are
1231 if (cc_item_is_connector(item)) {
1232 SPItem *attItem[2];
1233 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1235 for (int n = 0; n < 2; ++n) {
1236 if (!selection->includes(attItem[n])) {
1237 sp_conn_end_detach(item, n);
1238 }
1239 }
1240 }
1242 // "clones are unmoved when original is moved" preference
1243 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1244 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1245 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1246 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1248 /* If this is a clone and it's selected along with its original, do not move it;
1249 * it will feel the transform of its original and respond to it itself.
1250 * Without this, a clone is doubly transformed, very unintuitive.
1251 *
1252 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1253 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1254 * Same for linked offset if we are also moving its source: do not move it. */
1255 if (transform_textpath_with_path || transform_offset_with_source) {
1256 // Restore item->transform field from the repr, in case it was changed by seltrans.
1257 sp_object_read_attr(SP_OBJECT(item), "transform");
1258 } else if (transform_flowtext_with_frame) {
1259 // apply the inverse of the region's transform to the <use> so that the flow remains
1260 // the same (even though the output itself gets transformed)
1261 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1262 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1263 continue;
1264 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1265 if (!SP_IS_USE(use)) continue;
1266 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1267 }
1268 }
1269 } else if (transform_clone_with_original) {
1270 // We are transforming a clone along with its original. The below matrix juggling is
1271 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1272 // transform and its move compensation are both cancelled out.
1274 // restore item->transform field from the repr, in case it was changed by seltrans
1275 sp_object_read_attr(SP_OBJECT(item), "transform");
1277 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1278 Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1279 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1280 Geom::Matrix t_inv = t.inverse();
1281 Geom::Matrix result = t_inv * item->transform * t;
1283 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1284 // we need to cancel out the move compensation, too
1286 // find out the clone move, same as in sp_use_move_compensate
1287 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1288 Geom::Matrix clone_move = parent.inverse() * t * parent;
1290 if (prefs_parallel) {
1291 Geom::Matrix move = result * clone_move * t_inv;
1292 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1294 } else if (prefs_unmoved) {
1295 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1296 // clone_move = Geom::identity();
1297 Geom::Matrix move = result * clone_move;
1298 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1299 }
1301 } else {
1302 // just apply the result
1303 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1304 }
1306 } else {
1307 if (set_i2d) {
1308 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1309 }
1310 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1311 }
1313 // if we're moving the actual object, not just updating the repr, we can transform the
1314 // center by the same matrix (only necessary for non-translations)
1315 if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1316 item->setCenter(old_center * affine);
1317 SP_OBJECT(item)->updateRepr();
1318 }
1319 }
1320 }
1322 void sp_selection_remove_transform(SPDesktop *desktop)
1323 {
1324 if (desktop == NULL)
1325 return;
1327 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1329 GSList const *l = (GSList *) selection->reprList();
1330 while (l != NULL) {
1331 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1332 l = l->next;
1333 }
1335 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1336 _("Remove transform"));
1337 }
1339 void
1340 sp_selection_scale_absolute(Inkscape::Selection *selection,
1341 double const x0, double const x1,
1342 double const y0, double const y1)
1343 {
1344 if (selection->isEmpty())
1345 return;
1347 Geom::OptRect const bbox(selection->bounds());
1348 if ( !bbox ) {
1349 return;
1350 }
1352 Geom::Translate const p2o(-bbox->min());
1354 Geom::Scale const newSize(x1 - x0,
1355 y1 - y0);
1356 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1357 Geom::Translate const o2n(x0, y0);
1358 Geom::Matrix const final( p2o * scale * o2n );
1360 sp_selection_apply_affine(selection, final);
1361 }
1364 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1365 {
1366 if (selection->isEmpty())
1367 return;
1369 Geom::OptRect const bbox(selection->bounds());
1371 if ( !bbox ) {
1372 return;
1373 }
1375 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1376 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1377 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1378 {
1379 return;
1380 }
1382 Geom::Translate const n2d(-align);
1383 Geom::Translate const d2n(align);
1384 Geom::Matrix const final( n2d * scale * d2n );
1385 sp_selection_apply_affine(selection, final);
1386 }
1388 void
1389 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1390 {
1391 Geom::Translate const d2n(center);
1392 Geom::Translate const n2d(-center);
1393 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1394 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1395 sp_selection_apply_affine(selection, final);
1396 }
1398 void
1399 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1400 {
1401 Geom::Translate const d2n(align);
1402 Geom::Translate const n2d(-align);
1403 Geom::Matrix const skew(1, dy,
1404 dx, 1,
1405 0, 0);
1406 Geom::Matrix const final( n2d * skew * d2n );
1407 sp_selection_apply_affine(selection, final);
1408 }
1410 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1411 {
1412 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1413 }
1415 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1416 {
1417 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1418 }
1420 /**
1421 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1422 */
1423 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1424 {
1425 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1427 if (selection->isEmpty())
1428 return;
1430 GSList const *l = selection->itemList();
1431 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1432 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1433 SPItem *item = SP_ITEM(l2->data);
1434 sp_item_rotate_rel(item, rot_90);
1435 }
1437 sp_document_done(sp_desktop_document(desktop),
1438 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1439 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1440 }
1442 void
1443 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1444 {
1445 if (selection->isEmpty())
1446 return;
1448 boost::optional<Geom::Point> center = selection->center();
1449 if (!center) {
1450 return;
1451 }
1453 sp_selection_rotate_relative(selection, *center, angle_degrees);
1455 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1456 ( ( angle_degrees > 0 )
1457 ? "selector:rotate:ccw"
1458 : "selector:rotate:cw" ),
1459 SP_VERB_CONTEXT_SELECT,
1460 _("Rotate"));
1461 }
1463 // helper function:
1464 static
1465 Geom::Point
1466 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1467 Geom::Point m = r.midpoint();
1468 unsigned i = 0;
1469 if (p[X] < m[X]) {
1470 i = 1;
1471 }
1472 if (p[Y] < m[Y]) {
1473 i = 3 - i;
1474 }
1475 return r.corner(i);
1476 }
1478 /**
1479 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1480 */
1481 void
1482 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1483 {
1484 if (selection->isEmpty())
1485 return;
1487 Geom::OptRect const bbox(selection->bounds());
1488 boost::optional<Geom::Point> center = selection->center();
1490 if ( !bbox || !center ) {
1491 return;
1492 }
1494 gdouble const zoom = selection->desktop()->current_zoom();
1495 gdouble const zmove = angle / zoom;
1496 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1498 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1500 sp_selection_rotate_relative(selection, *center, zangle);
1502 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1503 ( (angle > 0)
1504 ? "selector:rotate:ccw"
1505 : "selector:rotate:cw" ),
1506 SP_VERB_CONTEXT_SELECT,
1507 _("Rotate by pixels"));
1508 }
1510 void
1511 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1512 {
1513 if (selection->isEmpty())
1514 return;
1516 Geom::OptRect const bbox(selection->bounds());
1517 if (!bbox) {
1518 return;
1519 }
1521 Geom::Point const center(bbox->midpoint());
1523 // you can't scale "do nizhe pola" (below zero)
1524 double const max_len = bbox->maxExtent();
1525 if ( max_len + grow <= 1e-3 ) {
1526 return;
1527 }
1529 double const times = 1.0 + grow / max_len;
1530 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1532 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1533 ( (grow > 0)
1534 ? "selector:scale:larger"
1535 : "selector:scale:smaller" ),
1536 SP_VERB_CONTEXT_SELECT,
1537 _("Scale"));
1538 }
1540 void
1541 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1542 {
1543 sp_selection_scale(selection,
1544 grow_pixels / selection->desktop()->current_zoom());
1545 }
1547 void
1548 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1549 {
1550 if (selection->isEmpty())
1551 return;
1553 Geom::OptRect sel_bbox = selection->bounds();
1555 if (!sel_bbox) {
1556 return;
1557 }
1559 Geom::Point const center(sel_bbox->midpoint());
1560 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1561 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1562 _("Scale by whole factor"));
1563 }
1565 void
1566 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1567 {
1568 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1569 if (selection->isEmpty()) {
1570 return;
1571 }
1573 sp_selection_move_relative(selection, dx, dy);
1575 if (dx == 0) {
1576 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1577 _("Move vertically"));
1578 } else if (dy == 0) {
1579 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1580 _("Move horizontally"));
1581 } else {
1582 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1583 _("Move"));
1584 }
1585 }
1587 void
1588 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1589 {
1590 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1591 if (selection->isEmpty()) {
1592 return;
1593 }
1595 // same as sp_selection_move but divide deltas by zoom factor
1596 gdouble const zoom = desktop->current_zoom();
1597 gdouble const zdx = dx / zoom;
1598 gdouble const zdy = dy / zoom;
1599 sp_selection_move_relative(selection, zdx, zdy);
1601 if (dx == 0) {
1602 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1603 _("Move vertically by pixels"));
1604 } else if (dy == 0) {
1605 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1606 _("Move horizontally by pixels"));
1607 } else {
1608 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1609 _("Move"));
1610 }
1611 }
1613 namespace {
1615 template <typename D>
1616 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1617 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1619 template <typename D>
1620 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1621 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1623 struct Forward {
1624 typedef SPObject *Iterator;
1626 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1627 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1628 static void dispose(Iterator /*i*/) {}
1630 static SPObject *object(Iterator i) { return i; }
1631 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1632 };
1634 struct Reverse {
1635 typedef GSList *Iterator;
1637 static Iterator children(SPObject *o) {
1638 return make_list(o->firstChild(), NULL);
1639 }
1640 static Iterator siblings_after(SPObject *o) {
1641 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1642 }
1643 static void dispose(Iterator i) {
1644 g_slist_free(i);
1645 }
1647 static SPObject *object(Iterator i) {
1648 return reinterpret_cast<SPObject *>(i->data);
1649 }
1650 static Iterator next(Iterator i) { return i->next; }
1652 private:
1653 static GSList *make_list(SPObject *object, SPObject *limit) {
1654 GSList *list=NULL;
1655 while ( object != limit ) {
1656 list = g_slist_prepend(list, object);
1657 object = SP_OBJECT_NEXT(object);
1658 }
1659 return list;
1660 }
1661 };
1663 }
1665 void
1666 sp_selection_item_next(SPDesktop *desktop)
1667 {
1668 g_return_if_fail(desktop != NULL);
1669 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1671 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1672 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1673 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1674 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1676 SPObject *root;
1677 if (PREFS_SELECTION_ALL != inlayer) {
1678 root = selection->activeContext();
1679 } else {
1680 root = desktop->currentRoot();
1681 }
1683 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1685 if (item) {
1686 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1687 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1688 scroll_to_show_item(desktop, item);
1689 }
1690 }
1691 }
1693 void
1694 sp_selection_item_prev(SPDesktop *desktop)
1695 {
1696 SPDocument *document = sp_desktop_document(desktop);
1697 g_return_if_fail(document != NULL);
1698 g_return_if_fail(desktop != NULL);
1699 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1701 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1702 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1703 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1704 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1706 SPObject *root;
1707 if (PREFS_SELECTION_ALL != inlayer) {
1708 root = selection->activeContext();
1709 } else {
1710 root = desktop->currentRoot();
1711 }
1713 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1715 if (item) {
1716 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1717 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1718 scroll_to_show_item(desktop, item);
1719 }
1720 }
1721 }
1723 void sp_selection_next_patheffect_param(SPDesktop * dt)
1724 {
1725 if (!dt) return;
1727 Inkscape::Selection *selection = sp_desktop_selection(dt);
1728 if ( selection && !selection->isEmpty() ) {
1729 SPItem *item = selection->singleItem();
1730 if ( item && SP_IS_SHAPE(item)) {
1731 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1732 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1733 } else {
1734 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1735 }
1736 }
1737 }
1738 }
1740 /*bool has_path_recursive(SPObject *obj)
1741 {
1742 if (!obj) return false;
1743 if (SP_IS_PATH(obj)) {
1744 return true;
1745 }
1746 if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1747 for (SPObject *c = obj->children; c; c = c->next) {
1748 if (has_path_recursive(c)) return true;
1749 }
1750 }
1751 return false;
1752 }*/
1754 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1755 {
1756 return;
1757 /*if (!dt) return;
1758 using namespace Inkscape::UI;
1760 Inkscape::Selection *selection = sp_desktop_selection(dt);
1761 if (!selection || selection->isEmpty()) return;
1763 GSList const *items = selection->itemList();
1764 bool has_path = false;
1765 for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1766 SPItem *item = SP_ITEM(i->data);
1767 SPObject *search = clip
1768 ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1769 : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1770 has_path |= has_path_recursive(search);
1771 if (has_path) break;
1772 }
1773 if (has_path) {
1774 if (!tools_isactive(dt, TOOLS_NODES)) {
1775 tools_switch(dt, TOOLS_NODES);
1776 }
1777 ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1778 clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1779 } else if (clip) {
1780 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1781 _("The selection has no applied clip path."));
1782 } else {
1783 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1784 _("The selection has no applied mask."));
1785 }*/
1786 }
1789 namespace {
1791 template <typename D>
1792 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1793 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1794 {
1795 SPObject *current=root;
1796 while (items) {
1797 SPItem *item=SP_ITEM(items->data);
1798 if ( root->isAncestorOf(item) &&
1799 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1800 {
1801 current = item;
1802 break;
1803 }
1804 items = items->next;
1805 }
1807 GSList *path=NULL;
1808 while ( current != root ) {
1809 path = g_slist_prepend(path, current);
1810 current = SP_OBJECT_PARENT(current);
1811 }
1813 SPItem *next;
1814 // first, try from the current object
1815 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1816 g_slist_free(path);
1818 if (!next) { // if we ran out of objects, start over at the root
1819 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1820 }
1822 return next;
1823 }
1825 template <typename D>
1826 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1827 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1828 {
1829 typename D::Iterator children;
1830 typename D::Iterator iter;
1832 SPItem *found=NULL;
1834 if (path) {
1835 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1836 g_assert(SP_OBJECT_PARENT(object) == root);
1837 if (desktop->isLayer(object)) {
1838 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1839 }
1840 iter = children = D::siblings_after(object);
1841 } else {
1842 iter = children = D::children(root);
1843 }
1845 while ( iter && !found ) {
1846 SPObject *object=D::object(iter);
1847 if (desktop->isLayer(object)) {
1848 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1849 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1850 }
1851 } else if ( SP_IS_ITEM(object) &&
1852 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1853 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1854 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1855 !desktop->isLayer(SP_ITEM(object)) )
1856 {
1857 found = SP_ITEM(object);
1858 }
1859 iter = D::next(iter);
1860 }
1862 D::dispose(children);
1864 return found;
1865 }
1867 }
1869 /**
1870 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1871 * \a item.
1872 */
1873 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1874 {
1875 Geom::Rect dbox = desktop->get_display_area();
1876 Geom::OptRect sbox = sp_item_bbox_desktop(item);
1878 if ( sbox && dbox.contains(*sbox) == false ) {
1879 Geom::Point const s_dt = sbox->midpoint();
1880 Geom::Point const s_w = desktop->d2w(s_dt);
1881 Geom::Point const d_dt = dbox.midpoint();
1882 Geom::Point const d_w = desktop->d2w(d_dt);
1883 Geom::Point const moved_w( d_w - s_w );
1884 gint const dx = (gint) moved_w[X];
1885 gint const dy = (gint) moved_w[Y];
1886 desktop->scroll_world(dx, dy);
1887 }
1888 }
1891 void
1892 sp_selection_clone(SPDesktop *desktop)
1893 {
1894 if (desktop == NULL)
1895 return;
1897 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1899 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1901 // check if something is selected
1902 if (selection->isEmpty()) {
1903 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1904 return;
1905 }
1907 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1909 selection->clear();
1911 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1912 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1914 GSList *newsel = NULL;
1916 while (reprs) {
1917 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1918 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1920 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1921 clone->setAttribute("x", "0", false);
1922 clone->setAttribute("y", "0", false);
1923 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1925 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1926 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1928 // add the new clone to the top of the original's parent
1929 parent->appendChild(clone);
1931 newsel = g_slist_prepend(newsel, clone);
1932 reprs = g_slist_remove(reprs, sel_repr);
1933 Inkscape::GC::release(clone);
1934 }
1936 // TRANSLATORS: only translate "string" in "context|string".
1937 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1938 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1939 Q_("action|Clone"));
1941 selection->setReprList(newsel);
1943 g_slist_free(newsel);
1944 }
1946 void
1947 sp_selection_relink(SPDesktop *desktop)
1948 {
1949 if (!desktop)
1950 return;
1952 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1954 if (selection->isEmpty()) {
1955 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1956 return;
1957 }
1959 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1960 const gchar *newid = cm->getFirstObjectID();
1961 if (!newid) {
1962 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1963 return;
1964 }
1965 gchar *newref = g_strdup_printf("#%s", newid);
1967 // Get a copy of current selection.
1968 bool relinked = false;
1969 for (GSList *items = (GSList *) selection->itemList();
1970 items != NULL;
1971 items = items->next)
1972 {
1973 SPItem *item = (SPItem *) items->data;
1975 if (!SP_IS_USE(item))
1976 continue;
1978 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1979 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1980 relinked = true;
1981 }
1983 g_free(newref);
1985 if (!relinked) {
1986 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1987 } else {
1988 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1989 _("Relink clone"));
1990 }
1991 }
1994 void
1995 sp_selection_unlink(SPDesktop *desktop)
1996 {
1997 if (!desktop)
1998 return;
2000 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2002 if (selection->isEmpty()) {
2003 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2004 return;
2005 }
2007 // Get a copy of current selection.
2008 GSList *new_select = NULL;
2009 bool unlinked = false;
2010 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2011 items != NULL;
2012 items = items->next)
2013 {
2014 SPItem *item = (SPItem *) items->data;
2016 if (SP_IS_TEXT(item)) {
2017 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2019 if (tspan) {
2020 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2021 }
2023 // Set unlink to true, and fall into the next if which
2024 // will include this text item in the new selection
2025 unlinked = true;
2026 }
2028 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2029 // keep the non-use item in the new selection
2030 new_select = g_slist_prepend(new_select, item);
2031 continue;
2032 }
2034 SPItem *unlink;
2035 if (SP_IS_USE(item)) {
2036 unlink = sp_use_unlink(SP_USE(item));
2037 } else /*if (SP_IS_TREF(use))*/ {
2038 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2039 }
2041 unlinked = true;
2042 // Add ungrouped items to the new selection.
2043 new_select = g_slist_prepend(new_select, unlink);
2044 }
2046 if (new_select) { // set new selection
2047 selection->clear();
2048 selection->setList(new_select);
2049 g_slist_free(new_select);
2050 }
2051 if (!unlinked) {
2052 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2053 }
2055 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2056 _("Unlink clone"));
2057 }
2059 void
2060 sp_select_clone_original(SPDesktop *desktop)
2061 {
2062 if (desktop == NULL)
2063 return;
2065 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2067 SPItem *item = selection->singleItem();
2069 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.");
2071 // Check if other than two objects are selected
2072 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2073 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2074 return;
2075 }
2077 SPItem *original = NULL;
2078 if (SP_IS_USE(item)) {
2079 original = sp_use_get_original(SP_USE(item));
2080 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2081 original = sp_offset_get_source(SP_OFFSET(item));
2082 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2083 original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2084 } else if (SP_IS_FLOWTEXT(item)) {
2085 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2086 } else { // it's an object that we don't know what to do with
2087 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2088 return;
2089 }
2091 if (!original) {
2092 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2093 return;
2094 }
2096 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2097 if (SP_IS_DEFS(o)) {
2098 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2099 return;
2100 }
2101 }
2103 if (original) {
2104 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2105 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2106 if (highlight) {
2107 Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2108 Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2109 if ( a && b ) {
2110 // draw a flashing line between the objects
2111 SPCurve *curve = new SPCurve();
2112 curve->moveto(a->midpoint());
2113 curve->lineto(b->midpoint());
2115 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2116 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2117 sp_canvas_item_show(canvasitem);
2118 curve->unref();
2119 desktop->add_temporary_canvasitem(canvasitem, 1000);
2120 }
2121 }
2123 selection->clear();
2124 selection->set(original);
2125 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2126 scroll_to_show_item(desktop, original);
2127 }
2128 }
2129 }
2132 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2133 {
2134 if (desktop == NULL)
2135 return;
2137 SPDocument *doc = sp_desktop_document(desktop);
2138 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2140 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2142 // check if something is selected
2143 if (selection->isEmpty()) {
2144 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2145 return;
2146 }
2148 sp_document_ensure_up_to_date(doc);
2149 Geom::OptRect r = selection->bounds();
2150 boost::optional<Geom::Point> c = selection->center();
2151 if ( !r || !c ) {
2152 return;
2153 }
2155 // calculate the transform to be applied to objects to move them to 0,0
2156 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2157 move_p[Geom::Y] = -move_p[Geom::Y];
2158 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2160 GSList *items = g_slist_copy((GSList *) selection->itemList());
2162 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2164 // bottommost object, after sorting
2165 SPObject *parent = SP_OBJECT_PARENT(items->data);
2167 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2169 // remember the position of the first item
2170 gint pos = SP_OBJECT_REPR(items->data)->position();
2171 (void)pos; // TODO check why this was remembered
2173 // create a list of duplicates
2174 GSList *repr_copies = NULL;
2175 for (GSList *i = items; i != NULL; i = i->next) {
2176 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2177 repr_copies = g_slist_prepend(repr_copies, dup);
2178 }
2180 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2182 if (apply) {
2183 // delete objects so that their clones don't get alerted; this object will be restored shortly
2184 for (GSList *i = items; i != NULL; i = i->next) {
2185 SPObject *item = SP_OBJECT(i->data);
2186 item->deleteObject(false);
2187 }
2188 }
2190 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2191 // without disturbing clones.
2192 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2193 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2194 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2195 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2197 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2198 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2199 Geom::Point(r->min()[Geom::X],
2200 r->max()[Geom::Y]))))
2201 * parent_transform.inverse() ),
2202 parent_transform * move);
2203 (void)mark_id;
2205 // restore compensation setting
2206 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2209 g_slist_free(items);
2211 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2212 _("Objects to marker"));
2213 }
2215 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2216 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2217 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2218 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2219 }
2220 } else {
2221 sp_item_convert_item_to_guides(item);
2223 if (deleteitem) {
2224 SP_OBJECT(item)->deleteObject(true);
2225 }
2226 }
2227 }
2229 void sp_selection_to_guides(SPDesktop *desktop)
2230 {
2231 if (desktop == NULL)
2232 return;
2234 SPDocument *doc = sp_desktop_document(desktop);
2235 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2236 // we need to copy the list because it gets reset when objects are deleted
2237 GSList *items = g_slist_copy((GSList *) selection->itemList());
2239 if (!items) {
2240 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2241 return;
2242 }
2244 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2245 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2246 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2248 for (GSList const *i = items; i != NULL; i = i->next) {
2249 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2250 }
2252 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2253 }
2255 void
2256 sp_selection_tile(SPDesktop *desktop, bool apply)
2257 {
2258 if (desktop == NULL)
2259 return;
2261 SPDocument *doc = sp_desktop_document(desktop);
2262 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2264 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2266 // check if something is selected
2267 if (selection->isEmpty()) {
2268 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2269 return;
2270 }
2272 sp_document_ensure_up_to_date(doc);
2273 Geom::OptRect r = selection->bounds();
2274 if ( !r ) {
2275 return;
2276 }
2278 // calculate the transform to be applied to objects to move them to 0,0
2279 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2280 move_p[Geom::Y] = -move_p[Geom::Y];
2281 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2283 GSList *items = g_slist_copy((GSList *) selection->itemList());
2285 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2287 // bottommost object, after sorting
2288 SPObject *parent = SP_OBJECT_PARENT(items->data);
2290 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2292 // remember the position of the first item
2293 gint pos = SP_OBJECT_REPR(items->data)->position();
2295 // create a list of duplicates
2296 GSList *repr_copies = NULL;
2297 for (GSList *i = items; i != NULL; i = i->next) {
2298 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2299 repr_copies = g_slist_prepend(repr_copies, dup);
2300 }
2301 // restore the z-order after prepends
2302 repr_copies = g_slist_reverse(repr_copies);
2304 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2306 if (apply) {
2307 // delete objects so that their clones don't get alerted; this object will be restored shortly
2308 for (GSList *i = items; i != NULL; i = i->next) {
2309 SPObject *item = SP_OBJECT(i->data);
2310 item->deleteObject(false);
2311 }
2312 }
2314 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2315 // without disturbing clones.
2316 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2317 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2318 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2319 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2321 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2322 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2323 r->max()[Geom::Y]))))
2324 * to_2geom(parent_transform.inverse()) ),
2325 parent_transform * move);
2327 // restore compensation setting
2328 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2330 if (apply) {
2331 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2332 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2334 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2335 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2337 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2338 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2339 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2340 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2342 // restore parent and position
2343 SP_OBJECT_REPR(parent)->appendChild(rect);
2344 rect->setPosition(pos > 0 ? pos : 0);
2345 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2347 Inkscape::GC::release(rect);
2349 selection->clear();
2350 selection->set(rectangle);
2351 }
2353 g_slist_free(items);
2355 sp_document_done(doc, SP_VERB_EDIT_TILE,
2356 _("Objects to pattern"));
2357 }
2359 void
2360 sp_selection_untile(SPDesktop *desktop)
2361 {
2362 if (desktop == NULL)
2363 return;
2365 SPDocument *doc = sp_desktop_document(desktop);
2366 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2368 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2370 // check if something is selected
2371 if (selection->isEmpty()) {
2372 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2373 return;
2374 }
2376 GSList *new_select = NULL;
2378 bool did = false;
2380 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2381 items != NULL;
2382 items = items->next) {
2384 SPItem *item = (SPItem *) items->data;
2386 SPStyle *style = SP_OBJECT_STYLE(item);
2388 if (!style || !style->fill.isPaintserver())
2389 continue;
2391 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2393 if (!SP_IS_PATTERN(server))
2394 continue;
2396 did = true;
2398 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2400 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2401 pat_transform *= item->transform;
2403 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2404 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2405 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2407 // FIXME: relink clones to the new canvas objects
2408 // use SPObject::setid when mental finishes it to steal ids of
2410 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2411 sp_document_ensure_up_to_date(doc);
2413 Geom::Matrix transform( i->transform * pat_transform );
2414 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2416 new_select = g_slist_prepend(new_select, i);
2417 }
2419 SPCSSAttr *css = sp_repr_css_attr_new();
2420 sp_repr_css_set_property(css, "fill", "none");
2421 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2422 }
2424 if (!did) {
2425 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2426 } else {
2427 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2428 _("Pattern to objects"));
2429 selection->setList(new_select);
2430 }
2431 }
2433 void
2434 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2435 {
2436 if (selection->isEmpty()) {
2437 return;
2438 }
2440 GSList const *reprlst = selection->reprList();
2441 bool filename_search = TRUE;
2442 bool xdpi_search = TRUE;
2443 bool ydpi_search = TRUE;
2445 for (; reprlst != NULL &&
2446 filename_search &&
2447 xdpi_search &&
2448 ydpi_search;
2449 reprlst = reprlst->next) {
2450 gchar const *dpi_string;
2451 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2453 if (filename_search) {
2454 *filename = repr->attribute("inkscape:export-filename");
2455 if (*filename != NULL)
2456 filename_search = FALSE;
2457 }
2459 if (xdpi_search) {
2460 dpi_string = NULL;
2461 dpi_string = repr->attribute("inkscape:export-xdpi");
2462 if (dpi_string != NULL) {
2463 *xdpi = atof(dpi_string);
2464 xdpi_search = FALSE;
2465 }
2466 }
2468 if (ydpi_search) {
2469 dpi_string = NULL;
2470 dpi_string = repr->attribute("inkscape:export-ydpi");
2471 if (dpi_string != NULL) {
2472 *ydpi = atof(dpi_string);
2473 ydpi_search = FALSE;
2474 }
2475 }
2476 }
2477 }
2479 void
2480 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2481 {
2482 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2483 gchar const *dpi_string;
2485 *filename = repr->attribute("inkscape:export-filename");
2487 dpi_string = NULL;
2488 dpi_string = repr->attribute("inkscape:export-xdpi");
2489 if (dpi_string != NULL) {
2490 *xdpi = atof(dpi_string);
2491 }
2493 dpi_string = NULL;
2494 dpi_string = repr->attribute("inkscape:export-ydpi");
2495 if (dpi_string != NULL) {
2496 *ydpi = atof(dpi_string);
2497 }
2498 }
2500 void
2501 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2502 {
2503 if (desktop == NULL)
2504 return;
2506 SPDocument *document = sp_desktop_document(desktop);
2507 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2509 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2511 // check if something is selected
2512 if (selection->isEmpty()) {
2513 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2514 return;
2515 }
2517 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2518 // set "busy" cursor
2519 desktop->setWaitingCursor();
2521 // Get the bounding box of the selection
2522 NRRect bbox;
2523 sp_document_ensure_up_to_date(document);
2524 selection->bounds(&bbox);
2525 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2526 desktop->clearWaitingCursor();
2527 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2528 }
2530 // List of the items to show; all others will be hidden
2531 GSList *items = g_slist_copy((GSList *) selection->itemList());
2533 // Sort items so that the topmost comes last
2534 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2536 // Generate a random value from the current time (you may create bitmap from the same object(s)
2537 // multiple times, and this is done so that they don't clash)
2538 GTimeVal cu;
2539 g_get_current_time(&cu);
2540 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2542 // Create the filename.
2543 gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2544 document->name,
2545 SP_OBJECT_REPR(items->data)->attribute("id"),
2546 current);
2547 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2548 // digits, and a few other chars, with "_"
2549 g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2551 // Build the complete path by adding document base dir, if set, otherwise home dir
2552 gchar * directory = NULL;
2553 if (SP_DOCUMENT_URI(document)) {
2554 directory = g_dirname(SP_DOCUMENT_URI(document));
2555 }
2556 if (directory == NULL) {
2557 directory = homedir_path(NULL);
2558 }
2559 gchar *filepath = g_build_filename(directory, basename, NULL);
2561 //g_print("%s\n", filepath);
2563 // Remember parent and z-order of the topmost one
2564 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2565 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2566 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2568 // Calculate resolution
2569 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2570 double res;
2571 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2572 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2573 if (0 < prefs_res) {
2574 // If it's given explicitly in prefs, take it
2575 res = prefs_res;
2576 } else if (0 < prefs_min) {
2577 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2578 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2579 } else {
2580 float hint_xdpi = 0, hint_ydpi = 0;
2581 char const *hint_filename;
2582 // take resolution hint from the selected objects
2583 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2584 if (hint_xdpi != 0) {
2585 res = hint_xdpi;
2586 } else {
2587 // take resolution hint from the document
2588 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2589 if (hint_xdpi != 0) {
2590 res = hint_xdpi;
2591 } else {
2592 // if all else fails, take the default 90 dpi
2593 res = PX_PER_IN;
2594 }
2595 }
2596 }
2598 // The width and height of the bitmap in pixels
2599 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2600 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2602 // Find out if we have to run an external filter
2603 gchar const *run = NULL;
2604 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2605 if (!filter.empty()) {
2606 // filter command is given;
2607 // see if we have a parameter to pass to it
2608 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2609 if (!param1.empty()) {
2610 if (param1[param1.length() - 1] == '%') {
2611 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2612 gchar p1[256];
2613 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2614 // the first param is always the image filename, the second is param1
2615 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2616 } else {
2617 // otherwise pass the param1 unchanged
2618 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2619 }
2620 } else {
2621 // run without extra parameter
2622 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2623 }
2624 }
2626 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2627 Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2628 Geom::Matrix t;
2630 double shift_x = bbox.x0;
2631 double shift_y = bbox.y1;
2632 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2633 shift_x = round(shift_x);
2634 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2635 }
2636 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2638 // Do the export
2639 sp_export_png_file(document, filepath,
2640 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2641 width, height, res, res,
2642 (guint32) 0xffffff00,
2643 NULL, NULL,
2644 true, /*bool force_overwrite,*/
2645 items);
2647 g_slist_free(items);
2649 // Run filter, if any
2650 if (run) {
2651 g_print("Running external filter: %s\n", run);
2652 int retval;
2653 retval = system(run);
2654 }
2656 // Import the image back
2657 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2658 if (pb) {
2659 // Create the repr for the image
2660 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2661 {
2662 repr->setAttribute("sodipodi:absref", filepath);
2663 gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2664 repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2665 g_free(abs_base);
2666 }
2667 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2668 sp_repr_set_svg_double(repr, "width", width);
2669 sp_repr_set_svg_double(repr, "height", height);
2670 } else {
2671 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2672 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2673 }
2675 // Write transform
2676 gchar *c=sp_svg_transform_write(t);
2677 repr->setAttribute("transform", c);
2678 g_free(c);
2680 // add the new repr to the parent
2681 parent->appendChild(repr);
2683 // move to the saved position
2684 repr->setPosition(pos > 0 ? pos + 1 : 1);
2686 // Set selection to the new image
2687 selection->clear();
2688 selection->add(repr);
2690 // Clean up
2691 Inkscape::GC::release(repr);
2692 gdk_pixbuf_unref(pb);
2694 // Complete undoable transaction
2695 sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2696 _("Create bitmap"));
2697 }
2699 desktop->clearWaitingCursor();
2701 g_free(basename);
2702 g_free(filepath);
2703 }
2705 /**
2706 * \brief Creates a mask or clipPath from selection
2707 * Two different modes:
2708 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2709 * and is applied to current layer
2710 * otherwise, topmost object is used as mask for other objects
2711 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2712 *
2713 */
2714 void
2715 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2716 {
2717 if (desktop == NULL)
2718 return;
2720 SPDocument *doc = sp_desktop_document(desktop);
2721 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2723 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2725 // check if something is selected
2726 bool is_empty = selection->isEmpty();
2727 if ( apply_to_layer && is_empty) {
2728 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2729 return;
2730 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2731 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2732 return;
2733 }
2735 // FIXME: temporary patch to prevent crash!
2736 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2737 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2738 if (clone_with_original) {
2739 return; // in this version, you cannot clip/mask an object with its own clone
2740 }
2741 // /END FIXME
2743 sp_document_ensure_up_to_date(doc);
2745 GSList *items = g_slist_copy((GSList *) selection->itemList());
2747 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2749 // create a list of duplicates
2750 GSList *mask_items = NULL;
2751 GSList *apply_to_items = NULL;
2752 GSList *items_to_delete = NULL;
2753 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2754 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2755 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2757 if (apply_to_layer) {
2758 // all selected items are used for mask, which is applied to a layer
2759 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2761 for (GSList *i = items; i != NULL; i = i->next) {
2762 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2763 mask_items = g_slist_prepend(mask_items, dup);
2765 if (remove_original) {
2766 SPObject *item = SP_OBJECT(i->data);
2767 items_to_delete = g_slist_prepend(items_to_delete, item);
2768 }
2769 }
2770 } else if (!topmost) {
2771 // topmost item is used as a mask, which is applied to other items in a selection
2772 GSList *i = items;
2773 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2774 mask_items = g_slist_prepend(mask_items, dup);
2776 if (remove_original) {
2777 SPObject *item = SP_OBJECT(i->data);
2778 items_to_delete = g_slist_prepend(items_to_delete, item);
2779 }
2781 for (i = i->next; i != NULL; i = i->next) {
2782 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2783 }
2784 } else {
2785 GSList *i = NULL;
2786 for (i = items; NULL != i->next; i = i->next) {
2787 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2788 }
2790 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2791 mask_items = g_slist_prepend(mask_items, dup);
2793 if (remove_original) {
2794 SPObject *item = SP_OBJECT(i->data);
2795 items_to_delete = g_slist_prepend(items_to_delete, item);
2796 }
2797 }
2799 g_slist_free(items);
2800 items = NULL;
2802 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2803 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2804 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2805 // inverted object transform should be applied to a mask object,
2806 // as mask is calculated in user space (after applying transform)
2807 Geom::Matrix maskTransform(item->transform.inverse());
2809 GSList *mask_items_dup = NULL;
2810 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2811 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2812 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2813 }
2815 gchar const *mask_id = NULL;
2816 if (apply_clip_path) {
2817 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2818 } else {
2819 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2820 }
2822 g_slist_free(mask_items_dup);
2823 mask_items_dup = NULL;
2825 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2826 }
2828 g_slist_free(mask_items);
2829 g_slist_free(apply_to_items);
2831 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2832 SPObject *item = SP_OBJECT(i->data);
2833 item->deleteObject(false);
2834 }
2835 g_slist_free(items_to_delete);
2837 if (apply_clip_path)
2838 sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2839 else
2840 sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2841 }
2843 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2844 if (desktop == NULL)
2845 return;
2847 SPDocument *doc = sp_desktop_document(desktop);
2848 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2849 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2851 // check if something is selected
2852 if (selection->isEmpty()) {
2853 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2854 return;
2855 }
2857 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2858 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2859 sp_document_ensure_up_to_date(doc);
2861 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2862 std::map<SPObject*,SPItem*> referenced_objects;
2863 // SPObject* refers to a group containing the clipped path or mask itself,
2864 // whereas SPItem* refers to the item being clipped or masked
2865 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2866 if (remove_original) {
2867 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2868 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2869 Inkscape::URIReference *uri_ref = NULL;
2871 if (apply_clip_path) {
2872 uri_ref = item->clip_ref;
2873 } else {
2874 uri_ref = item->mask_ref;
2875 }
2877 // collect distinct mask object (and associate with item to apply transform)
2878 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2879 referenced_objects[uri_ref->getObject()] = item;
2880 }
2881 }
2883 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2884 }
2886 // restore mask objects into a document
2887 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2888 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2889 GSList *items_to_move = NULL;
2890 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2891 // Collect all clipped paths and masks within a single group
2892 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2893 items_to_move = g_slist_prepend(items_to_move, copy);
2894 }
2896 if (!obj->isReferenced()) {
2897 // delete from defs if no other object references this mask
2898 obj->deleteObject(false);
2899 }
2901 // remember parent and position of the item to which the clippath/mask was applied
2902 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2903 gint pos = SP_OBJECT_REPR((*it).second)->position();
2905 // Iterate through all clipped paths / masks
2906 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2907 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2909 // insert into parent, restore pos
2910 parent->appendChild(repr);
2911 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2913 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
2914 selection->add(repr);
2916 // transform mask, so it is moved the same spot where mask was applied
2917 Geom::Matrix transform(mask_item->transform);
2918 transform *= (*it).second->transform;
2919 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2920 }
2922 g_slist_free(items_to_move);
2923 }
2925 if (apply_clip_path)
2926 sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2927 else
2928 sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2929 }
2931 /**
2932 * \param with_margins margins defined in the xml under <sodipodi:namedview>
2933 * "fit-margin-..." attributes. See SPDocument::fitToRect.
2934 * \return true if an undoable change should be recorded.
2935 */
2936 bool
2937 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
2938 {
2939 g_return_val_if_fail(desktop != NULL, false);
2940 SPDocument *doc = sp_desktop_document(desktop);
2942 g_return_val_if_fail(doc != NULL, false);
2943 g_return_val_if_fail(desktop->selection != NULL, false);
2945 if (desktop->selection->isEmpty()) {
2946 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2947 return false;
2948 }
2949 Geom::OptRect const bbox(desktop->selection->bounds());
2950 if (bbox) {
2951 doc->fitToRect(*bbox, with_margins);
2952 return true;
2953 } else {
2954 return false;
2955 }
2956 }
2958 /**
2959 * Fit canvas to the bounding box of the selection, as an undoable action.
2960 */
2961 void
2962 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2963 {
2964 if (fit_canvas_to_selection(desktop)) {
2965 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2966 _("Fit Page to Selection"));
2967 }
2968 }
2970 /**
2971 * \param with_margins margins defined in the xml under <sodipodi:namedview>
2972 * "fit-margin-..." attributes. See SPDocument::fitToRect.
2973 */
2974 bool
2975 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
2976 {
2977 g_return_val_if_fail(doc != NULL, false);
2979 sp_document_ensure_up_to_date(doc);
2980 SPItem const *const root = SP_ITEM(doc->root);
2981 Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2982 if (bbox) {
2983 doc->fitToRect(*bbox, with_margins);
2984 return true;
2985 } else {
2986 return false;
2987 }
2988 }
2990 void
2991 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2992 {
2993 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2994 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2995 _("Fit Page to Drawing"));
2996 }
2997 }
2999 /**
3000 * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3001 * "fit-margin-..." attributes. See SPDocument::fitToRect and
3002 * ui/dialog/page-sizer.
3003 */
3004 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3005 g_return_if_fail(desktop != NULL);
3006 SPDocument *doc = sp_desktop_document(desktop);
3008 g_return_if_fail(doc != NULL);
3009 g_return_if_fail(desktop->selection != NULL);
3011 bool const changed = ( desktop->selection->isEmpty()
3012 ? fit_canvas_to_drawing(doc, true)
3013 : fit_canvas_to_selection(desktop, true) );
3014 if (changed) {
3015 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3016 _("Fit Page to Selection or Drawing"));
3017 }
3018 };
3020 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3021 // don't operate on layers
3022 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3023 f(SP_ITEM(root), desktop);
3024 }
3025 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3026 //don't recurse into locked layers
3027 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3028 itemtree_map(f, iter, desktop);
3029 }
3030 }
3031 }
3033 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3034 if (item->isLocked()) {
3035 item->setLocked(FALSE);
3036 }
3037 }
3039 static void unhide(SPItem *item, SPDesktop *desktop) {
3040 if (desktop->itemIsHidden(item)) {
3041 item->setExplicitlyHidden(FALSE);
3042 }
3043 }
3045 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3046 if (!dt) return;
3048 SPObject *root;
3049 if (layer_only) {
3050 root = dt->currentLayer();
3051 } else {
3052 root = dt->currentRoot();
3053 }
3055 itemtree_map(f, root, dt);
3056 }
3058 void unlock_all(SPDesktop *dt) {
3059 process_all(&unlock, dt, true);
3060 }
3062 void unlock_all_in_all_layers(SPDesktop *dt) {
3063 process_all(&unlock, dt, false);
3064 }
3066 void unhide_all(SPDesktop *dt) {
3067 process_all(&unhide, dt, true);
3068 }
3070 void unhide_all_in_all_layers(SPDesktop *dt) {
3071 process_all(&unhide, dt, false);
3072 }
3075 /*
3076 Local Variables:
3077 mode:c++
3078 c-file-style:"stroustrup"
3079 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3080 indent-tabs-mode:nil
3081 fill-column:99
3082 End:
3083 */
3084 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :