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 "unit-constants.h"
80 #include "xml/simple-document.h"
81 #include "sp-filter-reference.h"
82 #include "gradient-drag.h"
83 #include "uri-references.h"
84 #include "libnr/nr-convert2geom.h"
85 #include "display/curve.h"
86 #include "display/canvas-bpath.h"
87 #include "inkscape-private.h"
89 // For clippath editing
90 #include "tools-switch.h"
91 #include "shape-editor.h"
92 #include "node-context.h"
93 #include "nodepath.h"
95 #include "ui/clipboard.h"
97 using Geom::X;
98 using Geom::Y;
100 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
101 because the layer manipulation code uses them. It should be rewritten specifically
102 for that purpose. */
104 /**
105 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
106 * then prepends the copy to 'clip'.
107 */
108 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
109 {
110 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
112 // copy complete inherited style
113 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
114 sp_repr_css_set(copy, css, "style");
115 sp_repr_css_attr_unref(css);
117 // write the complete accumulated transform passed to us
118 // (we're dealing with unattached repr, so we write to its attr
119 // instead of using sp_item_set_transform)
120 gchar *affinestr=sp_svg_transform_write(full_t);
121 copy->setAttribute("transform", affinestr);
122 g_free(affinestr);
124 *clip = g_slist_prepend(*clip, copy);
125 }
127 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
128 {
129 // Sort items:
130 GSList *sorted_items = g_slist_copy((GSList *) items);
131 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
133 // Copy item reprs:
134 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
135 sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
136 }
138 *clip = g_slist_reverse(*clip);
139 g_slist_free((GSList *) sorted_items);
140 }
142 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
143 {
144 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
146 GSList *copied = NULL;
147 // add objects to document
148 for (GSList *l = *clip; l != NULL; l = l->next) {
149 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
150 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
152 // premultiply the item transform by the accumulated parent transform in the paste layer
153 Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
154 if (!local.isIdentity()) {
155 gchar const *t_str = copy->attribute("transform");
156 Geom::Matrix item_t(Geom::identity());
157 if (t_str)
158 sp_svg_transform_read(t_str, &item_t);
159 item_t *= local.inverse();
160 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
161 gchar *affinestr=sp_svg_transform_write(item_t);
162 copy->setAttribute("transform", affinestr);
163 g_free(affinestr);
164 }
166 parent->appendChildRepr(copy);
167 copied = g_slist_prepend(copied, copy);
168 Inkscape::GC::release(copy);
169 }
170 return copied;
171 }
173 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
174 {
175 for (GSList const *i = items ; i ; i = i->next ) {
176 sp_object_ref((SPObject *)i->data, NULL);
177 }
178 for (GSList const *i = items; i != NULL; i = i->next) {
179 SPItem *item = (SPItem *) i->data;
180 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
181 sp_object_unref((SPObject *)item, NULL);
182 }
183 }
186 void sp_selection_delete(SPDesktop *desktop)
187 {
188 if (desktop == NULL) {
189 return;
190 }
192 if (tools_isactive(desktop, TOOLS_TEXT))
193 if (sp_text_delete_selection(desktop->event_context)) {
194 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
195 _("Delete text"));
196 return;
197 }
199 Inkscape::Selection *selection = sp_desktop_selection(desktop);
201 // check if something is selected
202 if (selection->isEmpty()) {
203 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
204 return;
205 }
207 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
208 selection->clear();
209 sp_selection_delete_impl(selected);
210 g_slist_free((GSList *) selected);
212 /* a tool may have set up private information in it's selection context
213 * that depends on desktop items. I think the only sane way to deal with
214 * this currently is to reset the current tool, which will reset it's
215 * associated selection context. For example: deleting an object
216 * while moving it around the canvas.
217 */
218 tools_switch( desktop, tools_active( desktop ) );
220 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
221 _("Delete"));
222 }
224 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
225 {
226 if (!obj)
227 return;
229 ids.push_back(SP_OBJECT_ID(obj));
231 if (SP_IS_GROUP(obj)) {
232 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
233 add_ids_recursive(ids, child);
234 }
235 }
236 }
238 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
239 {
240 if (desktop == NULL)
241 return;
243 SPDocument *doc = desktop->doc();
244 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
245 Inkscape::Selection *selection = sp_desktop_selection(desktop);
247 // check if something is selected
248 if (selection->isEmpty()) {
249 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
250 return;
251 }
253 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
255 selection->clear();
257 // sorting items from different parents sorts each parent's subset without possibly mixing
258 // them, just what we need
259 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
261 GSList *newsel = NULL;
263 std::vector<const gchar *> old_ids;
264 std::vector<const gchar *> new_ids;
265 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
266 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
268 while (reprs) {
269 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
270 Inkscape::XML::Node *parent = old_repr->parent();
271 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
273 parent->appendChild(copy);
275 if (relink_clones) {
276 SPObject *old_obj = doc->getObjectByRepr(old_repr);
277 SPObject *new_obj = doc->getObjectByRepr(copy);
278 add_ids_recursive(old_ids, old_obj);
279 add_ids_recursive(new_ids, new_obj);
280 }
282 newsel = g_slist_prepend(newsel, copy);
283 reprs = g_slist_remove(reprs, reprs->data);
284 Inkscape::GC::release(copy);
285 }
287 if (relink_clones) {
289 g_assert(old_ids.size() == new_ids.size());
291 for (unsigned int i = 0; i < old_ids.size(); i++) {
292 const gchar *id = old_ids[i];
293 SPObject *old_clone = doc->getObjectById(id);
294 if (SP_IS_USE(old_clone)) {
295 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
296 if (!orig) // orphaned
297 continue;
298 for (unsigned int j = 0; j < old_ids.size(); j++) {
299 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
300 // we have both orig and clone in selection, relink
301 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
302 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
303 SPObject *new_clone = doc->getObjectById(new_ids[i]);
304 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
305 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
306 g_free(newref);
307 }
308 }
309 }
310 }
311 }
314 if ( !suppressDone ) {
315 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
316 _("Duplicate"));
317 }
319 selection->setReprList(newsel);
321 g_slist_free(newsel);
322 }
324 void sp_edit_clear_all(SPDesktop *dt)
325 {
326 if (!dt)
327 return;
329 SPDocument *doc = sp_desktop_document(dt);
330 sp_desktop_selection(dt)->clear();
332 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
333 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
335 while (items) {
336 SP_OBJECT(items->data)->deleteObject();
337 items = g_slist_remove(items, items->data);
338 }
340 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
341 _("Delete all"));
342 }
344 GSList *
345 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
346 {
347 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
348 if (SP_IS_ITEM(child) &&
349 !desktop->isLayer(SP_ITEM(child)) &&
350 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
351 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
352 (!exclude || !g_slist_find((GSList *) exclude, child))
353 )
354 {
355 list = g_slist_prepend(list, SP_ITEM(child));
356 }
358 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
359 list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
360 }
361 }
363 return list;
364 }
366 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
367 {
368 if (!dt)
369 return;
371 Inkscape::Selection *selection = sp_desktop_selection(dt);
373 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
375 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
376 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
377 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
378 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
380 GSList *items = NULL;
382 GSList const *exclude = NULL;
383 if (invert) {
384 exclude = selection->itemList();
385 }
387 if (force_all_layers)
388 inlayer = PREFS_SELECTION_ALL;
390 switch (inlayer) {
391 case PREFS_SELECTION_LAYER: {
392 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
393 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
394 return;
396 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
398 for (GSList *i = all_items; i; i = i->next) {
399 SPItem *item = SP_ITEM(i->data);
401 if (item && (!onlysensitive || !item->isLocked())) {
402 if (!onlyvisible || !dt->itemIsHidden(item)) {
403 if (!dt->isLayer(item)) {
404 if (!invert || !g_slist_find((GSList *) exclude, item)) {
405 items = g_slist_prepend(items, item); // leave it in the list
406 }
407 }
408 }
409 }
410 }
412 g_slist_free(all_items);
413 break;
414 }
415 case PREFS_SELECTION_LAYER_RECURSIVE: {
416 items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
417 break;
418 }
419 default: {
420 items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
421 break;
422 }
423 }
425 selection->setList(items);
427 if (items) {
428 g_slist_free(items);
429 }
430 }
432 void sp_edit_select_all(SPDesktop *desktop)
433 {
434 sp_edit_select_all_full(desktop, false, false);
435 }
437 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
438 {
439 sp_edit_select_all_full(desktop, true, false);
440 }
442 void sp_edit_invert(SPDesktop *desktop)
443 {
444 sp_edit_select_all_full(desktop, false, true);
445 }
447 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
448 {
449 sp_edit_select_all_full(desktop, true, true);
450 }
452 void sp_selection_group(SPDesktop *desktop)
453 {
454 if (desktop == NULL)
455 return;
457 SPDocument *doc = sp_desktop_document(desktop);
458 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
460 Inkscape::Selection *selection = sp_desktop_selection(desktop);
462 // Check if something is selected.
463 if (selection->isEmpty()) {
464 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
465 return;
466 }
468 GSList const *l = (GSList *) selection->reprList();
470 GSList *p = g_slist_copy((GSList *) l);
472 selection->clear();
474 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
476 // Remember the position and parent of the topmost object.
477 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
478 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
480 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
482 while (p) {
483 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
485 if (current->parent() == topmost_parent) {
486 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
487 sp_repr_unparent(current);
488 group->appendChild(spnew);
489 Inkscape::GC::release(spnew);
490 topmost --; // only reduce count for those items deleted from topmost_parent
491 } else { // move it to topmost_parent first
492 GSList *temp_clip = NULL;
494 // At this point, current may already have no item, due to its being a clone whose original is already moved away
495 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
496 gchar const *t_str = current->attribute("transform");
497 Geom::Matrix item_t(Geom::identity());
498 if (t_str)
499 sp_svg_transform_read(t_str, &item_t);
500 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
501 // FIXME: when moving both clone and original from a transformed group (either by
502 // grouping into another parent, or by cut/paste) the transform from the original's
503 // parent becomes embedded into original itself, and this affects its clones. Fix
504 // this by remembering the transform diffs we write to each item into an array and
505 // then, if this is clone, looking up its original in that array and pre-multiplying
506 // it by the inverse of that original's transform diff.
508 sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
509 sp_repr_unparent(current);
511 // paste into topmost_parent (temporarily)
512 GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
513 if (temp_clip) g_slist_free(temp_clip);
514 if (copied) { // if success,
515 // take pasted object (now in topmost_parent)
516 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
517 // make a copy
518 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
519 // remove pasted
520 sp_repr_unparent(in_topmost);
521 // put its copy into group
522 group->appendChild(spnew);
523 Inkscape::GC::release(spnew);
524 g_slist_free(copied);
525 }
526 }
527 p = g_slist_remove(p, current);
528 }
530 // Add the new group to the topmost members' parent
531 topmost_parent->appendChild(group);
533 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
534 group->setPosition(topmost + 1);
536 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
537 _("Group"));
539 selection->set(group);
540 Inkscape::GC::release(group);
541 }
543 void sp_selection_ungroup(SPDesktop *desktop)
544 {
545 if (desktop == NULL)
546 return;
548 Inkscape::Selection *selection = sp_desktop_selection(desktop);
550 if (selection->isEmpty()) {
551 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
552 return;
553 }
555 GSList *items = g_slist_copy((GSList *) selection->itemList());
556 selection->clear();
558 // Get a copy of current selection.
559 GSList *new_select = NULL;
560 bool ungrouped = false;
561 for (GSList *i = items;
562 i != NULL;
563 i = i->next)
564 {
565 SPItem *group = (SPItem *) i->data;
567 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
568 if (!SP_IS_OBJECT(group)) {
569 continue;
570 }
572 /* We do not allow ungrouping <svg> etc. (lauris) */
573 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
574 // keep the non-group item in the new selection
575 selection->add(group);
576 continue;
577 }
579 GSList *children = NULL;
580 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
581 sp_item_group_ungroup(SP_GROUP(group), &children, false);
582 ungrouped = true;
583 // Add ungrouped items to the new selection.
584 new_select = g_slist_concat(new_select, children);
585 }
587 if (new_select) { // Set new selection.
588 selection->addList(new_select);
589 g_slist_free(new_select);
590 }
591 if (!ungrouped) {
592 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
593 }
595 g_slist_free(items);
597 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
598 _("Ungroup"));
599 }
601 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
602 GSList *
603 sp_degroup_list(GSList *items)
604 {
605 GSList *out = NULL;
606 bool has_groups = false;
607 for (GSList *item = items; item; item = item->next) {
608 if (!SP_IS_GROUP(item->data)) {
609 out = g_slist_prepend(out, item->data);
610 } else {
611 has_groups = true;
612 GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
613 for (GSList *member = members; member; member = member->next) {
614 out = g_slist_prepend(out, member->data);
615 }
616 g_slist_free(members);
617 }
618 }
619 out = g_slist_reverse(out);
620 g_slist_free(items);
622 if (has_groups) { // recurse if we unwrapped a group - it may have contained others
623 out = sp_degroup_list(out);
624 }
626 return out;
627 }
630 /** If items in the list have a common parent, return it, otherwise return NULL */
631 static SPGroup *
632 sp_item_list_common_parent_group(GSList const *items)
633 {
634 if (!items) {
635 return NULL;
636 }
637 SPObject *parent = SP_OBJECT_PARENT(items->data);
638 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
639 if (!SP_IS_GROUP(parent)) {
640 return NULL;
641 }
642 for (items = items->next; items; items = items->next) {
643 if (SP_OBJECT_PARENT(items->data) != parent) {
644 return NULL;
645 }
646 }
648 return SP_GROUP(parent);
649 }
651 /** Finds out the minimum common bbox of the selected items. */
652 static Geom::OptRect
653 enclose_items(GSList const *items)
654 {
655 g_assert(items != NULL);
657 Geom::OptRect r;
658 for (GSList const *i = items; i; i = i->next) {
659 r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
660 }
661 return r;
662 }
664 SPObject *
665 prev_sibling(SPObject *child)
666 {
667 SPObject *parent = SP_OBJECT_PARENT(child);
668 if (!SP_IS_GROUP(parent)) {
669 return NULL;
670 }
671 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
672 if (i->next == child)
673 return i;
674 }
675 return NULL;
676 }
678 void
679 sp_selection_raise(SPDesktop *desktop)
680 {
681 if (!desktop)
682 return;
684 Inkscape::Selection *selection = sp_desktop_selection(desktop);
686 GSList const *items = (GSList *) selection->itemList();
687 if (!items) {
688 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
689 return;
690 }
692 SPGroup const *group = sp_item_list_common_parent_group(items);
693 if (!group) {
694 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
695 return;
696 }
698 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
700 /* Construct reverse-ordered list of selected children. */
701 GSList *rev = g_slist_copy((GSList *) items);
702 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
704 // Determine the common bbox of the selected items.
705 Geom::OptRect selected = enclose_items(items);
707 // Iterate over all objects in the selection (starting from top).
708 if (selected) {
709 while (rev) {
710 SPObject *child = SP_OBJECT(rev->data);
711 // for each selected object, find the next sibling
712 for (SPObject *newref = child->next; newref; newref = newref->next) {
713 // if the sibling is an item AND overlaps our selection,
714 if (SP_IS_ITEM(newref)) {
715 Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
716 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
717 // AND if it's not one of our selected objects,
718 if (!g_slist_find((GSList *) items, newref)) {
719 // move the selected object after that sibling
720 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
721 }
722 break;
723 }
724 }
725 }
726 rev = g_slist_remove(rev, child);
727 }
728 } else {
729 g_slist_free(rev);
730 }
732 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
733 //TRANSLATORS: only translate "string" in "context|string".
734 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
735 // "Raise" means "to raise an object" in the undo history
736 Q_("undo_action|Raise"));
737 }
739 void sp_selection_raise_to_top(SPDesktop *desktop)
740 {
741 if (desktop == NULL)
742 return;
744 SPDocument *document = sp_desktop_document(desktop);
745 Inkscape::Selection *selection = sp_desktop_selection(desktop);
747 if (selection->isEmpty()) {
748 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
749 return;
750 }
752 GSList const *items = (GSList *) selection->itemList();
754 SPGroup const *group = sp_item_list_common_parent_group(items);
755 if (!group) {
756 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
757 return;
758 }
760 GSList *rl = g_slist_copy((GSList *) selection->reprList());
761 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
763 for (GSList *l = rl; l != NULL; l = l->next) {
764 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
765 repr->setPosition(-1);
766 }
768 g_slist_free(rl);
770 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
771 _("Raise to top"));
772 }
774 void
775 sp_selection_lower(SPDesktop *desktop)
776 {
777 if (desktop == NULL)
778 return;
780 Inkscape::Selection *selection = sp_desktop_selection(desktop);
782 GSList const *items = (GSList *) selection->itemList();
783 if (!items) {
784 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
785 return;
786 }
788 SPGroup const *group = sp_item_list_common_parent_group(items);
789 if (!group) {
790 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
791 return;
792 }
794 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
796 // Determine the common bbox of the selected items.
797 Geom::OptRect selected = enclose_items(items);
799 /* Construct direct-ordered list of selected children. */
800 GSList *rev = g_slist_copy((GSList *) items);
801 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
802 rev = g_slist_reverse(rev);
804 // Iterate over all objects in the selection (starting from top).
805 if (selected) {
806 while (rev) {
807 SPObject *child = SP_OBJECT(rev->data);
808 // for each selected object, find the prev sibling
809 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
810 // if the sibling is an item AND overlaps our selection,
811 if (SP_IS_ITEM(newref)) {
812 Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
813 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
814 // AND if it's not one of our selected objects,
815 if (!g_slist_find((GSList *) items, newref)) {
816 // move the selected object before that sibling
817 SPObject *put_after = prev_sibling(newref);
818 if (put_after)
819 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
820 else
821 SP_OBJECT_REPR(child)->setPosition(0);
822 }
823 break;
824 }
825 }
826 }
827 rev = g_slist_remove(rev, child);
828 }
829 } else {
830 g_slist_free(rev);
831 }
833 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
834 _("Lower"));
835 }
837 void sp_selection_lower_to_bottom(SPDesktop *desktop)
838 {
839 if (desktop == NULL)
840 return;
842 SPDocument *document = sp_desktop_document(desktop);
843 Inkscape::Selection *selection = sp_desktop_selection(desktop);
845 if (selection->isEmpty()) {
846 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
847 return;
848 }
850 GSList const *items = (GSList *) selection->itemList();
852 SPGroup const *group = sp_item_list_common_parent_group(items);
853 if (!group) {
854 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
855 return;
856 }
858 GSList *rl;
859 rl = g_slist_copy((GSList *) selection->reprList());
860 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
861 rl = g_slist_reverse(rl);
863 for (GSList *l = rl; l != NULL; l = l->next) {
864 gint minpos;
865 SPObject *pp, *pc;
866 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
867 pp = document->getObjectByRepr(sp_repr_parent(repr));
868 minpos = 0;
869 g_assert(SP_IS_GROUP(pp));
870 pc = sp_object_first_child(pp);
871 while (!SP_IS_ITEM(pc)) {
872 minpos += 1;
873 pc = pc->next;
874 }
875 repr->setPosition(minpos);
876 }
878 g_slist_free(rl);
880 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
881 _("Lower to bottom"));
882 }
884 void
885 sp_undo(SPDesktop *desktop, SPDocument *)
886 {
887 if (!sp_document_undo(sp_desktop_document(desktop)))
888 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
889 }
891 void
892 sp_redo(SPDesktop *desktop, SPDocument *)
893 {
894 if (!sp_document_redo(sp_desktop_document(desktop)))
895 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
896 }
898 void sp_selection_cut(SPDesktop *desktop)
899 {
900 sp_selection_copy();
901 sp_selection_delete(desktop);
902 }
904 /**
905 * \pre item != NULL
906 */
907 SPCSSAttr *
908 take_style_from_item(SPItem *item)
909 {
910 // write the complete cascaded style, context-free
911 SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
912 if (css == NULL)
913 return NULL;
915 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
916 (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
917 // if this is a text with exactly one tspan child, merge the style of that tspan as well
918 // If this is a group, merge the style of its topmost (last) child with style
919 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
920 if (SP_OBJECT_STYLE(last_element) != NULL) {
921 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
922 if (temp) {
923 sp_repr_css_merge(css, temp);
924 sp_repr_css_attr_unref(temp);
925 }
926 break;
927 }
928 }
929 }
930 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
931 // do not copy text properties from non-text objects, it's confusing
932 css = sp_css_attr_unset_text(css);
933 }
935 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
936 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
937 if (ex != 1.0) {
938 css = sp_css_attr_scale(css, ex);
939 }
941 return css;
942 }
945 void sp_selection_copy()
946 {
947 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
948 cm->copy();
949 }
951 void sp_selection_paste(SPDesktop *desktop, bool in_place)
952 {
953 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
954 if (cm->paste(in_place))
955 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
956 }
958 void sp_selection_paste_style(SPDesktop *desktop)
959 {
960 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
961 if (cm->pasteStyle())
962 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
963 }
966 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
967 {
968 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
969 if (cm->pastePathEffect())
970 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
971 _("Paste live path effect"));
972 }
975 void sp_selection_remove_livepatheffect_impl(SPItem *item)
976 {
977 if ( item && SP_IS_LPE_ITEM(item) &&
978 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
979 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
980 }
981 }
983 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
984 {
985 if (desktop == NULL) return;
987 Inkscape::Selection *selection = sp_desktop_selection(desktop);
989 // check if something is selected
990 if (selection->isEmpty()) {
991 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
992 return;
993 }
995 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
996 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
998 sp_selection_remove_livepatheffect_impl(item);
1000 }
1002 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1003 _("Remove live path effect"));
1004 }
1006 void sp_selection_remove_filter(SPDesktop *desktop)
1007 {
1008 if (desktop == NULL) return;
1010 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1012 // check if something is selected
1013 if (selection->isEmpty()) {
1014 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1015 return;
1016 }
1018 SPCSSAttr *css = sp_repr_css_attr_new();
1019 sp_repr_css_unset_property(css, "filter");
1020 sp_desktop_set_style(desktop, css);
1021 sp_repr_css_attr_unref(css);
1023 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1024 _("Remove filter"));
1025 }
1028 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1029 {
1030 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1031 if (cm->pasteSize(false, apply_x, apply_y))
1032 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1033 _("Paste size"));
1034 }
1036 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1037 {
1038 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1039 if (cm->pasteSize(true, apply_x, apply_y))
1040 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1041 _("Paste size separately"));
1042 }
1044 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1045 {
1046 Inkscape::Selection *selection = sp_desktop_selection(dt);
1048 // check if something is selected
1049 if (selection->isEmpty()) {
1050 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1051 return;
1052 }
1054 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1056 bool no_more = false; // Set to true, if no more layers above
1057 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1058 if (next) {
1059 GSList *temp_clip = NULL;
1060 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1061 sp_selection_delete_impl(items, false, false);
1062 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1063 GSList *copied;
1064 if (next) {
1065 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1066 } else {
1067 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1068 no_more = true;
1069 }
1070 selection->setReprList((GSList const *) copied);
1071 g_slist_free(copied);
1072 if (temp_clip) g_slist_free(temp_clip);
1073 if (next) dt->setCurrentLayer(next);
1074 if ( !suppressDone ) {
1075 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1076 _("Raise to next layer"));
1077 }
1078 } else {
1079 no_more = true;
1080 }
1082 if (no_more) {
1083 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1084 }
1086 g_slist_free((GSList *) items);
1087 }
1089 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1090 {
1091 Inkscape::Selection *selection = sp_desktop_selection(dt);
1093 // check if something is selected
1094 if (selection->isEmpty()) {
1095 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1096 return;
1097 }
1099 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1101 bool no_more = false; // Set to true, if no more layers below
1102 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1103 if (next) {
1104 GSList *temp_clip = NULL;
1105 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
1106 sp_selection_delete_impl(items, false, false);
1107 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1108 GSList *copied;
1109 if (next) {
1110 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1111 } else {
1112 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1113 no_more = true;
1114 }
1115 selection->setReprList((GSList const *) copied);
1116 g_slist_free(copied);
1117 if (temp_clip) g_slist_free(temp_clip);
1118 if (next) dt->setCurrentLayer(next);
1119 if ( !suppressDone ) {
1120 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1121 _("Lower to previous layer"));
1122 }
1123 } else {
1124 no_more = true;
1125 }
1127 if (no_more) {
1128 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1129 }
1131 g_slist_free((GSList *) items);
1132 }
1134 bool
1135 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1136 {
1137 bool contains_original = false;
1139 bool is_use = SP_IS_USE(item);
1140 SPItem *item_use = item;
1141 SPItem *item_use_first = item;
1142 while (is_use && item_use && !contains_original)
1143 {
1144 item_use = sp_use_get_original(SP_USE(item_use));
1145 contains_original |= selection->includes(item_use);
1146 if (item_use == item_use_first)
1147 break;
1148 is_use = SP_IS_USE(item_use);
1149 }
1151 // If it's a tref, check whether the object containing the character
1152 // data is part of the selection
1153 if (!contains_original && SP_IS_TREF(item)) {
1154 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1155 }
1157 return contains_original;
1158 }
1161 bool
1162 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1163 {
1164 bool clone_with_original = false;
1165 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1166 SPItem *item = SP_ITEM(l->data);
1167 clone_with_original |= selection_contains_original(item, selection);
1168 if (clone_with_original)
1169 break;
1170 }
1171 return clone_with_original;
1172 }
1175 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1176 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1177 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1178 that case, items are already in the new position, but the repr is in the old, and this function
1179 then simply updates the repr from item->transform.
1180 */
1181 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1182 {
1183 if (selection->isEmpty())
1184 return;
1186 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1187 SPItem *item = SP_ITEM(l->data);
1189 Geom::Point old_center(0,0);
1190 if (set_i2d && item->isCenterSet())
1191 old_center = item->getCenter();
1193 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1194 At the time of writing, this is the only place to re-enable. */
1195 sp_item_update_cns(*item, selection->desktop());
1196 #endif
1198 // we're moving both a clone and its original or any ancestor in clone chain?
1199 bool transform_clone_with_original = selection_contains_original(item, selection);
1200 // ...both a text-on-path and its path?
1201 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)))) ));
1202 // ...both a flowtext and its frame?
1203 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)
1204 // ...both an offset and its source?
1205 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1207 // If we're moving a connector, we want to detach it
1208 // from shapes that aren't part of the selection, but
1209 // leave it attached if they are
1210 if (cc_item_is_connector(item)) {
1211 SPItem *attItem[2];
1212 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1214 for (int n = 0; n < 2; ++n) {
1215 if (!selection->includes(attItem[n])) {
1216 sp_conn_end_detach(item, n);
1217 }
1218 }
1219 }
1221 // "clones are unmoved when original is moved" preference
1222 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1223 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1224 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1225 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1227 /* If this is a clone and it's selected along with its original, do not move it;
1228 * it will feel the transform of its original and respond to it itself.
1229 * Without this, a clone is doubly transformed, very unintuitive.
1230 *
1231 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1232 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1233 * Same for linked offset if we are also moving its source: do not move it. */
1234 if (transform_textpath_with_path || transform_offset_with_source) {
1235 // Restore item->transform field from the repr, in case it was changed by seltrans.
1236 sp_object_read_attr(SP_OBJECT(item), "transform");
1237 } else if (transform_flowtext_with_frame) {
1238 // apply the inverse of the region's transform to the <use> so that the flow remains
1239 // the same (even though the output itself gets transformed)
1240 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1241 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1242 continue;
1243 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1244 if (!SP_IS_USE(use)) continue;
1245 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1246 }
1247 }
1248 } else if (transform_clone_with_original) {
1249 // We are transforming a clone along with its original. The below matrix juggling is
1250 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1251 // transform and its move compensation are both cancelled out.
1253 // restore item->transform field from the repr, in case it was changed by seltrans
1254 sp_object_read_attr(SP_OBJECT(item), "transform");
1256 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1257 Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1258 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1259 Geom::Matrix t_inv = t.inverse();
1260 Geom::Matrix result = t_inv * item->transform * t;
1262 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1263 // we need to cancel out the move compensation, too
1265 // find out the clone move, same as in sp_use_move_compensate
1266 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1267 Geom::Matrix clone_move = parent.inverse() * t * parent;
1269 if (prefs_parallel) {
1270 Geom::Matrix move = result * clone_move * t_inv;
1271 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1273 } else if (prefs_unmoved) {
1274 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1275 // clone_move = Geom::identity();
1276 Geom::Matrix move = result * clone_move;
1277 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1278 }
1280 } else {
1281 // just apply the result
1282 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1283 }
1285 } else {
1286 if (set_i2d) {
1287 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1288 }
1289 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1290 }
1292 // if we're moving the actual object, not just updating the repr, we can transform the
1293 // center by the same matrix (only necessary for non-translations)
1294 if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1295 item->setCenter(old_center * affine);
1296 SP_OBJECT(item)->updateRepr();
1297 }
1298 }
1299 }
1301 void sp_selection_remove_transform(SPDesktop *desktop)
1302 {
1303 if (desktop == NULL)
1304 return;
1306 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1308 GSList const *l = (GSList *) selection->reprList();
1309 while (l != NULL) {
1310 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1311 l = l->next;
1312 }
1314 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1315 _("Remove transform"));
1316 }
1318 void
1319 sp_selection_scale_absolute(Inkscape::Selection *selection,
1320 double const x0, double const x1,
1321 double const y0, double const y1)
1322 {
1323 if (selection->isEmpty())
1324 return;
1326 Geom::OptRect const bbox(selection->bounds());
1327 if ( !bbox ) {
1328 return;
1329 }
1331 Geom::Translate const p2o(-bbox->min());
1333 Geom::Scale const newSize(x1 - x0,
1334 y1 - y0);
1335 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1336 Geom::Translate const o2n(x0, y0);
1337 Geom::Matrix const final( p2o * scale * o2n );
1339 sp_selection_apply_affine(selection, final);
1340 }
1343 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1344 {
1345 if (selection->isEmpty())
1346 return;
1348 Geom::OptRect const bbox(selection->bounds());
1350 if ( !bbox ) {
1351 return;
1352 }
1354 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1355 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1356 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1357 {
1358 return;
1359 }
1361 Geom::Translate const n2d(-align);
1362 Geom::Translate const d2n(align);
1363 Geom::Matrix const final( n2d * scale * d2n );
1364 sp_selection_apply_affine(selection, final);
1365 }
1367 void
1368 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1369 {
1370 Geom::Translate const d2n(center);
1371 Geom::Translate const n2d(-center);
1372 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1373 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1374 sp_selection_apply_affine(selection, final);
1375 }
1377 void
1378 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1379 {
1380 Geom::Translate const d2n(align);
1381 Geom::Translate const n2d(-align);
1382 Geom::Matrix const skew(1, dy,
1383 dx, 1,
1384 0, 0);
1385 Geom::Matrix const final( n2d * skew * d2n );
1386 sp_selection_apply_affine(selection, final);
1387 }
1389 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1390 {
1391 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1392 }
1394 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1395 {
1396 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1397 }
1399 /**
1400 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1401 */
1402 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1403 {
1404 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1406 if (selection->isEmpty())
1407 return;
1409 GSList const *l = selection->itemList();
1410 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1411 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1412 SPItem *item = SP_ITEM(l2->data);
1413 sp_item_rotate_rel(item, rot_90);
1414 }
1416 sp_document_done(sp_desktop_document(desktop),
1417 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1418 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1419 }
1421 void
1422 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1423 {
1424 if (selection->isEmpty())
1425 return;
1427 boost::optional<Geom::Point> center = selection->center();
1428 if (!center) {
1429 return;
1430 }
1432 sp_selection_rotate_relative(selection, *center, angle_degrees);
1434 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1435 ( ( angle_degrees > 0 )
1436 ? "selector:rotate:ccw"
1437 : "selector:rotate:cw" ),
1438 SP_VERB_CONTEXT_SELECT,
1439 _("Rotate"));
1440 }
1442 // helper function:
1443 static
1444 Geom::Point
1445 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1446 Geom::Point m = r.midpoint();
1447 unsigned i = 0;
1448 if (p[X] < m[X]) {
1449 i = 1;
1450 }
1451 if (p[Y] < m[Y]) {
1452 i = 3 - i;
1453 }
1454 return r.corner(i);
1455 }
1457 /**
1458 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1459 */
1460 void
1461 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1462 {
1463 if (selection->isEmpty())
1464 return;
1466 Geom::OptRect const bbox(selection->bounds());
1467 boost::optional<Geom::Point> center = selection->center();
1469 if ( !bbox || !center ) {
1470 return;
1471 }
1473 gdouble const zoom = selection->desktop()->current_zoom();
1474 gdouble const zmove = angle / zoom;
1475 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1477 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1479 sp_selection_rotate_relative(selection, *center, zangle);
1481 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1482 ( (angle > 0)
1483 ? "selector:rotate:ccw"
1484 : "selector:rotate:cw" ),
1485 SP_VERB_CONTEXT_SELECT,
1486 _("Rotate by pixels"));
1487 }
1489 void
1490 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1491 {
1492 if (selection->isEmpty())
1493 return;
1495 Geom::OptRect const bbox(selection->bounds());
1496 if (!bbox) {
1497 return;
1498 }
1500 Geom::Point const center(bbox->midpoint());
1502 // you can't scale "do nizhe pola" (below zero)
1503 double const max_len = bbox->maxExtent();
1504 if ( max_len + grow <= 1e-3 ) {
1505 return;
1506 }
1508 double const times = 1.0 + grow / max_len;
1509 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1511 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1512 ( (grow > 0)
1513 ? "selector:scale:larger"
1514 : "selector:scale:smaller" ),
1515 SP_VERB_CONTEXT_SELECT,
1516 _("Scale"));
1517 }
1519 void
1520 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1521 {
1522 sp_selection_scale(selection,
1523 grow_pixels / selection->desktop()->current_zoom());
1524 }
1526 void
1527 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1528 {
1529 if (selection->isEmpty())
1530 return;
1532 Geom::OptRect sel_bbox = selection->bounds();
1534 if (!sel_bbox) {
1535 return;
1536 }
1538 Geom::Point const center(sel_bbox->midpoint());
1539 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1540 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1541 _("Scale by whole factor"));
1542 }
1544 void
1545 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1546 {
1547 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1548 if (selection->isEmpty()) {
1549 return;
1550 }
1552 sp_selection_move_relative(selection, dx, dy);
1554 if (dx == 0) {
1555 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1556 _("Move vertically"));
1557 } else if (dy == 0) {
1558 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1559 _("Move horizontally"));
1560 } else {
1561 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1562 _("Move"));
1563 }
1564 }
1566 void
1567 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1568 {
1569 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1570 if (selection->isEmpty()) {
1571 return;
1572 }
1574 // same as sp_selection_move but divide deltas by zoom factor
1575 gdouble const zoom = desktop->current_zoom();
1576 gdouble const zdx = dx / zoom;
1577 gdouble const zdy = dy / zoom;
1578 sp_selection_move_relative(selection, zdx, zdy);
1580 if (dx == 0) {
1581 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1582 _("Move vertically by pixels"));
1583 } else if (dy == 0) {
1584 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1585 _("Move horizontally by pixels"));
1586 } else {
1587 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1588 _("Move"));
1589 }
1590 }
1592 namespace {
1594 template <typename D>
1595 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1596 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1598 template <typename D>
1599 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1600 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1602 struct Forward {
1603 typedef SPObject *Iterator;
1605 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1606 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1607 static void dispose(Iterator /*i*/) {}
1609 static SPObject *object(Iterator i) { return i; }
1610 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1611 };
1613 struct Reverse {
1614 typedef GSList *Iterator;
1616 static Iterator children(SPObject *o) {
1617 return make_list(o->firstChild(), NULL);
1618 }
1619 static Iterator siblings_after(SPObject *o) {
1620 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1621 }
1622 static void dispose(Iterator i) {
1623 g_slist_free(i);
1624 }
1626 static SPObject *object(Iterator i) {
1627 return reinterpret_cast<SPObject *>(i->data);
1628 }
1629 static Iterator next(Iterator i) { return i->next; }
1631 private:
1632 static GSList *make_list(SPObject *object, SPObject *limit) {
1633 GSList *list=NULL;
1634 while ( object != limit ) {
1635 list = g_slist_prepend(list, object);
1636 object = SP_OBJECT_NEXT(object);
1637 }
1638 return list;
1639 }
1640 };
1642 }
1644 void
1645 sp_selection_item_next(SPDesktop *desktop)
1646 {
1647 g_return_if_fail(desktop != NULL);
1648 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1650 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1651 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1652 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1653 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1655 SPObject *root;
1656 if (PREFS_SELECTION_ALL != inlayer) {
1657 root = selection->activeContext();
1658 } else {
1659 root = desktop->currentRoot();
1660 }
1662 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1664 if (item) {
1665 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1666 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1667 scroll_to_show_item(desktop, item);
1668 }
1669 }
1670 }
1672 void
1673 sp_selection_item_prev(SPDesktop *desktop)
1674 {
1675 SPDocument *document = sp_desktop_document(desktop);
1676 g_return_if_fail(document != NULL);
1677 g_return_if_fail(desktop != NULL);
1678 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1680 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1681 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1682 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1683 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1685 SPObject *root;
1686 if (PREFS_SELECTION_ALL != inlayer) {
1687 root = selection->activeContext();
1688 } else {
1689 root = desktop->currentRoot();
1690 }
1692 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1694 if (item) {
1695 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1696 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1697 scroll_to_show_item(desktop, item);
1698 }
1699 }
1700 }
1702 void sp_selection_next_patheffect_param(SPDesktop * dt)
1703 {
1704 if (!dt) return;
1706 Inkscape::Selection *selection = sp_desktop_selection(dt);
1707 if ( selection && !selection->isEmpty() ) {
1708 SPItem *item = selection->singleItem();
1709 if ( item && SP_IS_SHAPE(item)) {
1710 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1711 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1712 } else {
1713 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1714 }
1715 }
1716 }
1717 }
1719 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1720 {
1721 if (!dt) return;
1723 Inkscape::Selection *selection = sp_desktop_selection(dt);
1724 if ( selection && !selection->isEmpty() ) {
1725 SPItem *item = selection->singleItem();
1726 if ( item ) {
1727 SPObject *obj = NULL;
1728 if (clip)
1729 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1730 else
1731 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1733 if (obj) {
1734 // obj is a group object, the children are the actual clippers
1735 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1736 if ( SP_IS_ITEM(child) ) {
1737 // If not already in nodecontext, goto it!
1738 if (!tools_isactive(dt, TOOLS_NODES)) {
1739 tools_switch(dt, TOOLS_NODES);
1740 }
1742 ShapeEditor * shape_editor = dt->event_context->shape_editor;
1743 // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1744 shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1745 shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1746 Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1747 if (np) {
1748 // take colors from prefs (same as used in outline mode)
1749 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1750 np->helperpath_rgba = clip ?
1751 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) :
1752 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1753 np->helperpath_width = 1.0;
1754 sp_nodepath_show_helperpath(np, true);
1755 }
1756 break; // break out of for loop after 1st encountered item
1757 }
1758 }
1759 } else if (clip) {
1760 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1761 } else {
1762 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1763 }
1764 }
1765 }
1766 }
1769 namespace {
1771 template <typename D>
1772 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1773 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1774 {
1775 SPObject *current=root;
1776 while (items) {
1777 SPItem *item=SP_ITEM(items->data);
1778 if ( root->isAncestorOf(item) &&
1779 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1780 {
1781 current = item;
1782 break;
1783 }
1784 items = items->next;
1785 }
1787 GSList *path=NULL;
1788 while ( current != root ) {
1789 path = g_slist_prepend(path, current);
1790 current = SP_OBJECT_PARENT(current);
1791 }
1793 SPItem *next;
1794 // first, try from the current object
1795 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1796 g_slist_free(path);
1798 if (!next) { // if we ran out of objects, start over at the root
1799 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1800 }
1802 return next;
1803 }
1805 template <typename D>
1806 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1807 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1808 {
1809 typename D::Iterator children;
1810 typename D::Iterator iter;
1812 SPItem *found=NULL;
1814 if (path) {
1815 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1816 g_assert(SP_OBJECT_PARENT(object) == root);
1817 if (desktop->isLayer(object)) {
1818 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1819 }
1820 iter = children = D::siblings_after(object);
1821 } else {
1822 iter = children = D::children(root);
1823 }
1825 while ( iter && !found ) {
1826 SPObject *object=D::object(iter);
1827 if (desktop->isLayer(object)) {
1828 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1829 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1830 }
1831 } else if ( SP_IS_ITEM(object) &&
1832 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1833 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1834 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1835 !desktop->isLayer(SP_ITEM(object)) )
1836 {
1837 found = SP_ITEM(object);
1838 }
1839 iter = D::next(iter);
1840 }
1842 D::dispose(children);
1844 return found;
1845 }
1847 }
1849 /**
1850 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1851 * \a item.
1852 */
1853 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1854 {
1855 Geom::Rect dbox = desktop->get_display_area();
1856 Geom::OptRect sbox = sp_item_bbox_desktop(item);
1858 if ( sbox && dbox.contains(*sbox) == false ) {
1859 Geom::Point const s_dt = sbox->midpoint();
1860 Geom::Point const s_w = desktop->d2w(s_dt);
1861 Geom::Point const d_dt = dbox.midpoint();
1862 Geom::Point const d_w = desktop->d2w(d_dt);
1863 Geom::Point const moved_w( d_w - s_w );
1864 gint const dx = (gint) moved_w[X];
1865 gint const dy = (gint) moved_w[Y];
1866 desktop->scroll_world(dx, dy);
1867 }
1868 }
1871 void
1872 sp_selection_clone(SPDesktop *desktop)
1873 {
1874 if (desktop == NULL)
1875 return;
1877 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1879 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1881 // check if something is selected
1882 if (selection->isEmpty()) {
1883 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1884 return;
1885 }
1887 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1889 selection->clear();
1891 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1892 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1894 GSList *newsel = NULL;
1896 while (reprs) {
1897 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1898 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1900 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1901 clone->setAttribute("x", "0", false);
1902 clone->setAttribute("y", "0", false);
1903 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1905 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1906 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1908 // add the new clone to the top of the original's parent
1909 parent->appendChild(clone);
1911 newsel = g_slist_prepend(newsel, clone);
1912 reprs = g_slist_remove(reprs, sel_repr);
1913 Inkscape::GC::release(clone);
1914 }
1916 // TRANSLATORS: only translate "string" in "context|string".
1917 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1918 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1919 Q_("action|Clone"));
1921 selection->setReprList(newsel);
1923 g_slist_free(newsel);
1924 }
1926 void
1927 sp_selection_relink(SPDesktop *desktop)
1928 {
1929 if (!desktop)
1930 return;
1932 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1934 if (selection->isEmpty()) {
1935 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1936 return;
1937 }
1939 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1940 const gchar *newid = cm->getFirstObjectID();
1941 if (!newid) {
1942 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1943 return;
1944 }
1945 gchar *newref = g_strdup_printf("#%s", newid);
1947 // Get a copy of current selection.
1948 bool relinked = false;
1949 for (GSList *items = (GSList *) selection->itemList();
1950 items != NULL;
1951 items = items->next)
1952 {
1953 SPItem *item = (SPItem *) items->data;
1955 if (!SP_IS_USE(item))
1956 continue;
1958 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1959 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1960 relinked = true;
1961 }
1963 g_free(newref);
1965 if (!relinked) {
1966 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1967 } else {
1968 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1969 _("Relink clone"));
1970 }
1971 }
1974 void
1975 sp_selection_unlink(SPDesktop *desktop)
1976 {
1977 if (!desktop)
1978 return;
1980 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1982 if (selection->isEmpty()) {
1983 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1984 return;
1985 }
1987 // Get a copy of current selection.
1988 GSList *new_select = NULL;
1989 bool unlinked = false;
1990 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1991 items != NULL;
1992 items = items->next)
1993 {
1994 SPItem *item = (SPItem *) items->data;
1996 if (SP_IS_TEXT(item)) {
1997 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1999 if (tspan) {
2000 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2001 }
2003 // Set unlink to true, and fall into the next if which
2004 // will include this text item in the new selection
2005 unlinked = true;
2006 }
2008 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2009 // keep the non-use item in the new selection
2010 new_select = g_slist_prepend(new_select, item);
2011 continue;
2012 }
2014 SPItem *unlink;
2015 if (SP_IS_USE(item)) {
2016 unlink = sp_use_unlink(SP_USE(item));
2017 } else /*if (SP_IS_TREF(use))*/ {
2018 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2019 }
2021 unlinked = true;
2022 // Add ungrouped items to the new selection.
2023 new_select = g_slist_prepend(new_select, unlink);
2024 }
2026 if (new_select) { // set new selection
2027 selection->clear();
2028 selection->setList(new_select);
2029 g_slist_free(new_select);
2030 }
2031 if (!unlinked) {
2032 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2033 }
2035 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2036 _("Unlink clone"));
2037 }
2039 void
2040 sp_select_clone_original(SPDesktop *desktop)
2041 {
2042 if (desktop == NULL)
2043 return;
2045 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2047 SPItem *item = selection->singleItem();
2049 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.");
2051 // Check if other than two objects are selected
2052 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2053 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2054 return;
2055 }
2057 SPItem *original = NULL;
2058 if (SP_IS_USE(item)) {
2059 original = sp_use_get_original(SP_USE(item));
2060 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2061 original = sp_offset_get_source(SP_OFFSET(item));
2062 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2063 original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2064 } else if (SP_IS_FLOWTEXT(item)) {
2065 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2066 } else { // it's an object that we don't know what to do with
2067 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2068 return;
2069 }
2071 if (!original) {
2072 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2073 return;
2074 }
2076 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2077 if (SP_IS_DEFS(o)) {
2078 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2079 return;
2080 }
2081 }
2083 if (original) {
2084 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2085 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2086 if (highlight) {
2087 Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2088 Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2089 if ( a && b ) {
2090 // draw a flashing line between the objects
2091 SPCurve *curve = new SPCurve();
2092 curve->moveto(a->midpoint());
2093 curve->lineto(b->midpoint());
2095 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2096 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2097 sp_canvas_item_show(canvasitem);
2098 curve->unref();
2099 desktop->add_temporary_canvasitem(canvasitem, 1000);
2100 }
2101 }
2103 selection->clear();
2104 selection->set(original);
2105 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2106 scroll_to_show_item(desktop, original);
2107 }
2108 }
2109 }
2112 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2113 {
2114 if (desktop == NULL)
2115 return;
2117 SPDocument *doc = sp_desktop_document(desktop);
2118 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2120 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2122 // check if something is selected
2123 if (selection->isEmpty()) {
2124 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2125 return;
2126 }
2128 sp_document_ensure_up_to_date(doc);
2129 Geom::OptRect r = selection->bounds();
2130 boost::optional<Geom::Point> c = selection->center();
2131 if ( !r || !c ) {
2132 return;
2133 }
2135 // calculate the transform to be applied to objects to move them to 0,0
2136 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2137 move_p[Geom::Y] = -move_p[Geom::Y];
2138 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2140 GSList *items = g_slist_copy((GSList *) selection->itemList());
2142 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2144 // bottommost object, after sorting
2145 SPObject *parent = SP_OBJECT_PARENT(items->data);
2147 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2149 // remember the position of the first item
2150 gint pos = SP_OBJECT_REPR(items->data)->position();
2151 (void)pos; // TODO check why this was remembered
2153 // create a list of duplicates
2154 GSList *repr_copies = NULL;
2155 for (GSList *i = items; i != NULL; i = i->next) {
2156 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2157 repr_copies = g_slist_prepend(repr_copies, dup);
2158 }
2160 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2162 if (apply) {
2163 // delete objects so that their clones don't get alerted; this object will be restored shortly
2164 for (GSList *i = items; i != NULL; i = i->next) {
2165 SPObject *item = SP_OBJECT(i->data);
2166 item->deleteObject(false);
2167 }
2168 }
2170 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2171 // without disturbing clones.
2172 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2173 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2174 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2175 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2177 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2178 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2179 Geom::Point(r->min()[Geom::X],
2180 r->max()[Geom::Y]))))
2181 * parent_transform.inverse() ),
2182 parent_transform * move);
2183 (void)mark_id;
2185 // restore compensation setting
2186 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2189 g_slist_free(items);
2191 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2192 _("Objects to marker"));
2193 }
2195 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2196 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2197 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2198 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2199 }
2200 } else {
2201 sp_item_convert_item_to_guides(item);
2203 if (deleteitem) {
2204 SP_OBJECT(item)->deleteObject(true);
2205 }
2206 }
2207 }
2209 void sp_selection_to_guides(SPDesktop *desktop)
2210 {
2211 if (desktop == NULL)
2212 return;
2214 SPDocument *doc = sp_desktop_document(desktop);
2215 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2216 // we need to copy the list because it gets reset when objects are deleted
2217 GSList *items = g_slist_copy((GSList *) selection->itemList());
2219 if (!items) {
2220 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2221 return;
2222 }
2224 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2225 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2226 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2228 for (GSList const *i = items; i != NULL; i = i->next) {
2229 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2230 }
2232 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2233 }
2235 void
2236 sp_selection_tile(SPDesktop *desktop, bool apply)
2237 {
2238 if (desktop == NULL)
2239 return;
2241 SPDocument *doc = sp_desktop_document(desktop);
2242 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2244 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2246 // check if something is selected
2247 if (selection->isEmpty()) {
2248 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2249 return;
2250 }
2252 sp_document_ensure_up_to_date(doc);
2253 Geom::OptRect r = selection->bounds();
2254 if ( !r ) {
2255 return;
2256 }
2258 // calculate the transform to be applied to objects to move them to 0,0
2259 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2260 move_p[Geom::Y] = -move_p[Geom::Y];
2261 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2263 GSList *items = g_slist_copy((GSList *) selection->itemList());
2265 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2267 // bottommost object, after sorting
2268 SPObject *parent = SP_OBJECT_PARENT(items->data);
2270 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2272 // remember the position of the first item
2273 gint pos = SP_OBJECT_REPR(items->data)->position();
2275 // create a list of duplicates
2276 GSList *repr_copies = NULL;
2277 for (GSList *i = items; i != NULL; i = i->next) {
2278 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2279 repr_copies = g_slist_prepend(repr_copies, dup);
2280 }
2281 // restore the z-order after prepends
2282 repr_copies = g_slist_reverse(repr_copies);
2284 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2286 if (apply) {
2287 // delete objects so that their clones don't get alerted; this object will be restored shortly
2288 for (GSList *i = items; i != NULL; i = i->next) {
2289 SPObject *item = SP_OBJECT(i->data);
2290 item->deleteObject(false);
2291 }
2292 }
2294 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2295 // without disturbing clones.
2296 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2297 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2298 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2299 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2301 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2302 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2303 r->max()[Geom::Y]))))
2304 * to_2geom(parent_transform.inverse()) ),
2305 parent_transform * move);
2307 // restore compensation setting
2308 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2310 if (apply) {
2311 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2312 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2314 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2315 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2317 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2318 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2319 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2320 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2322 // restore parent and position
2323 SP_OBJECT_REPR(parent)->appendChild(rect);
2324 rect->setPosition(pos > 0 ? pos : 0);
2325 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2327 Inkscape::GC::release(rect);
2329 selection->clear();
2330 selection->set(rectangle);
2331 }
2333 g_slist_free(items);
2335 sp_document_done(doc, SP_VERB_EDIT_TILE,
2336 _("Objects to pattern"));
2337 }
2339 void
2340 sp_selection_untile(SPDesktop *desktop)
2341 {
2342 if (desktop == NULL)
2343 return;
2345 SPDocument *doc = sp_desktop_document(desktop);
2346 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2348 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2350 // check if something is selected
2351 if (selection->isEmpty()) {
2352 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2353 return;
2354 }
2356 GSList *new_select = NULL;
2358 bool did = false;
2360 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2361 items != NULL;
2362 items = items->next) {
2364 SPItem *item = (SPItem *) items->data;
2366 SPStyle *style = SP_OBJECT_STYLE(item);
2368 if (!style || !style->fill.isPaintserver())
2369 continue;
2371 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2373 if (!SP_IS_PATTERN(server))
2374 continue;
2376 did = true;
2378 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2380 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2381 pat_transform *= item->transform;
2383 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2384 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2385 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2387 // FIXME: relink clones to the new canvas objects
2388 // use SPObject::setid when mental finishes it to steal ids of
2390 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2391 sp_document_ensure_up_to_date(doc);
2393 Geom::Matrix transform( i->transform * pat_transform );
2394 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2396 new_select = g_slist_prepend(new_select, i);
2397 }
2399 SPCSSAttr *css = sp_repr_css_attr_new();
2400 sp_repr_css_set_property(css, "fill", "none");
2401 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2402 }
2404 if (!did) {
2405 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2406 } else {
2407 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2408 _("Pattern to objects"));
2409 selection->setList(new_select);
2410 }
2411 }
2413 void
2414 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2415 {
2416 if (selection->isEmpty()) {
2417 return;
2418 }
2420 GSList const *reprlst = selection->reprList();
2421 bool filename_search = TRUE;
2422 bool xdpi_search = TRUE;
2423 bool ydpi_search = TRUE;
2425 for (; reprlst != NULL &&
2426 filename_search &&
2427 xdpi_search &&
2428 ydpi_search;
2429 reprlst = reprlst->next) {
2430 gchar const *dpi_string;
2431 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2433 if (filename_search) {
2434 *filename = repr->attribute("inkscape:export-filename");
2435 if (*filename != NULL)
2436 filename_search = FALSE;
2437 }
2439 if (xdpi_search) {
2440 dpi_string = NULL;
2441 dpi_string = repr->attribute("inkscape:export-xdpi");
2442 if (dpi_string != NULL) {
2443 *xdpi = atof(dpi_string);
2444 xdpi_search = FALSE;
2445 }
2446 }
2448 if (ydpi_search) {
2449 dpi_string = NULL;
2450 dpi_string = repr->attribute("inkscape:export-ydpi");
2451 if (dpi_string != NULL) {
2452 *ydpi = atof(dpi_string);
2453 ydpi_search = FALSE;
2454 }
2455 }
2456 }
2457 }
2459 void
2460 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2461 {
2462 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2463 gchar const *dpi_string;
2465 *filename = repr->attribute("inkscape:export-filename");
2467 dpi_string = NULL;
2468 dpi_string = repr->attribute("inkscape:export-xdpi");
2469 if (dpi_string != NULL) {
2470 *xdpi = atof(dpi_string);
2471 }
2473 dpi_string = NULL;
2474 dpi_string = repr->attribute("inkscape:export-ydpi");
2475 if (dpi_string != NULL) {
2476 *ydpi = atof(dpi_string);
2477 }
2478 }
2480 void
2481 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2482 {
2483 if (desktop == NULL)
2484 return;
2486 SPDocument *document = sp_desktop_document(desktop);
2487 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2489 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2491 // check if something is selected
2492 if (selection->isEmpty()) {
2493 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2494 return;
2495 }
2497 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2498 // set "busy" cursor
2499 desktop->setWaitingCursor();
2501 // Get the bounding box of the selection
2502 NRRect bbox;
2503 sp_document_ensure_up_to_date(document);
2504 selection->bounds(&bbox);
2505 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2506 desktop->clearWaitingCursor();
2507 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2508 }
2510 // List of the items to show; all others will be hidden
2511 GSList *items = g_slist_copy((GSList *) selection->itemList());
2513 // Sort items so that the topmost comes last
2514 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2516 // Generate a random value from the current time (you may create bitmap from the same object(s)
2517 // multiple times, and this is done so that they don't clash)
2518 GTimeVal cu;
2519 g_get_current_time(&cu);
2520 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2522 // Create the filename.
2523 gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2524 document->name,
2525 SP_OBJECT_REPR(items->data)->attribute("id"),
2526 current);
2527 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2528 // digits, and a few other chars, with "_"
2529 g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2531 // Build the complete path by adding document base dir, if set, otherwise home dir
2532 gchar * directory = NULL;
2533 if (SP_DOCUMENT_URI(document)) {
2534 directory = g_dirname(SP_DOCUMENT_URI(document));
2535 }
2536 if (directory == NULL) {
2537 directory = homedir_path(NULL);
2538 }
2539 gchar *filepath = g_build_filename(directory, basename, NULL);
2541 //g_print("%s\n", filepath);
2543 // Remember parent and z-order of the topmost one
2544 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2545 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2546 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2548 // Calculate resolution
2549 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2550 double res;
2551 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2552 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2553 if (0 < prefs_res) {
2554 // If it's given explicitly in prefs, take it
2555 res = prefs_res;
2556 } else if (0 < prefs_min) {
2557 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2558 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2559 } else {
2560 float hint_xdpi = 0, hint_ydpi = 0;
2561 char const *hint_filename;
2562 // take resolution hint from the selected objects
2563 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2564 if (hint_xdpi != 0) {
2565 res = hint_xdpi;
2566 } else {
2567 // take resolution hint from the document
2568 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2569 if (hint_xdpi != 0) {
2570 res = hint_xdpi;
2571 } else {
2572 // if all else fails, take the default 90 dpi
2573 res = PX_PER_IN;
2574 }
2575 }
2576 }
2578 // The width and height of the bitmap in pixels
2579 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2580 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2582 // Find out if we have to run an external filter
2583 gchar const *run = NULL;
2584 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2585 if (!filter.empty()) {
2586 // filter command is given;
2587 // see if we have a parameter to pass to it
2588 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2589 if (!param1.empty()) {
2590 if (param1[param1.length() - 1] == '%') {
2591 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2592 gchar p1[256];
2593 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2594 // the first param is always the image filename, the second is param1
2595 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2596 } else {
2597 // otherwise pass the param1 unchanged
2598 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2599 }
2600 } else {
2601 // run without extra parameter
2602 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2603 }
2604 }
2606 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2607 Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2608 Geom::Matrix t;
2610 double shift_x = bbox.x0;
2611 double shift_y = bbox.y1;
2612 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2613 shift_x = round(shift_x);
2614 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2615 }
2616 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2618 // Do the export
2619 sp_export_png_file(document, filepath,
2620 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2621 width, height, res, res,
2622 (guint32) 0xffffff00,
2623 NULL, NULL,
2624 true, /*bool force_overwrite,*/
2625 items);
2627 g_slist_free(items);
2629 // Run filter, if any
2630 if (run) {
2631 g_print("Running external filter: %s\n", run);
2632 int retval;
2633 retval = system(run);
2634 }
2636 // Import the image back
2637 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2638 if (pb) {
2639 // Create the repr for the image
2640 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2641 {
2642 repr->setAttribute("sodipodi:absref", filepath);
2643 gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2644 repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2645 g_free(abs_base);
2646 }
2647 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2648 sp_repr_set_svg_double(repr, "width", width);
2649 sp_repr_set_svg_double(repr, "height", height);
2650 } else {
2651 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2652 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2653 }
2655 // Write transform
2656 gchar *c=sp_svg_transform_write(t);
2657 repr->setAttribute("transform", c);
2658 g_free(c);
2660 // add the new repr to the parent
2661 parent->appendChild(repr);
2663 // move to the saved position
2664 repr->setPosition(pos > 0 ? pos + 1 : 1);
2666 // Set selection to the new image
2667 selection->clear();
2668 selection->add(repr);
2670 // Clean up
2671 Inkscape::GC::release(repr);
2672 gdk_pixbuf_unref(pb);
2674 // Complete undoable transaction
2675 sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2676 _("Create bitmap"));
2677 }
2679 desktop->clearWaitingCursor();
2681 g_free(basename);
2682 g_free(filepath);
2683 }
2685 /**
2686 * \brief Creates a mask or clipPath from selection
2687 * Two different modes:
2688 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2689 * and is applied to current layer
2690 * otherwise, topmost object is used as mask for other objects
2691 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2692 *
2693 */
2694 void
2695 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2696 {
2697 if (desktop == NULL)
2698 return;
2700 SPDocument *doc = sp_desktop_document(desktop);
2701 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2703 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2705 // check if something is selected
2706 bool is_empty = selection->isEmpty();
2707 if ( apply_to_layer && is_empty) {
2708 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2709 return;
2710 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2711 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2712 return;
2713 }
2715 // FIXME: temporary patch to prevent crash!
2716 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2717 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2718 if (clone_with_original) {
2719 return; // in this version, you cannot clip/mask an object with its own clone
2720 }
2721 // /END FIXME
2723 sp_document_ensure_up_to_date(doc);
2725 GSList *items = g_slist_copy((GSList *) selection->itemList());
2727 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2729 // create a list of duplicates
2730 GSList *mask_items = NULL;
2731 GSList *apply_to_items = NULL;
2732 GSList *items_to_delete = NULL;
2733 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2734 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2735 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2737 if (apply_to_layer) {
2738 // all selected items are used for mask, which is applied to a layer
2739 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2741 for (GSList *i = items; i != NULL; i = i->next) {
2742 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2743 mask_items = g_slist_prepend(mask_items, dup);
2745 if (remove_original) {
2746 SPObject *item = SP_OBJECT(i->data);
2747 items_to_delete = g_slist_prepend(items_to_delete, item);
2748 }
2749 }
2750 } else if (!topmost) {
2751 // topmost item is used as a mask, which is applied to other items in a selection
2752 GSList *i = items;
2753 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2754 mask_items = g_slist_prepend(mask_items, dup);
2756 if (remove_original) {
2757 SPObject *item = SP_OBJECT(i->data);
2758 items_to_delete = g_slist_prepend(items_to_delete, item);
2759 }
2761 for (i = i->next; i != NULL; i = i->next) {
2762 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2763 }
2764 } else {
2765 GSList *i = NULL;
2766 for (i = items; NULL != i->next; i = i->next) {
2767 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2768 }
2770 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2771 mask_items = g_slist_prepend(mask_items, dup);
2773 if (remove_original) {
2774 SPObject *item = SP_OBJECT(i->data);
2775 items_to_delete = g_slist_prepend(items_to_delete, item);
2776 }
2777 }
2779 g_slist_free(items);
2780 items = NULL;
2782 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2783 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2784 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2785 // inverted object transform should be applied to a mask object,
2786 // as mask is calculated in user space (after applying transform)
2787 Geom::Matrix maskTransform(item->transform.inverse());
2789 GSList *mask_items_dup = NULL;
2790 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2791 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2792 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2793 }
2795 gchar const *mask_id = NULL;
2796 if (apply_clip_path) {
2797 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2798 } else {
2799 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2800 }
2802 g_slist_free(mask_items_dup);
2803 mask_items_dup = NULL;
2805 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2806 }
2808 g_slist_free(mask_items);
2809 g_slist_free(apply_to_items);
2811 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2812 SPObject *item = SP_OBJECT(i->data);
2813 item->deleteObject(false);
2814 }
2815 g_slist_free(items_to_delete);
2817 if (apply_clip_path)
2818 sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2819 else
2820 sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2821 }
2823 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2824 if (desktop == NULL)
2825 return;
2827 SPDocument *doc = sp_desktop_document(desktop);
2828 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2829 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2831 // check if something is selected
2832 if (selection->isEmpty()) {
2833 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2834 return;
2835 }
2837 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2838 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2839 sp_document_ensure_up_to_date(doc);
2841 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2842 std::map<SPObject*,SPItem*> referenced_objects;
2843 // SPObject* refers to a group containing the clipped path or mask itself,
2844 // whereas SPItem* refers to the item being clipped or masked
2845 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2846 if (remove_original) {
2847 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2848 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2849 Inkscape::URIReference *uri_ref = NULL;
2851 if (apply_clip_path) {
2852 uri_ref = item->clip_ref;
2853 } else {
2854 uri_ref = item->mask_ref;
2855 }
2857 // collect distinct mask object (and associate with item to apply transform)
2858 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2859 referenced_objects[uri_ref->getObject()] = item;
2860 }
2861 }
2863 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2864 }
2866 // restore mask objects into a document
2867 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2868 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2869 GSList *items_to_move = NULL;
2870 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2871 // Collect all clipped paths and masks within a single group
2872 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2873 items_to_move = g_slist_prepend(items_to_move, copy);
2874 }
2876 if (!obj->isReferenced()) {
2877 // delete from defs if no other object references this mask
2878 obj->deleteObject(false);
2879 }
2881 // remember parent and position of the item to which the clippath/mask was applied
2882 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2883 gint pos = SP_OBJECT_REPR((*it).second)->position();
2885 // Iterate through all clipped paths / masks
2886 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2887 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2889 // insert into parent, restore pos
2890 parent->appendChild(repr);
2891 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2893 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
2894 selection->add(repr);
2896 // transform mask, so it is moved the same spot where mask was applied
2897 Geom::Matrix transform(mask_item->transform);
2898 transform *= (*it).second->transform;
2899 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2900 }
2902 g_slist_free(items_to_move);
2903 }
2905 if (apply_clip_path)
2906 sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2907 else
2908 sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2909 }
2911 /**
2912 * Returns true if an undoable change should be recorded.
2913 */
2914 bool
2915 fit_canvas_to_selection(SPDesktop *desktop)
2916 {
2917 g_return_val_if_fail(desktop != NULL, false);
2918 SPDocument *doc = sp_desktop_document(desktop);
2920 g_return_val_if_fail(doc != NULL, false);
2921 g_return_val_if_fail(desktop->selection != NULL, false);
2923 if (desktop->selection->isEmpty()) {
2924 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2925 return false;
2926 }
2927 Geom::OptRect const bbox(desktop->selection->bounds());
2928 if (bbox) {
2929 doc->fitToRect(*bbox);
2930 return true;
2931 } else {
2932 return false;
2933 }
2934 }
2936 /**
2937 * Fit canvas to the bounding box of the selection, as an undoable action.
2938 */
2939 void
2940 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2941 {
2942 if (fit_canvas_to_selection(desktop)) {
2943 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2944 _("Fit Page to Selection"));
2945 }
2946 }
2948 bool
2949 fit_canvas_to_drawing(SPDocument *doc)
2950 {
2951 g_return_val_if_fail(doc != NULL, false);
2953 sp_document_ensure_up_to_date(doc);
2954 SPItem const *const root = SP_ITEM(doc->root);
2955 Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2956 if (bbox) {
2957 doc->fitToRect(*bbox);
2958 return true;
2959 } else {
2960 return false;
2961 }
2962 }
2964 void
2965 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2966 {
2967 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2968 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2969 _("Fit Page to Drawing"));
2970 }
2971 }
2973 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2974 g_return_if_fail(desktop != NULL);
2975 SPDocument *doc = sp_desktop_document(desktop);
2977 g_return_if_fail(doc != NULL);
2978 g_return_if_fail(desktop->selection != NULL);
2980 bool const changed = ( desktop->selection->isEmpty()
2981 ? fit_canvas_to_drawing(doc)
2982 : fit_canvas_to_selection(desktop) );
2983 if (changed) {
2984 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2985 _("Fit Page to Selection or Drawing"));
2986 }
2987 };
2989 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2990 // don't operate on layers
2991 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2992 f(SP_ITEM(root), desktop);
2993 }
2994 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2995 //don't recurse into locked layers
2996 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2997 itemtree_map(f, iter, desktop);
2998 }
2999 }
3000 }
3002 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3003 if (item->isLocked()) {
3004 item->setLocked(FALSE);
3005 }
3006 }
3008 static void unhide(SPItem *item, SPDesktop *desktop) {
3009 if (desktop->itemIsHidden(item)) {
3010 item->setExplicitlyHidden(FALSE);
3011 }
3012 }
3014 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3015 if (!dt) return;
3017 SPObject *root;
3018 if (layer_only) {
3019 root = dt->currentLayer();
3020 } else {
3021 root = dt->currentRoot();
3022 }
3024 itemtree_map(f, root, dt);
3025 }
3027 void unlock_all(SPDesktop *dt) {
3028 process_all(&unlock, dt, true);
3029 }
3031 void unlock_all_in_all_layers(SPDesktop *dt) {
3032 process_all(&unlock, dt, false);
3033 }
3035 void unhide_all(SPDesktop *dt) {
3036 process_all(&unhide, dt, true);
3037 }
3039 void unhide_all_in_all_layers(SPDesktop *dt) {
3040 process_all(&unhide, dt, false);
3041 }
3044 /*
3045 Local Variables:
3046 mode:c++
3047 c-file-style:"stroustrup"
3048 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3049 indent-tabs-mode:nil
3050 fill-column:99
3051 End:
3052 */
3053 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :