9d60399fecdd85ec83815d729b9c10162b6fb606
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 put the word "Raise" in the translation. Means "to raise an object" in the undo history
734 Q_("undo_action|Raise"));
735 }
737 void sp_selection_raise_to_top(SPDesktop *desktop)
738 {
739 if (desktop == NULL)
740 return;
742 SPDocument *document = sp_desktop_document(desktop);
743 Inkscape::Selection *selection = sp_desktop_selection(desktop);
745 if (selection->isEmpty()) {
746 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
747 return;
748 }
750 GSList const *items = (GSList *) selection->itemList();
752 SPGroup const *group = sp_item_list_common_parent_group(items);
753 if (!group) {
754 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
755 return;
756 }
758 GSList *rl = g_slist_copy((GSList *) selection->reprList());
759 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
761 for (GSList *l = rl; l != NULL; l = l->next) {
762 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
763 repr->setPosition(-1);
764 }
766 g_slist_free(rl);
768 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
769 _("Raise to top"));
770 }
772 void
773 sp_selection_lower(SPDesktop *desktop)
774 {
775 if (desktop == NULL)
776 return;
778 Inkscape::Selection *selection = sp_desktop_selection(desktop);
780 GSList const *items = (GSList *) selection->itemList();
781 if (!items) {
782 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
783 return;
784 }
786 SPGroup const *group = sp_item_list_common_parent_group(items);
787 if (!group) {
788 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
789 return;
790 }
792 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
794 // Determine the common bbox of the selected items.
795 Geom::OptRect selected = enclose_items(items);
797 /* Construct direct-ordered list of selected children. */
798 GSList *rev = g_slist_copy((GSList *) items);
799 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
800 rev = g_slist_reverse(rev);
802 // Iterate over all objects in the selection (starting from top).
803 if (selected) {
804 while (rev) {
805 SPObject *child = SP_OBJECT(rev->data);
806 // for each selected object, find the prev sibling
807 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
808 // if the sibling is an item AND overlaps our selection,
809 if (SP_IS_ITEM(newref)) {
810 Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
811 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
812 // AND if it's not one of our selected objects,
813 if (!g_slist_find((GSList *) items, newref)) {
814 // move the selected object before that sibling
815 SPObject *put_after = prev_sibling(newref);
816 if (put_after)
817 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
818 else
819 SP_OBJECT_REPR(child)->setPosition(0);
820 }
821 break;
822 }
823 }
824 }
825 rev = g_slist_remove(rev, child);
826 }
827 } else {
828 g_slist_free(rev);
829 }
831 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
832 _("Lower"));
833 }
835 void sp_selection_lower_to_bottom(SPDesktop *desktop)
836 {
837 if (desktop == NULL)
838 return;
840 SPDocument *document = sp_desktop_document(desktop);
841 Inkscape::Selection *selection = sp_desktop_selection(desktop);
843 if (selection->isEmpty()) {
844 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
845 return;
846 }
848 GSList const *items = (GSList *) selection->itemList();
850 SPGroup const *group = sp_item_list_common_parent_group(items);
851 if (!group) {
852 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
853 return;
854 }
856 GSList *rl;
857 rl = g_slist_copy((GSList *) selection->reprList());
858 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
859 rl = g_slist_reverse(rl);
861 for (GSList *l = rl; l != NULL; l = l->next) {
862 gint minpos;
863 SPObject *pp, *pc;
864 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
865 pp = document->getObjectByRepr(sp_repr_parent(repr));
866 minpos = 0;
867 g_assert(SP_IS_GROUP(pp));
868 pc = sp_object_first_child(pp);
869 while (!SP_IS_ITEM(pc)) {
870 minpos += 1;
871 pc = pc->next;
872 }
873 repr->setPosition(minpos);
874 }
876 g_slist_free(rl);
878 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
879 _("Lower to bottom"));
880 }
882 void
883 sp_undo(SPDesktop *desktop, SPDocument *)
884 {
885 if (!sp_document_undo(sp_desktop_document(desktop)))
886 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
887 }
889 void
890 sp_redo(SPDesktop *desktop, SPDocument *)
891 {
892 if (!sp_document_redo(sp_desktop_document(desktop)))
893 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
894 }
896 void sp_selection_cut(SPDesktop *desktop)
897 {
898 sp_selection_copy();
899 sp_selection_delete(desktop);
900 }
902 /**
903 * \pre item != NULL
904 */
905 SPCSSAttr *
906 take_style_from_item(SPItem *item)
907 {
908 // write the complete cascaded style, context-free
909 SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
910 if (css == NULL)
911 return NULL;
913 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
914 (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
915 // if this is a text with exactly one tspan child, merge the style of that tspan as well
916 // If this is a group, merge the style of its topmost (last) child with style
917 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
918 if (SP_OBJECT_STYLE(last_element) != NULL) {
919 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
920 if (temp) {
921 sp_repr_css_merge(css, temp);
922 sp_repr_css_attr_unref(temp);
923 }
924 break;
925 }
926 }
927 }
928 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
929 // do not copy text properties from non-text objects, it's confusing
930 css = sp_css_attr_unset_text(css);
931 }
933 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
934 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
935 if (ex != 1.0) {
936 css = sp_css_attr_scale(css, ex);
937 }
939 return css;
940 }
943 void sp_selection_copy()
944 {
945 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
946 cm->copy();
947 }
949 void sp_selection_paste(SPDesktop *desktop, bool in_place)
950 {
951 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
952 if (cm->paste(in_place))
953 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
954 }
956 void sp_selection_paste_style(SPDesktop *desktop)
957 {
958 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
959 if (cm->pasteStyle())
960 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
961 }
964 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
965 {
966 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
967 if (cm->pastePathEffect())
968 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
969 _("Paste live path effect"));
970 }
973 void sp_selection_remove_livepatheffect_impl(SPItem *item)
974 {
975 if ( item && SP_IS_LPE_ITEM(item) &&
976 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
977 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
978 }
979 }
981 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
982 {
983 if (desktop == NULL) return;
985 Inkscape::Selection *selection = sp_desktop_selection(desktop);
987 // check if something is selected
988 if (selection->isEmpty()) {
989 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
990 return;
991 }
993 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
994 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
996 sp_selection_remove_livepatheffect_impl(item);
998 }
1000 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1001 _("Remove live path effect"));
1002 }
1004 void sp_selection_remove_filter(SPDesktop *desktop)
1005 {
1006 if (desktop == NULL) return;
1008 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1010 // check if something is selected
1011 if (selection->isEmpty()) {
1012 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1013 return;
1014 }
1016 SPCSSAttr *css = sp_repr_css_attr_new();
1017 sp_repr_css_unset_property(css, "filter");
1018 sp_desktop_set_style(desktop, css);
1019 sp_repr_css_attr_unref(css);
1021 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1022 _("Remove filter"));
1023 }
1026 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1027 {
1028 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1029 if (cm->pasteSize(false, apply_x, apply_y))
1030 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1031 _("Paste size"));
1032 }
1034 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1035 {
1036 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1037 if (cm->pasteSize(true, apply_x, apply_y))
1038 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1039 _("Paste size separately"));
1040 }
1042 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1043 {
1044 Inkscape::Selection *selection = sp_desktop_selection(dt);
1046 // check if something is selected
1047 if (selection->isEmpty()) {
1048 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1049 return;
1050 }
1052 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1054 bool no_more = false; // Set to true, if no more layers above
1055 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1056 if (next) {
1057 GSList *temp_clip = NULL;
1058 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1059 sp_selection_delete_impl(items, false, false);
1060 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1061 GSList *copied;
1062 if (next) {
1063 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1064 } else {
1065 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1066 no_more = true;
1067 }
1068 selection->setReprList((GSList const *) copied);
1069 g_slist_free(copied);
1070 if (temp_clip) g_slist_free(temp_clip);
1071 if (next) dt->setCurrentLayer(next);
1072 if ( !suppressDone ) {
1073 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1074 _("Raise to next layer"));
1075 }
1076 } else {
1077 no_more = true;
1078 }
1080 if (no_more) {
1081 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1082 }
1084 g_slist_free((GSList *) items);
1085 }
1087 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1088 {
1089 Inkscape::Selection *selection = sp_desktop_selection(dt);
1091 // check if something is selected
1092 if (selection->isEmpty()) {
1093 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1094 return;
1095 }
1097 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1099 bool no_more = false; // Set to true, if no more layers below
1100 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1101 if (next) {
1102 GSList *temp_clip = NULL;
1103 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
1104 sp_selection_delete_impl(items, false, false);
1105 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1106 GSList *copied;
1107 if (next) {
1108 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1109 } else {
1110 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1111 no_more = true;
1112 }
1113 selection->setReprList((GSList const *) copied);
1114 g_slist_free(copied);
1115 if (temp_clip) g_slist_free(temp_clip);
1116 if (next) dt->setCurrentLayer(next);
1117 if ( !suppressDone ) {
1118 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1119 _("Lower to previous layer"));
1120 }
1121 } else {
1122 no_more = true;
1123 }
1125 if (no_more) {
1126 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1127 }
1129 g_slist_free((GSList *) items);
1130 }
1132 bool
1133 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1134 {
1135 bool contains_original = false;
1137 bool is_use = SP_IS_USE(item);
1138 SPItem *item_use = item;
1139 SPItem *item_use_first = item;
1140 while (is_use && item_use && !contains_original)
1141 {
1142 item_use = sp_use_get_original(SP_USE(item_use));
1143 contains_original |= selection->includes(item_use);
1144 if (item_use == item_use_first)
1145 break;
1146 is_use = SP_IS_USE(item_use);
1147 }
1149 // If it's a tref, check whether the object containing the character
1150 // data is part of the selection
1151 if (!contains_original && SP_IS_TREF(item)) {
1152 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1153 }
1155 return contains_original;
1156 }
1159 bool
1160 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1161 {
1162 bool clone_with_original = false;
1163 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1164 SPItem *item = SP_ITEM(l->data);
1165 clone_with_original |= selection_contains_original(item, selection);
1166 if (clone_with_original)
1167 break;
1168 }
1169 return clone_with_original;
1170 }
1173 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1174 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1175 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1176 that case, items are already in the new position, but the repr is in the old, and this function
1177 then simply updates the repr from item->transform.
1178 */
1179 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1180 {
1181 if (selection->isEmpty())
1182 return;
1184 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1185 SPItem *item = SP_ITEM(l->data);
1187 Geom::Point old_center(0,0);
1188 if (set_i2d && item->isCenterSet())
1189 old_center = item->getCenter();
1191 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1192 At the time of writing, this is the only place to re-enable. */
1193 sp_item_update_cns(*item, selection->desktop());
1194 #endif
1196 // we're moving both a clone and its original or any ancestor in clone chain?
1197 bool transform_clone_with_original = selection_contains_original(item, selection);
1198 // ...both a text-on-path and its path?
1199 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)))) ));
1200 // ...both a flowtext and its frame?
1201 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)
1202 // ...both an offset and its source?
1203 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1205 // If we're moving a connector, we want to detach it
1206 // from shapes that aren't part of the selection, but
1207 // leave it attached if they are
1208 if (cc_item_is_connector(item)) {
1209 SPItem *attItem[2];
1210 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1212 for (int n = 0; n < 2; ++n) {
1213 if (!selection->includes(attItem[n])) {
1214 sp_conn_end_detach(item, n);
1215 }
1216 }
1217 }
1219 // "clones are unmoved when original is moved" preference
1220 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1221 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1222 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1223 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1225 /* If this is a clone and it's selected along with its original, do not move it;
1226 * it will feel the transform of its original and respond to it itself.
1227 * Without this, a clone is doubly transformed, very unintuitive.
1228 *
1229 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1230 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1231 * Same for linked offset if we are also moving its source: do not move it. */
1232 if (transform_textpath_with_path || transform_offset_with_source) {
1233 // Restore item->transform field from the repr, in case it was changed by seltrans.
1234 sp_object_read_attr(SP_OBJECT(item), "transform");
1235 } else if (transform_flowtext_with_frame) {
1236 // apply the inverse of the region's transform to the <use> so that the flow remains
1237 // the same (even though the output itself gets transformed)
1238 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1239 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1240 continue;
1241 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1242 if (!SP_IS_USE(use)) continue;
1243 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1244 }
1245 }
1246 } else if (transform_clone_with_original) {
1247 // We are transforming a clone along with its original. The below matrix juggling is
1248 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1249 // transform and its move compensation are both cancelled out.
1251 // restore item->transform field from the repr, in case it was changed by seltrans
1252 sp_object_read_attr(SP_OBJECT(item), "transform");
1254 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1255 Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1256 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1257 Geom::Matrix t_inv = t.inverse();
1258 Geom::Matrix result = t_inv * item->transform * t;
1260 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1261 // we need to cancel out the move compensation, too
1263 // find out the clone move, same as in sp_use_move_compensate
1264 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1265 Geom::Matrix clone_move = parent.inverse() * t * parent;
1267 if (prefs_parallel) {
1268 Geom::Matrix move = result * clone_move * t_inv;
1269 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1271 } else if (prefs_unmoved) {
1272 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1273 // clone_move = Geom::identity();
1274 Geom::Matrix move = result * clone_move;
1275 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1276 }
1278 } else {
1279 // just apply the result
1280 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1281 }
1283 } else {
1284 if (set_i2d) {
1285 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1286 }
1287 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1288 }
1290 // if we're moving the actual object, not just updating the repr, we can transform the
1291 // center by the same matrix (only necessary for non-translations)
1292 if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1293 item->setCenter(old_center * affine);
1294 SP_OBJECT(item)->updateRepr();
1295 }
1296 }
1297 }
1299 void sp_selection_remove_transform(SPDesktop *desktop)
1300 {
1301 if (desktop == NULL)
1302 return;
1304 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1306 GSList const *l = (GSList *) selection->reprList();
1307 while (l != NULL) {
1308 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1309 l = l->next;
1310 }
1312 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1313 _("Remove transform"));
1314 }
1316 void
1317 sp_selection_scale_absolute(Inkscape::Selection *selection,
1318 double const x0, double const x1,
1319 double const y0, double const y1)
1320 {
1321 if (selection->isEmpty())
1322 return;
1324 Geom::OptRect const bbox(selection->bounds());
1325 if ( !bbox ) {
1326 return;
1327 }
1329 Geom::Translate const p2o(-bbox->min());
1331 Geom::Scale const newSize(x1 - x0,
1332 y1 - y0);
1333 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1334 Geom::Translate const o2n(x0, y0);
1335 Geom::Matrix const final( p2o * scale * o2n );
1337 sp_selection_apply_affine(selection, final);
1338 }
1341 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1342 {
1343 if (selection->isEmpty())
1344 return;
1346 Geom::OptRect const bbox(selection->bounds());
1348 if ( !bbox ) {
1349 return;
1350 }
1352 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1353 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1354 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1355 {
1356 return;
1357 }
1359 Geom::Translate const n2d(-align);
1360 Geom::Translate const d2n(align);
1361 Geom::Matrix const final( n2d * scale * d2n );
1362 sp_selection_apply_affine(selection, final);
1363 }
1365 void
1366 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1367 {
1368 Geom::Translate const d2n(center);
1369 Geom::Translate const n2d(-center);
1370 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1371 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1372 sp_selection_apply_affine(selection, final);
1373 }
1375 void
1376 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1377 {
1378 Geom::Translate const d2n(align);
1379 Geom::Translate const n2d(-align);
1380 Geom::Matrix const skew(1, dy,
1381 dx, 1,
1382 0, 0);
1383 Geom::Matrix const final( n2d * skew * d2n );
1384 sp_selection_apply_affine(selection, final);
1385 }
1387 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1388 {
1389 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)));
1390 }
1392 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1393 {
1394 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1395 }
1397 /**
1398 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1399 */
1400 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1401 {
1402 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1404 if (selection->isEmpty())
1405 return;
1407 GSList const *l = selection->itemList();
1408 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1409 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1410 SPItem *item = SP_ITEM(l2->data);
1411 sp_item_rotate_rel(item, rot_90);
1412 }
1414 sp_document_done(sp_desktop_document(desktop),
1415 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1416 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1417 }
1419 void
1420 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1421 {
1422 if (selection->isEmpty())
1423 return;
1425 boost::optional<Geom::Point> center = selection->center();
1426 if (!center) {
1427 return;
1428 }
1430 sp_selection_rotate_relative(selection, *center, angle_degrees);
1432 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1433 ( ( angle_degrees > 0 )
1434 ? "selector:rotate:ccw"
1435 : "selector:rotate:cw" ),
1436 SP_VERB_CONTEXT_SELECT,
1437 _("Rotate"));
1438 }
1440 // helper function:
1441 static
1442 Geom::Point
1443 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1444 Geom::Point m = r.midpoint();
1445 unsigned i = 0;
1446 if (p[X] < m[X]) {
1447 i = 1;
1448 }
1449 if (p[Y] < m[Y]) {
1450 i = 3 - i;
1451 }
1452 return r.corner(i);
1453 }
1455 /**
1456 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1457 */
1458 void
1459 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1460 {
1461 if (selection->isEmpty())
1462 return;
1464 Geom::OptRect const bbox(selection->bounds());
1465 boost::optional<Geom::Point> center = selection->center();
1467 if ( !bbox || !center ) {
1468 return;
1469 }
1471 gdouble const zoom = selection->desktop()->current_zoom();
1472 gdouble const zmove = angle / zoom;
1473 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1475 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1477 sp_selection_rotate_relative(selection, *center, zangle);
1479 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1480 ( (angle > 0)
1481 ? "selector:rotate:ccw"
1482 : "selector:rotate:cw" ),
1483 SP_VERB_CONTEXT_SELECT,
1484 _("Rotate by pixels"));
1485 }
1487 void
1488 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1489 {
1490 if (selection->isEmpty())
1491 return;
1493 Geom::OptRect const bbox(selection->bounds());
1494 if (!bbox) {
1495 return;
1496 }
1498 Geom::Point const center(bbox->midpoint());
1500 // you can't scale "do nizhe pola" (below zero)
1501 double const max_len = bbox->maxExtent();
1502 if ( max_len + grow <= 1e-3 ) {
1503 return;
1504 }
1506 double const times = 1.0 + grow / max_len;
1507 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1509 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1510 ( (grow > 0)
1511 ? "selector:scale:larger"
1512 : "selector:scale:smaller" ),
1513 SP_VERB_CONTEXT_SELECT,
1514 _("Scale"));
1515 }
1517 void
1518 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1519 {
1520 sp_selection_scale(selection,
1521 grow_pixels / selection->desktop()->current_zoom());
1522 }
1524 void
1525 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1526 {
1527 if (selection->isEmpty())
1528 return;
1530 Geom::OptRect sel_bbox = selection->bounds();
1532 if (!sel_bbox) {
1533 return;
1534 }
1536 Geom::Point const center(sel_bbox->midpoint());
1537 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1538 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1539 _("Scale by whole factor"));
1540 }
1542 void
1543 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1544 {
1545 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1546 if (selection->isEmpty()) {
1547 return;
1548 }
1550 sp_selection_move_relative(selection, dx, dy);
1552 if (dx == 0) {
1553 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1554 _("Move vertically"));
1555 } else if (dy == 0) {
1556 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1557 _("Move horizontally"));
1558 } else {
1559 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1560 _("Move"));
1561 }
1562 }
1564 void
1565 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1566 {
1567 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1568 if (selection->isEmpty()) {
1569 return;
1570 }
1572 // same as sp_selection_move but divide deltas by zoom factor
1573 gdouble const zoom = desktop->current_zoom();
1574 gdouble const zdx = dx / zoom;
1575 gdouble const zdy = dy / zoom;
1576 sp_selection_move_relative(selection, zdx, zdy);
1578 if (dx == 0) {
1579 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1580 _("Move vertically by pixels"));
1581 } else if (dy == 0) {
1582 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1583 _("Move horizontally by pixels"));
1584 } else {
1585 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1586 _("Move"));
1587 }
1588 }
1590 namespace {
1592 template <typename D>
1593 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1594 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1596 template <typename D>
1597 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1598 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1600 struct Forward {
1601 typedef SPObject *Iterator;
1603 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1604 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1605 static void dispose(Iterator /*i*/) {}
1607 static SPObject *object(Iterator i) { return i; }
1608 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1609 };
1611 struct Reverse {
1612 typedef GSList *Iterator;
1614 static Iterator children(SPObject *o) {
1615 return make_list(o->firstChild(), NULL);
1616 }
1617 static Iterator siblings_after(SPObject *o) {
1618 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1619 }
1620 static void dispose(Iterator i) {
1621 g_slist_free(i);
1622 }
1624 static SPObject *object(Iterator i) {
1625 return reinterpret_cast<SPObject *>(i->data);
1626 }
1627 static Iterator next(Iterator i) { return i->next; }
1629 private:
1630 static GSList *make_list(SPObject *object, SPObject *limit) {
1631 GSList *list=NULL;
1632 while ( object != limit ) {
1633 list = g_slist_prepend(list, object);
1634 object = SP_OBJECT_NEXT(object);
1635 }
1636 return list;
1637 }
1638 };
1640 }
1642 void
1643 sp_selection_item_next(SPDesktop *desktop)
1644 {
1645 g_return_if_fail(desktop != NULL);
1646 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1648 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1649 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1650 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1651 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1653 SPObject *root;
1654 if (PREFS_SELECTION_ALL != inlayer) {
1655 root = selection->activeContext();
1656 } else {
1657 root = desktop->currentRoot();
1658 }
1660 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1662 if (item) {
1663 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1664 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1665 scroll_to_show_item(desktop, item);
1666 }
1667 }
1668 }
1670 void
1671 sp_selection_item_prev(SPDesktop *desktop)
1672 {
1673 SPDocument *document = sp_desktop_document(desktop);
1674 g_return_if_fail(document != NULL);
1675 g_return_if_fail(desktop != NULL);
1676 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1678 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1679 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1680 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1681 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1683 SPObject *root;
1684 if (PREFS_SELECTION_ALL != inlayer) {
1685 root = selection->activeContext();
1686 } else {
1687 root = desktop->currentRoot();
1688 }
1690 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1692 if (item) {
1693 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1694 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1695 scroll_to_show_item(desktop, item);
1696 }
1697 }
1698 }
1700 void sp_selection_next_patheffect_param(SPDesktop * dt)
1701 {
1702 if (!dt) return;
1704 Inkscape::Selection *selection = sp_desktop_selection(dt);
1705 if ( selection && !selection->isEmpty() ) {
1706 SPItem *item = selection->singleItem();
1707 if ( item && SP_IS_SHAPE(item)) {
1708 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1709 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1710 } else {
1711 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1712 }
1713 }
1714 }
1715 }
1717 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1718 {
1719 if (!dt) return;
1721 Inkscape::Selection *selection = sp_desktop_selection(dt);
1722 if ( selection && !selection->isEmpty() ) {
1723 SPItem *item = selection->singleItem();
1724 if ( item ) {
1725 SPObject *obj = NULL;
1726 if (clip)
1727 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1728 else
1729 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1731 if (obj) {
1732 // obj is a group object, the children are the actual clippers
1733 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1734 if ( SP_IS_ITEM(child) ) {
1735 // If not already in nodecontext, goto it!
1736 if (!tools_isactive(dt, TOOLS_NODES)) {
1737 tools_switch(dt, TOOLS_NODES);
1738 }
1740 ShapeEditor * shape_editor = dt->event_context->shape_editor;
1741 // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1742 shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1743 shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1744 Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1745 if (np) {
1746 // take colors from prefs (same as used in outline mode)
1747 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1748 np->helperpath_rgba = clip ?
1749 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) :
1750 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1751 np->helperpath_width = 1.0;
1752 sp_nodepath_show_helperpath(np, true);
1753 }
1754 break; // break out of for loop after 1st encountered item
1755 }
1756 }
1757 } else if (clip) {
1758 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1759 } else {
1760 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1761 }
1762 }
1763 }
1764 }
1767 namespace {
1769 template <typename D>
1770 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1771 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1772 {
1773 SPObject *current=root;
1774 while (items) {
1775 SPItem *item=SP_ITEM(items->data);
1776 if ( root->isAncestorOf(item) &&
1777 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1778 {
1779 current = item;
1780 break;
1781 }
1782 items = items->next;
1783 }
1785 GSList *path=NULL;
1786 while ( current != root ) {
1787 path = g_slist_prepend(path, current);
1788 current = SP_OBJECT_PARENT(current);
1789 }
1791 SPItem *next;
1792 // first, try from the current object
1793 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1794 g_slist_free(path);
1796 if (!next) { // if we ran out of objects, start over at the root
1797 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1798 }
1800 return next;
1801 }
1803 template <typename D>
1804 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1805 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1806 {
1807 typename D::Iterator children;
1808 typename D::Iterator iter;
1810 SPItem *found=NULL;
1812 if (path) {
1813 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1814 g_assert(SP_OBJECT_PARENT(object) == root);
1815 if (desktop->isLayer(object)) {
1816 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1817 }
1818 iter = children = D::siblings_after(object);
1819 } else {
1820 iter = children = D::children(root);
1821 }
1823 while ( iter && !found ) {
1824 SPObject *object=D::object(iter);
1825 if (desktop->isLayer(object)) {
1826 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1827 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1828 }
1829 } else if ( SP_IS_ITEM(object) &&
1830 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1831 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1832 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1833 !desktop->isLayer(SP_ITEM(object)) )
1834 {
1835 found = SP_ITEM(object);
1836 }
1837 iter = D::next(iter);
1838 }
1840 D::dispose(children);
1842 return found;
1843 }
1845 }
1847 /**
1848 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1849 * \a item.
1850 */
1851 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1852 {
1853 Geom::Rect dbox = desktop->get_display_area();
1854 Geom::OptRect sbox = sp_item_bbox_desktop(item);
1856 if ( sbox && dbox.contains(*sbox) == false ) {
1857 Geom::Point const s_dt = sbox->midpoint();
1858 Geom::Point const s_w = desktop->d2w(s_dt);
1859 Geom::Point const d_dt = dbox.midpoint();
1860 Geom::Point const d_w = desktop->d2w(d_dt);
1861 Geom::Point const moved_w( d_w - s_w );
1862 gint const dx = (gint) moved_w[X];
1863 gint const dy = (gint) moved_w[Y];
1864 desktop->scroll_world(dx, dy);
1865 }
1866 }
1869 void
1870 sp_selection_clone(SPDesktop *desktop)
1871 {
1872 if (desktop == NULL)
1873 return;
1875 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1877 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1879 // check if something is selected
1880 if (selection->isEmpty()) {
1881 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1882 return;
1883 }
1885 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1887 selection->clear();
1889 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1890 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1892 GSList *newsel = NULL;
1894 while (reprs) {
1895 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1896 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1898 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1899 clone->setAttribute("x", "0", false);
1900 clone->setAttribute("y", "0", false);
1901 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1903 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1904 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1906 // add the new clone to the top of the original's parent
1907 parent->appendChild(clone);
1909 newsel = g_slist_prepend(newsel, clone);
1910 reprs = g_slist_remove(reprs, sel_repr);
1911 Inkscape::GC::release(clone);
1912 }
1914 // TRANSLATORS: only translate "string" in "context|string".
1915 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1916 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1917 Q_("action|Clone"));
1919 selection->setReprList(newsel);
1921 g_slist_free(newsel);
1922 }
1924 void
1925 sp_selection_relink(SPDesktop *desktop)
1926 {
1927 if (!desktop)
1928 return;
1930 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1932 if (selection->isEmpty()) {
1933 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1934 return;
1935 }
1937 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1938 const gchar *newid = cm->getFirstObjectID();
1939 if (!newid) {
1940 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1941 return;
1942 }
1943 gchar *newref = g_strdup_printf("#%s", newid);
1945 // Get a copy of current selection.
1946 bool relinked = false;
1947 for (GSList *items = (GSList *) selection->itemList();
1948 items != NULL;
1949 items = items->next)
1950 {
1951 SPItem *item = (SPItem *) items->data;
1953 if (!SP_IS_USE(item))
1954 continue;
1956 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1957 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1958 relinked = true;
1959 }
1961 g_free(newref);
1963 if (!relinked) {
1964 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1965 } else {
1966 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1967 _("Relink clone"));
1968 }
1969 }
1972 void
1973 sp_selection_unlink(SPDesktop *desktop)
1974 {
1975 if (!desktop)
1976 return;
1978 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1980 if (selection->isEmpty()) {
1981 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1982 return;
1983 }
1985 // Get a copy of current selection.
1986 GSList *new_select = NULL;
1987 bool unlinked = false;
1988 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1989 items != NULL;
1990 items = items->next)
1991 {
1992 SPItem *item = (SPItem *) items->data;
1994 if (SP_IS_TEXT(item)) {
1995 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1997 if (tspan) {
1998 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1999 }
2001 // Set unlink to true, and fall into the next if which
2002 // will include this text item in the new selection
2003 unlinked = true;
2004 }
2006 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2007 // keep the non-use item in the new selection
2008 new_select = g_slist_prepend(new_select, item);
2009 continue;
2010 }
2012 SPItem *unlink;
2013 if (SP_IS_USE(item)) {
2014 unlink = sp_use_unlink(SP_USE(item));
2015 } else /*if (SP_IS_TREF(use))*/ {
2016 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2017 }
2019 unlinked = true;
2020 // Add ungrouped items to the new selection.
2021 new_select = g_slist_prepend(new_select, unlink);
2022 }
2024 if (new_select) { // set new selection
2025 selection->clear();
2026 selection->setList(new_select);
2027 g_slist_free(new_select);
2028 }
2029 if (!unlinked) {
2030 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2031 }
2033 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2034 _("Unlink clone"));
2035 }
2037 void
2038 sp_select_clone_original(SPDesktop *desktop)
2039 {
2040 if (desktop == NULL)
2041 return;
2043 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2045 SPItem *item = selection->singleItem();
2047 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.");
2049 // Check if other than two objects are selected
2050 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2051 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2052 return;
2053 }
2055 SPItem *original = NULL;
2056 if (SP_IS_USE(item)) {
2057 original = sp_use_get_original(SP_USE(item));
2058 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2059 original = sp_offset_get_source(SP_OFFSET(item));
2060 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2061 original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2062 } else if (SP_IS_FLOWTEXT(item)) {
2063 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2064 } else { // it's an object that we don't know what to do with
2065 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2066 return;
2067 }
2069 if (!original) {
2070 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2071 return;
2072 }
2074 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2075 if (SP_IS_DEFS(o)) {
2076 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2077 return;
2078 }
2079 }
2081 if (original) {
2082 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2083 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2084 if (highlight) {
2085 Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2086 Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2087 if ( a && b ) {
2088 // draw a flashing line between the objects
2089 SPCurve *curve = new SPCurve();
2090 curve->moveto(a->midpoint());
2091 curve->lineto(b->midpoint());
2093 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2094 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2095 sp_canvas_item_show(canvasitem);
2096 curve->unref();
2097 desktop->add_temporary_canvasitem(canvasitem, 1000);
2098 }
2099 }
2101 selection->clear();
2102 selection->set(original);
2103 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2104 scroll_to_show_item(desktop, original);
2105 }
2106 }
2107 }
2110 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2111 {
2112 if (desktop == NULL)
2113 return;
2115 SPDocument *doc = sp_desktop_document(desktop);
2116 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2118 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2120 // check if something is selected
2121 if (selection->isEmpty()) {
2122 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2123 return;
2124 }
2126 sp_document_ensure_up_to_date(doc);
2127 Geom::OptRect r = selection->bounds();
2128 boost::optional<Geom::Point> c = selection->center();
2129 if ( !r || !c ) {
2130 return;
2131 }
2133 // calculate the transform to be applied to objects to move them to 0,0
2134 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2135 move_p[Geom::Y] = -move_p[Geom::Y];
2136 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2138 GSList *items = g_slist_copy((GSList *) selection->itemList());
2140 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2142 // bottommost object, after sorting
2143 SPObject *parent = SP_OBJECT_PARENT(items->data);
2145 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2147 // remember the position of the first item
2148 gint pos = SP_OBJECT_REPR(items->data)->position();
2149 (void)pos; // TODO check why this was remembered
2151 // create a list of duplicates
2152 GSList *repr_copies = NULL;
2153 for (GSList *i = items; i != NULL; i = i->next) {
2154 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2155 repr_copies = g_slist_prepend(repr_copies, dup);
2156 }
2158 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2160 if (apply) {
2161 // delete objects so that their clones don't get alerted; this object will be restored shortly
2162 for (GSList *i = items; i != NULL; i = i->next) {
2163 SPObject *item = SP_OBJECT(i->data);
2164 item->deleteObject(false);
2165 }
2166 }
2168 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2169 // without disturbing clones.
2170 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2171 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2172 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2173 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2175 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2176 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2177 Geom::Point(r->min()[Geom::X],
2178 r->max()[Geom::Y]))))
2179 * parent_transform.inverse() ),
2180 parent_transform * move);
2181 (void)mark_id;
2183 // restore compensation setting
2184 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2187 g_slist_free(items);
2189 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2190 _("Objects to marker"));
2191 }
2193 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2194 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2195 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2196 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2197 }
2198 } else {
2199 sp_item_convert_item_to_guides(item);
2201 if (deleteitem) {
2202 SP_OBJECT(item)->deleteObject(true);
2203 }
2204 }
2205 }
2207 void sp_selection_to_guides(SPDesktop *desktop)
2208 {
2209 if (desktop == NULL)
2210 return;
2212 SPDocument *doc = sp_desktop_document(desktop);
2213 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2214 // we need to copy the list because it gets reset when objects are deleted
2215 GSList *items = g_slist_copy((GSList *) selection->itemList());
2217 if (!items) {
2218 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2219 return;
2220 }
2222 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2223 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2224 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2226 for (GSList const *i = items; i != NULL; i = i->next) {
2227 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2228 }
2230 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2231 }
2233 void
2234 sp_selection_tile(SPDesktop *desktop, bool apply)
2235 {
2236 if (desktop == NULL)
2237 return;
2239 SPDocument *doc = sp_desktop_document(desktop);
2240 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2242 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2244 // check if something is selected
2245 if (selection->isEmpty()) {
2246 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2247 return;
2248 }
2250 sp_document_ensure_up_to_date(doc);
2251 Geom::OptRect r = selection->bounds();
2252 if ( !r ) {
2253 return;
2254 }
2256 // calculate the transform to be applied to objects to move them to 0,0
2257 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2258 move_p[Geom::Y] = -move_p[Geom::Y];
2259 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2261 GSList *items = g_slist_copy((GSList *) selection->itemList());
2263 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2265 // bottommost object, after sorting
2266 SPObject *parent = SP_OBJECT_PARENT(items->data);
2268 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2270 // remember the position of the first item
2271 gint pos = SP_OBJECT_REPR(items->data)->position();
2273 // create a list of duplicates
2274 GSList *repr_copies = NULL;
2275 for (GSList *i = items; i != NULL; i = i->next) {
2276 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2277 repr_copies = g_slist_prepend(repr_copies, dup);
2278 }
2279 // restore the z-order after prepends
2280 repr_copies = g_slist_reverse(repr_copies);
2282 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2284 if (apply) {
2285 // delete objects so that their clones don't get alerted; this object will be restored shortly
2286 for (GSList *i = items; i != NULL; i = i->next) {
2287 SPObject *item = SP_OBJECT(i->data);
2288 item->deleteObject(false);
2289 }
2290 }
2292 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2293 // without disturbing clones.
2294 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2295 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2296 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2297 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2299 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2300 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2301 r->max()[Geom::Y]))))
2302 * to_2geom(parent_transform.inverse()) ),
2303 parent_transform * move);
2305 // restore compensation setting
2306 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2308 if (apply) {
2309 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2310 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2312 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2313 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2315 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2316 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2317 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2318 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2320 // restore parent and position
2321 SP_OBJECT_REPR(parent)->appendChild(rect);
2322 rect->setPosition(pos > 0 ? pos : 0);
2323 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2325 Inkscape::GC::release(rect);
2327 selection->clear();
2328 selection->set(rectangle);
2329 }
2331 g_slist_free(items);
2333 sp_document_done(doc, SP_VERB_EDIT_TILE,
2334 _("Objects to pattern"));
2335 }
2337 void
2338 sp_selection_untile(SPDesktop *desktop)
2339 {
2340 if (desktop == NULL)
2341 return;
2343 SPDocument *doc = sp_desktop_document(desktop);
2344 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2346 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2348 // check if something is selected
2349 if (selection->isEmpty()) {
2350 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2351 return;
2352 }
2354 GSList *new_select = NULL;
2356 bool did = false;
2358 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2359 items != NULL;
2360 items = items->next) {
2362 SPItem *item = (SPItem *) items->data;
2364 SPStyle *style = SP_OBJECT_STYLE(item);
2366 if (!style || !style->fill.isPaintserver())
2367 continue;
2369 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2371 if (!SP_IS_PATTERN(server))
2372 continue;
2374 did = true;
2376 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2378 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2379 pat_transform *= item->transform;
2381 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2382 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2383 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2385 // FIXME: relink clones to the new canvas objects
2386 // use SPObject::setid when mental finishes it to steal ids of
2388 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2389 sp_document_ensure_up_to_date(doc);
2391 Geom::Matrix transform( i->transform * pat_transform );
2392 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2394 new_select = g_slist_prepend(new_select, i);
2395 }
2397 SPCSSAttr *css = sp_repr_css_attr_new();
2398 sp_repr_css_set_property(css, "fill", "none");
2399 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2400 }
2402 if (!did) {
2403 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2404 } else {
2405 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2406 _("Pattern to objects"));
2407 selection->setList(new_select);
2408 }
2409 }
2411 void
2412 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2413 {
2414 if (selection->isEmpty()) {
2415 return;
2416 }
2418 GSList const *reprlst = selection->reprList();
2419 bool filename_search = TRUE;
2420 bool xdpi_search = TRUE;
2421 bool ydpi_search = TRUE;
2423 for (; reprlst != NULL &&
2424 filename_search &&
2425 xdpi_search &&
2426 ydpi_search;
2427 reprlst = reprlst->next) {
2428 gchar const *dpi_string;
2429 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2431 if (filename_search) {
2432 *filename = repr->attribute("inkscape:export-filename");
2433 if (*filename != NULL)
2434 filename_search = FALSE;
2435 }
2437 if (xdpi_search) {
2438 dpi_string = NULL;
2439 dpi_string = repr->attribute("inkscape:export-xdpi");
2440 if (dpi_string != NULL) {
2441 *xdpi = atof(dpi_string);
2442 xdpi_search = FALSE;
2443 }
2444 }
2446 if (ydpi_search) {
2447 dpi_string = NULL;
2448 dpi_string = repr->attribute("inkscape:export-ydpi");
2449 if (dpi_string != NULL) {
2450 *ydpi = atof(dpi_string);
2451 ydpi_search = FALSE;
2452 }
2453 }
2454 }
2455 }
2457 void
2458 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2459 {
2460 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2461 gchar const *dpi_string;
2463 *filename = repr->attribute("inkscape:export-filename");
2465 dpi_string = NULL;
2466 dpi_string = repr->attribute("inkscape:export-xdpi");
2467 if (dpi_string != NULL) {
2468 *xdpi = atof(dpi_string);
2469 }
2471 dpi_string = NULL;
2472 dpi_string = repr->attribute("inkscape:export-ydpi");
2473 if (dpi_string != NULL) {
2474 *ydpi = atof(dpi_string);
2475 }
2476 }
2478 void
2479 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2480 {
2481 if (desktop == NULL)
2482 return;
2484 SPDocument *document = sp_desktop_document(desktop);
2485 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2487 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2489 // check if something is selected
2490 if (selection->isEmpty()) {
2491 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2492 return;
2493 }
2495 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2496 // set "busy" cursor
2497 desktop->setWaitingCursor();
2499 // Get the bounding box of the selection
2500 NRRect bbox;
2501 sp_document_ensure_up_to_date(document);
2502 selection->bounds(&bbox);
2503 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2504 desktop->clearWaitingCursor();
2505 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2506 }
2508 // List of the items to show; all others will be hidden
2509 GSList *items = g_slist_copy((GSList *) selection->itemList());
2511 // Sort items so that the topmost comes last
2512 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2514 // Generate a random value from the current time (you may create bitmap from the same object(s)
2515 // multiple times, and this is done so that they don't clash)
2516 GTimeVal cu;
2517 g_get_current_time(&cu);
2518 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2520 // Create the filename.
2521 gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2522 document->name,
2523 SP_OBJECT_REPR(items->data)->attribute("id"),
2524 current);
2525 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2526 // digits, and a few other chars, with "_"
2527 g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2529 // Build the complete path by adding document base dir, if set, otherwise home dir
2530 gchar * directory = NULL;
2531 if (SP_DOCUMENT_URI(document)) {
2532 directory = g_dirname(SP_DOCUMENT_URI(document));
2533 }
2534 if (directory == NULL) {
2535 directory = homedir_path(NULL);
2536 }
2537 gchar *filepath = g_build_filename(directory, basename, NULL);
2539 //g_print("%s\n", filepath);
2541 // Remember parent and z-order of the topmost one
2542 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2543 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2544 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2546 // Calculate resolution
2547 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2548 double res;
2549 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2550 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2551 if (0 < prefs_res) {
2552 // If it's given explicitly in prefs, take it
2553 res = prefs_res;
2554 } else if (0 < prefs_min) {
2555 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2556 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2557 } else {
2558 float hint_xdpi = 0, hint_ydpi = 0;
2559 char const *hint_filename;
2560 // take resolution hint from the selected objects
2561 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2562 if (hint_xdpi != 0) {
2563 res = hint_xdpi;
2564 } else {
2565 // take resolution hint from the document
2566 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2567 if (hint_xdpi != 0) {
2568 res = hint_xdpi;
2569 } else {
2570 // if all else fails, take the default 90 dpi
2571 res = PX_PER_IN;
2572 }
2573 }
2574 }
2576 // The width and height of the bitmap in pixels
2577 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2578 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2580 // Find out if we have to run an external filter
2581 gchar const *run = NULL;
2582 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2583 if (!filter.empty()) {
2584 // filter command is given;
2585 // see if we have a parameter to pass to it
2586 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2587 if (!param1.empty()) {
2588 if (param1[param1.length() - 1] == '%') {
2589 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2590 gchar p1[256];
2591 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2592 // the first param is always the image filename, the second is param1
2593 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2594 } else {
2595 // otherwise pass the param1 unchanged
2596 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2597 }
2598 } else {
2599 // run without extra parameter
2600 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2601 }
2602 }
2604 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2605 Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2606 Geom::Matrix t;
2608 double shift_x = bbox.x0;
2609 double shift_y = bbox.y1;
2610 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2611 shift_x = round(shift_x);
2612 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2613 }
2614 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2616 // Do the export
2617 sp_export_png_file(document, filepath,
2618 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2619 width, height, res, res,
2620 (guint32) 0xffffff00,
2621 NULL, NULL,
2622 true, /*bool force_overwrite,*/
2623 items);
2625 g_slist_free(items);
2627 // Run filter, if any
2628 if (run) {
2629 g_print("Running external filter: %s\n", run);
2630 int retval;
2631 retval = system(run);
2632 }
2634 // Import the image back
2635 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2636 if (pb) {
2637 // Create the repr for the image
2638 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2639 {
2640 repr->setAttribute("sodipodi:absref", filepath);
2641 gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2642 repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2643 g_free(abs_base);
2644 }
2645 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2646 sp_repr_set_svg_double(repr, "width", width);
2647 sp_repr_set_svg_double(repr, "height", height);
2648 } else {
2649 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2650 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2651 }
2653 // Write transform
2654 gchar *c=sp_svg_transform_write(t);
2655 repr->setAttribute("transform", c);
2656 g_free(c);
2658 // add the new repr to the parent
2659 parent->appendChild(repr);
2661 // move to the saved position
2662 repr->setPosition(pos > 0 ? pos + 1 : 1);
2664 // Set selection to the new image
2665 selection->clear();
2666 selection->add(repr);
2668 // Clean up
2669 Inkscape::GC::release(repr);
2670 gdk_pixbuf_unref(pb);
2672 // Complete undoable transaction
2673 sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2674 _("Create bitmap"));
2675 }
2677 desktop->clearWaitingCursor();
2679 g_free(basename);
2680 g_free(filepath);
2681 }
2683 /**
2684 * \brief Creates a mask or clipPath from selection
2685 * Two different modes:
2686 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2687 * and is applied to current layer
2688 * otherwise, topmost object is used as mask for other objects
2689 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2690 *
2691 */
2692 void
2693 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2694 {
2695 if (desktop == NULL)
2696 return;
2698 SPDocument *doc = sp_desktop_document(desktop);
2699 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2701 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2703 // check if something is selected
2704 bool is_empty = selection->isEmpty();
2705 if ( apply_to_layer && is_empty) {
2706 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2707 return;
2708 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2709 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2710 return;
2711 }
2713 // FIXME: temporary patch to prevent crash!
2714 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2715 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2716 if (clone_with_original) {
2717 return; // in this version, you cannot clip/mask an object with its own clone
2718 }
2719 // /END FIXME
2721 sp_document_ensure_up_to_date(doc);
2723 GSList *items = g_slist_copy((GSList *) selection->itemList());
2725 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2727 // create a list of duplicates
2728 GSList *mask_items = NULL;
2729 GSList *apply_to_items = NULL;
2730 GSList *items_to_delete = NULL;
2731 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2732 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2733 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2735 if (apply_to_layer) {
2736 // all selected items are used for mask, which is applied to a layer
2737 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2739 for (GSList *i = items; i != NULL; i = i->next) {
2740 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2741 mask_items = g_slist_prepend(mask_items, dup);
2743 if (remove_original) {
2744 SPObject *item = SP_OBJECT(i->data);
2745 items_to_delete = g_slist_prepend(items_to_delete, item);
2746 }
2747 }
2748 } else if (!topmost) {
2749 // topmost item is used as a mask, which is applied to other items in a selection
2750 GSList *i = items;
2751 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2752 mask_items = g_slist_prepend(mask_items, dup);
2754 if (remove_original) {
2755 SPObject *item = SP_OBJECT(i->data);
2756 items_to_delete = g_slist_prepend(items_to_delete, item);
2757 }
2759 for (i = i->next; i != NULL; i = i->next) {
2760 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2761 }
2762 } else {
2763 GSList *i = NULL;
2764 for (i = items; NULL != i->next; i = i->next) {
2765 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2766 }
2768 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2769 mask_items = g_slist_prepend(mask_items, dup);
2771 if (remove_original) {
2772 SPObject *item = SP_OBJECT(i->data);
2773 items_to_delete = g_slist_prepend(items_to_delete, item);
2774 }
2775 }
2777 g_slist_free(items);
2778 items = NULL;
2780 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2781 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2782 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2783 // inverted object transform should be applied to a mask object,
2784 // as mask is calculated in user space (after applying transform)
2785 Geom::Matrix maskTransform(item->transform.inverse());
2787 GSList *mask_items_dup = NULL;
2788 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2789 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2790 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2791 }
2793 gchar const *mask_id = NULL;
2794 if (apply_clip_path) {
2795 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2796 } else {
2797 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2798 }
2800 g_slist_free(mask_items_dup);
2801 mask_items_dup = NULL;
2803 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2804 }
2806 g_slist_free(mask_items);
2807 g_slist_free(apply_to_items);
2809 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2810 SPObject *item = SP_OBJECT(i->data);
2811 item->deleteObject(false);
2812 }
2813 g_slist_free(items_to_delete);
2815 if (apply_clip_path)
2816 sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2817 else
2818 sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2819 }
2821 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2822 if (desktop == NULL)
2823 return;
2825 SPDocument *doc = sp_desktop_document(desktop);
2826 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2827 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2829 // check if something is selected
2830 if (selection->isEmpty()) {
2831 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2832 return;
2833 }
2835 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2836 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2837 sp_document_ensure_up_to_date(doc);
2839 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2840 std::map<SPObject*,SPItem*> referenced_objects;
2841 // SPObject* refers to a group containing the clipped path or mask itself,
2842 // whereas SPItem* refers to the item being clipped or masked
2843 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2844 if (remove_original) {
2845 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2846 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2847 Inkscape::URIReference *uri_ref = NULL;
2849 if (apply_clip_path) {
2850 uri_ref = item->clip_ref;
2851 } else {
2852 uri_ref = item->mask_ref;
2853 }
2855 // collect distinct mask object (and associate with item to apply transform)
2856 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2857 referenced_objects[uri_ref->getObject()] = item;
2858 }
2859 }
2861 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2862 }
2864 // restore mask objects into a document
2865 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2866 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2867 GSList *items_to_move = NULL;
2868 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2869 // Collect all clipped paths and masks within a single group
2870 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2871 items_to_move = g_slist_prepend(items_to_move, copy);
2872 }
2874 if (!obj->isReferenced()) {
2875 // delete from defs if no other object references this mask
2876 obj->deleteObject(false);
2877 }
2879 // remember parent and position of the item to which the clippath/mask was applied
2880 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2881 gint pos = SP_OBJECT_REPR((*it).second)->position();
2883 // Iterate through all clipped paths / masks
2884 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2885 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2887 // insert into parent, restore pos
2888 parent->appendChild(repr);
2889 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2891 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
2892 selection->add(repr);
2894 // transform mask, so it is moved the same spot where mask was applied
2895 Geom::Matrix transform(mask_item->transform);
2896 transform *= (*it).second->transform;
2897 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2898 }
2900 g_slist_free(items_to_move);
2901 }
2903 if (apply_clip_path)
2904 sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2905 else
2906 sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2907 }
2909 /**
2910 * Returns true if an undoable change should be recorded.
2911 */
2912 bool
2913 fit_canvas_to_selection(SPDesktop *desktop)
2914 {
2915 g_return_val_if_fail(desktop != NULL, false);
2916 SPDocument *doc = sp_desktop_document(desktop);
2918 g_return_val_if_fail(doc != NULL, false);
2919 g_return_val_if_fail(desktop->selection != NULL, false);
2921 if (desktop->selection->isEmpty()) {
2922 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2923 return false;
2924 }
2925 Geom::OptRect const bbox(desktop->selection->bounds());
2926 if (bbox) {
2927 doc->fitToRect(*bbox);
2928 return true;
2929 } else {
2930 return false;
2931 }
2932 }
2934 /**
2935 * Fit canvas to the bounding box of the selection, as an undoable action.
2936 */
2937 void
2938 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2939 {
2940 if (fit_canvas_to_selection(desktop)) {
2941 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2942 _("Fit Page to Selection"));
2943 }
2944 }
2946 bool
2947 fit_canvas_to_drawing(SPDocument *doc)
2948 {
2949 g_return_val_if_fail(doc != NULL, false);
2951 sp_document_ensure_up_to_date(doc);
2952 SPItem const *const root = SP_ITEM(doc->root);
2953 Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2954 if (bbox) {
2955 doc->fitToRect(*bbox);
2956 return true;
2957 } else {
2958 return false;
2959 }
2960 }
2962 void
2963 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2964 {
2965 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2966 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2967 _("Fit Page to Drawing"));
2968 }
2969 }
2971 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2972 g_return_if_fail(desktop != NULL);
2973 SPDocument *doc = sp_desktop_document(desktop);
2975 g_return_if_fail(doc != NULL);
2976 g_return_if_fail(desktop->selection != NULL);
2978 bool const changed = ( desktop->selection->isEmpty()
2979 ? fit_canvas_to_drawing(doc)
2980 : fit_canvas_to_selection(desktop) );
2981 if (changed) {
2982 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2983 _("Fit Page to Selection or Drawing"));
2984 }
2985 };
2987 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2988 // don't operate on layers
2989 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2990 f(SP_ITEM(root), desktop);
2991 }
2992 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2993 //don't recurse into locked layers
2994 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2995 itemtree_map(f, iter, desktop);
2996 }
2997 }
2998 }
3000 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3001 if (item->isLocked()) {
3002 item->setLocked(FALSE);
3003 }
3004 }
3006 static void unhide(SPItem *item, SPDesktop *desktop) {
3007 if (desktop->itemIsHidden(item)) {
3008 item->setExplicitlyHidden(FALSE);
3009 }
3010 }
3012 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3013 if (!dt) return;
3015 SPObject *root;
3016 if (layer_only) {
3017 root = dt->currentLayer();
3018 } else {
3019 root = dt->currentRoot();
3020 }
3022 itemtree_map(f, root, dt);
3023 }
3025 void unlock_all(SPDesktop *dt) {
3026 process_all(&unlock, dt, true);
3027 }
3029 void unlock_all_in_all_layers(SPDesktop *dt) {
3030 process_all(&unlock, dt, false);
3031 }
3033 void unhide_all(SPDesktop *dt) {
3034 process_all(&unhide, dt, true);
3035 }
3037 void unhide_all_in_all_layers(SPDesktop *dt) {
3038 process_all(&unhide, dt, false);
3039 }
3042 /*
3043 Local Variables:
3044 mode:c++
3045 c-file-style:"stroustrup"
3046 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3047 indent-tabs-mode:nil
3048 fill-column:99
3049 End:
3050 */
3051 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :