1 #define __SP_SELECTION_CHEMISTRY_C__
3 /** @file
4 * @brief Miscellanous operations on selected items
5 */
6 /* Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * Frank Felfe <innerspace@iname.com>
9 * MenTaLguY <mental@rydia.net>
10 * bulia byak <buliabyak@users.sf.net>
11 * Andrius R. <knutux@gmail.com>
12 *
13 * Copyright (C) 1999-2006 authors
14 * Copyright (C) 2001-2002 Ximian, Inc.
15 *
16 * Released under GNU GPL, read the file 'COPYING' for more information
17 */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "desktop.h"
29 #include "desktop-style.h"
30 #include "selection.h"
31 #include "tools-switch.h"
32 #include "desktop-handles.h"
33 #include "message-stack.h"
34 #include "sp-item-transform.h"
35 #include "marker.h"
36 #include "sp-use.h"
37 #include "sp-textpath.h"
38 #include "sp-tspan.h"
39 #include "sp-tref.h"
40 #include "sp-flowtext.h"
41 #include "sp-flowregion.h"
42 #include "text-editing.h"
43 #include "text-context.h"
44 #include "connector-context.h"
45 #include "sp-path.h"
46 #include "sp-conn-end.h"
47 #include "dropper-context.h"
48 #include <glibmm/i18n.h>
49 #include "libnr/nr-matrix-rotate-ops.h"
50 #include "libnr/nr-matrix-translate-ops.h"
51 #include "libnr/nr-scale-ops.h"
52 #include <libnr/nr-matrix-ops.h>
53 #include <2geom/transforms.h>
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "preferences.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include <cstring>
73 #include <string>
74 #include "helper/units.h"
75 #include "sp-item.h"
76 #include "box3d.h"
77 #include "unit-constants.h"
78 #include "xml/simple-document.h"
79 #include "sp-filter-reference.h"
80 #include "gradient-drag.h"
81 #include "uri-references.h"
82 #include "libnr/nr-convert2geom.h"
83 #include "display/curve.h"
84 #include "display/canvas-bpath.h"
85 #include "inkscape-private.h"
87 // For clippath editing
88 #include "tools-switch.h"
89 #include "shape-editor.h"
90 #include "node-context.h"
91 #include "nodepath.h"
93 #include "ui/clipboard.h"
95 using Geom::X;
96 using Geom::Y;
98 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
99 because the layer manipulation code uses them. It should be rewritten specifically
100 for that purpose. */
102 /**
103 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
104 * then prepends the copy to 'clip'.
105 */
106 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
107 {
108 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
110 // copy complete inherited style
111 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
112 sp_repr_css_set(copy, css, "style");
113 sp_repr_css_attr_unref(css);
115 // write the complete accumulated transform passed to us
116 // (we're dealing with unattached repr, so we write to its attr
117 // instead of using sp_item_set_transform)
118 gchar *affinestr=sp_svg_transform_write(full_t);
119 copy->setAttribute("transform", affinestr);
120 g_free(affinestr);
122 *clip = g_slist_prepend(*clip, copy);
123 }
125 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
126 {
127 // Sort items:
128 GSList *sorted_items = g_slist_copy((GSList *) items);
129 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
131 // Copy item reprs:
132 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
133 sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
134 }
136 *clip = g_slist_reverse(*clip);
137 g_slist_free((GSList *) sorted_items);
138 }
140 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
141 {
142 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
144 GSList *copied = NULL;
145 // add objects to document
146 for (GSList *l = *clip; l != NULL; l = l->next) {
147 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
148 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
150 // premultiply the item transform by the accumulated parent transform in the paste layer
151 Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
152 if (!local.isIdentity()) {
153 gchar const *t_str = copy->attribute("transform");
154 Geom::Matrix item_t(Geom::identity());
155 if (t_str)
156 sp_svg_transform_read(t_str, &item_t);
157 item_t *= local.inverse();
158 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
159 gchar *affinestr=sp_svg_transform_write(item_t);
160 copy->setAttribute("transform", affinestr);
161 g_free(affinestr);
162 }
164 parent->appendChildRepr(copy);
165 copied = g_slist_prepend(copied, copy);
166 Inkscape::GC::release(copy);
167 }
168 return copied;
169 }
171 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
172 {
173 for (GSList const *i = items ; i ; i = i->next ) {
174 sp_object_ref((SPObject *)i->data, NULL);
175 }
176 for (GSList const *i = items; i != NULL; i = i->next) {
177 SPItem *item = (SPItem *) i->data;
178 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
179 sp_object_unref((SPObject *)item, NULL);
180 }
181 }
184 void sp_selection_delete(SPDesktop *desktop)
185 {
186 if (desktop == NULL) {
187 return;
188 }
190 if (tools_isactive(desktop, TOOLS_TEXT))
191 if (sp_text_delete_selection(desktop->event_context)) {
192 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
193 _("Delete text"));
194 return;
195 }
197 Inkscape::Selection *selection = sp_desktop_selection(desktop);
199 // check if something is selected
200 if (selection->isEmpty()) {
201 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
202 return;
203 }
205 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
206 selection->clear();
207 sp_selection_delete_impl(selected);
208 g_slist_free((GSList *) selected);
210 /* a tool may have set up private information in it's selection context
211 * that depends on desktop items. I think the only sane way to deal with
212 * this currently is to reset the current tool, which will reset it's
213 * associated selection context. For example: deleting an object
214 * while moving it around the canvas.
215 */
216 tools_switch( desktop, tools_active( desktop ) );
218 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
219 _("Delete"));
220 }
222 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
223 {
224 if (!obj)
225 return;
227 ids.push_back(SP_OBJECT_ID(obj));
229 if (SP_IS_GROUP(obj)) {
230 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
231 add_ids_recursive(ids, child);
232 }
233 }
234 }
236 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
237 {
238 if (desktop == NULL)
239 return;
241 SPDocument *doc = desktop->doc();
242 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
243 Inkscape::Selection *selection = sp_desktop_selection(desktop);
245 // check if something is selected
246 if (selection->isEmpty()) {
247 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
248 return;
249 }
251 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
253 selection->clear();
255 // sorting items from different parents sorts each parent's subset without possibly mixing
256 // them, just what we need
257 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
259 GSList *newsel = NULL;
261 std::vector<const gchar *> old_ids;
262 std::vector<const gchar *> new_ids;
263 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
264 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
266 while (reprs) {
267 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
268 Inkscape::XML::Node *parent = old_repr->parent();
269 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
271 parent->appendChild(copy);
273 if (relink_clones) {
274 SPObject *old_obj = doc->getObjectByRepr(old_repr);
275 SPObject *new_obj = doc->getObjectByRepr(copy);
276 add_ids_recursive(old_ids, old_obj);
277 add_ids_recursive(new_ids, new_obj);
278 }
280 newsel = g_slist_prepend(newsel, copy);
281 reprs = g_slist_remove(reprs, reprs->data);
282 Inkscape::GC::release(copy);
283 }
285 if (relink_clones) {
287 g_assert(old_ids.size() == new_ids.size());
289 for (unsigned int i = 0; i < old_ids.size(); i++) {
290 const gchar *id = old_ids[i];
291 SPObject *old_clone = doc->getObjectById(id);
292 if (SP_IS_USE(old_clone)) {
293 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
294 if (!orig) // orphaned
295 continue;
296 for (unsigned int j = 0; j < old_ids.size(); j++) {
297 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
298 // we have both orig and clone in selection, relink
299 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
300 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
301 SPObject *new_clone = doc->getObjectById(new_ids[i]);
302 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
303 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
304 g_free(newref);
305 }
306 }
307 }
308 }
309 }
312 if ( !suppressDone ) {
313 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
314 _("Duplicate"));
315 }
317 selection->setReprList(newsel);
319 g_slist_free(newsel);
320 }
322 void sp_edit_clear_all(SPDesktop *dt)
323 {
324 if (!dt)
325 return;
327 SPDocument *doc = sp_desktop_document(dt);
328 sp_desktop_selection(dt)->clear();
330 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
331 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
333 while (items) {
334 SP_OBJECT(items->data)->deleteObject();
335 items = g_slist_remove(items, items->data);
336 }
338 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
339 _("Delete all"));
340 }
342 GSList *
343 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
344 {
345 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
346 if (SP_IS_ITEM(child) &&
347 !desktop->isLayer(SP_ITEM(child)) &&
348 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
349 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
350 (!exclude || !g_slist_find((GSList *) exclude, child))
351 )
352 {
353 list = g_slist_prepend(list, SP_ITEM(child));
354 }
356 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
357 list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
358 }
359 }
361 return list;
362 }
364 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
365 {
366 if (!dt)
367 return;
369 Inkscape::Selection *selection = sp_desktop_selection(dt);
371 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
373 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
374 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
375 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
376 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
378 GSList *items = NULL;
380 GSList const *exclude = NULL;
381 if (invert) {
382 exclude = selection->itemList();
383 }
385 if (force_all_layers)
386 inlayer = PREFS_SELECTION_ALL;
388 switch (inlayer) {
389 case PREFS_SELECTION_LAYER: {
390 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
391 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
392 return;
394 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
396 for (GSList *i = all_items; i; i = i->next) {
397 SPItem *item = SP_ITEM(i->data);
399 if (item && (!onlysensitive || !item->isLocked())) {
400 if (!onlyvisible || !dt->itemIsHidden(item)) {
401 if (!dt->isLayer(item)) {
402 if (!invert || !g_slist_find((GSList *) exclude, item)) {
403 items = g_slist_prepend(items, item); // leave it in the list
404 }
405 }
406 }
407 }
408 }
410 g_slist_free(all_items);
411 break;
412 }
413 case PREFS_SELECTION_LAYER_RECURSIVE: {
414 items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
415 break;
416 }
417 default: {
418 items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
419 break;
420 }
421 }
423 selection->setList(items);
425 if (items) {
426 g_slist_free(items);
427 }
428 }
430 void sp_edit_select_all(SPDesktop *desktop)
431 {
432 sp_edit_select_all_full(desktop, false, false);
433 }
435 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
436 {
437 sp_edit_select_all_full(desktop, true, false);
438 }
440 void sp_edit_invert(SPDesktop *desktop)
441 {
442 sp_edit_select_all_full(desktop, false, true);
443 }
445 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
446 {
447 sp_edit_select_all_full(desktop, true, true);
448 }
450 void sp_selection_group(SPDesktop *desktop)
451 {
452 if (desktop == NULL)
453 return;
455 SPDocument *doc = sp_desktop_document(desktop);
456 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
458 Inkscape::Selection *selection = sp_desktop_selection(desktop);
460 // Check if something is selected.
461 if (selection->isEmpty()) {
462 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
463 return;
464 }
466 GSList const *l = (GSList *) selection->reprList();
468 GSList *p = g_slist_copy((GSList *) l);
470 selection->clear();
472 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
474 // Remember the position and parent of the topmost object.
475 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
476 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
478 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
480 while (p) {
481 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
483 if (current->parent() == topmost_parent) {
484 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
485 sp_repr_unparent(current);
486 group->appendChild(spnew);
487 Inkscape::GC::release(spnew);
488 topmost --; // only reduce count for those items deleted from topmost_parent
489 } else { // move it to topmost_parent first
490 GSList *temp_clip = NULL;
492 // At this point, current may already have no item, due to its being a clone whose original is already moved away
493 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
494 gchar const *t_str = current->attribute("transform");
495 Geom::Matrix item_t(Geom::identity());
496 if (t_str)
497 sp_svg_transform_read(t_str, &item_t);
498 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
499 // FIXME: when moving both clone and original from a transformed group (either by
500 // grouping into another parent, or by cut/paste) the transform from the original's
501 // parent becomes embedded into original itself, and this affects its clones. Fix
502 // this by remembering the transform diffs we write to each item into an array and
503 // then, if this is clone, looking up its original in that array and pre-multiplying
504 // it by the inverse of that original's transform diff.
506 sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
507 sp_repr_unparent(current);
509 // paste into topmost_parent (temporarily)
510 GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
511 if (temp_clip) g_slist_free(temp_clip);
512 if (copied) { // if success,
513 // take pasted object (now in topmost_parent)
514 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
515 // make a copy
516 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
517 // remove pasted
518 sp_repr_unparent(in_topmost);
519 // put its copy into group
520 group->appendChild(spnew);
521 Inkscape::GC::release(spnew);
522 g_slist_free(copied);
523 }
524 }
525 p = g_slist_remove(p, current);
526 }
528 // Add the new group to the topmost members' parent
529 topmost_parent->appendChild(group);
531 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
532 group->setPosition(topmost + 1);
534 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
535 _("Group"));
537 selection->set(group);
538 Inkscape::GC::release(group);
539 }
541 void sp_selection_ungroup(SPDesktop *desktop)
542 {
543 if (desktop == NULL)
544 return;
546 Inkscape::Selection *selection = sp_desktop_selection(desktop);
548 if (selection->isEmpty()) {
549 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
550 return;
551 }
553 GSList *items = g_slist_copy((GSList *) selection->itemList());
554 selection->clear();
556 // Get a copy of current selection.
557 GSList *new_select = NULL;
558 bool ungrouped = false;
559 for (GSList *i = items;
560 i != NULL;
561 i = i->next)
562 {
563 SPItem *group = (SPItem *) i->data;
565 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
566 if (!SP_IS_OBJECT(group)) {
567 continue;
568 }
570 /* We do not allow ungrouping <svg> etc. (lauris) */
571 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
572 // keep the non-group item in the new selection
573 selection->add(group);
574 continue;
575 }
577 GSList *children = NULL;
578 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
579 sp_item_group_ungroup(SP_GROUP(group), &children, false);
580 ungrouped = true;
581 // Add ungrouped items to the new selection.
582 new_select = g_slist_concat(new_select, children);
583 }
585 if (new_select) { // Set new selection.
586 selection->addList(new_select);
587 g_slist_free(new_select);
588 }
589 if (!ungrouped) {
590 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
591 }
593 g_slist_free(items);
595 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
596 _("Ungroup"));
597 }
599 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
600 GSList *
601 sp_degroup_list(GSList *items)
602 {
603 GSList *out = NULL;
604 bool has_groups = false;
605 for (GSList *item = items; item; item = item->next) {
606 if (!SP_IS_GROUP(item->data)) {
607 out = g_slist_prepend(out, item->data);
608 } else {
609 has_groups = true;
610 GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
611 for (GSList *member = members; member; member = member->next) {
612 out = g_slist_prepend(out, member->data);
613 }
614 g_slist_free(members);
615 }
616 }
617 out = g_slist_reverse(out);
618 g_slist_free(items);
620 if (has_groups) { // recurse if we unwrapped a group - it may have contained others
621 out = sp_degroup_list(out);
622 }
624 return out;
625 }
628 /** If items in the list have a common parent, return it, otherwise return NULL */
629 static SPGroup *
630 sp_item_list_common_parent_group(GSList const *items)
631 {
632 if (!items) {
633 return NULL;
634 }
635 SPObject *parent = SP_OBJECT_PARENT(items->data);
636 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
637 if (!SP_IS_GROUP(parent)) {
638 return NULL;
639 }
640 for (items = items->next; items; items = items->next) {
641 if (SP_OBJECT_PARENT(items->data) != parent) {
642 return NULL;
643 }
644 }
646 return SP_GROUP(parent);
647 }
649 /** Finds out the minimum common bbox of the selected items. */
650 static Geom::OptRect
651 enclose_items(GSList const *items)
652 {
653 g_assert(items != NULL);
655 Geom::OptRect r;
656 for (GSList const *i = items; i; i = i->next) {
657 r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
658 }
659 return r;
660 }
662 SPObject *
663 prev_sibling(SPObject *child)
664 {
665 SPObject *parent = SP_OBJECT_PARENT(child);
666 if (!SP_IS_GROUP(parent)) {
667 return NULL;
668 }
669 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
670 if (i->next == child)
671 return i;
672 }
673 return NULL;
674 }
676 void
677 sp_selection_raise(SPDesktop *desktop)
678 {
679 if (!desktop)
680 return;
682 Inkscape::Selection *selection = sp_desktop_selection(desktop);
684 GSList const *items = (GSList *) selection->itemList();
685 if (!items) {
686 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
687 return;
688 }
690 SPGroup const *group = sp_item_list_common_parent_group(items);
691 if (!group) {
692 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
693 return;
694 }
696 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
698 /* Construct reverse-ordered list of selected children. */
699 GSList *rev = g_slist_copy((GSList *) items);
700 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
702 // Determine the common bbox of the selected items.
703 Geom::OptRect selected = enclose_items(items);
705 // Iterate over all objects in the selection (starting from top).
706 if (selected) {
707 while (rev) {
708 SPObject *child = SP_OBJECT(rev->data);
709 // for each selected object, find the next sibling
710 for (SPObject *newref = child->next; newref; newref = newref->next) {
711 // if the sibling is an item AND overlaps our selection,
712 if (SP_IS_ITEM(newref)) {
713 Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
714 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
715 // AND if it's not one of our selected objects,
716 if (!g_slist_find((GSList *) items, newref)) {
717 // move the selected object after that sibling
718 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
719 }
720 break;
721 }
722 }
723 }
724 rev = g_slist_remove(rev, child);
725 }
726 } else {
727 g_slist_free(rev);
728 }
730 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
731 //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
732 Q_("undo_action|Raise"));
733 }
735 void sp_selection_raise_to_top(SPDesktop *desktop)
736 {
737 if (desktop == NULL)
738 return;
740 SPDocument *document = sp_desktop_document(desktop);
741 Inkscape::Selection *selection = sp_desktop_selection(desktop);
743 if (selection->isEmpty()) {
744 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
745 return;
746 }
748 GSList const *items = (GSList *) selection->itemList();
750 SPGroup const *group = sp_item_list_common_parent_group(items);
751 if (!group) {
752 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
753 return;
754 }
756 GSList *rl = g_slist_copy((GSList *) selection->reprList());
757 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
759 for (GSList *l = rl; l != NULL; l = l->next) {
760 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
761 repr->setPosition(-1);
762 }
764 g_slist_free(rl);
766 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
767 _("Raise to top"));
768 }
770 void
771 sp_selection_lower(SPDesktop *desktop)
772 {
773 if (desktop == NULL)
774 return;
776 Inkscape::Selection *selection = sp_desktop_selection(desktop);
778 GSList const *items = (GSList *) selection->itemList();
779 if (!items) {
780 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
781 return;
782 }
784 SPGroup const *group = sp_item_list_common_parent_group(items);
785 if (!group) {
786 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
787 return;
788 }
790 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
792 // Determine the common bbox of the selected items.
793 Geom::OptRect selected = enclose_items(items);
795 /* Construct direct-ordered list of selected children. */
796 GSList *rev = g_slist_copy((GSList *) items);
797 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
798 rev = g_slist_reverse(rev);
800 // Iterate over all objects in the selection (starting from top).
801 if (selected) {
802 while (rev) {
803 SPObject *child = SP_OBJECT(rev->data);
804 // for each selected object, find the prev sibling
805 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
806 // if the sibling is an item AND overlaps our selection,
807 if (SP_IS_ITEM(newref)) {
808 Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
809 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
810 // AND if it's not one of our selected objects,
811 if (!g_slist_find((GSList *) items, newref)) {
812 // move the selected object before that sibling
813 SPObject *put_after = prev_sibling(newref);
814 if (put_after)
815 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
816 else
817 SP_OBJECT_REPR(child)->setPosition(0);
818 }
819 break;
820 }
821 }
822 }
823 rev = g_slist_remove(rev, child);
824 }
825 } else {
826 g_slist_free(rev);
827 }
829 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
830 _("Lower"));
831 }
833 void sp_selection_lower_to_bottom(SPDesktop *desktop)
834 {
835 if (desktop == NULL)
836 return;
838 SPDocument *document = sp_desktop_document(desktop);
839 Inkscape::Selection *selection = sp_desktop_selection(desktop);
841 if (selection->isEmpty()) {
842 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
843 return;
844 }
846 GSList const *items = (GSList *) selection->itemList();
848 SPGroup const *group = sp_item_list_common_parent_group(items);
849 if (!group) {
850 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
851 return;
852 }
854 GSList *rl;
855 rl = g_slist_copy((GSList *) selection->reprList());
856 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
857 rl = g_slist_reverse(rl);
859 for (GSList *l = rl; l != NULL; l = l->next) {
860 gint minpos;
861 SPObject *pp, *pc;
862 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
863 pp = document->getObjectByRepr(sp_repr_parent(repr));
864 minpos = 0;
865 g_assert(SP_IS_GROUP(pp));
866 pc = sp_object_first_child(pp);
867 while (!SP_IS_ITEM(pc)) {
868 minpos += 1;
869 pc = pc->next;
870 }
871 repr->setPosition(minpos);
872 }
874 g_slist_free(rl);
876 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
877 _("Lower to bottom"));
878 }
880 void
881 sp_undo(SPDesktop *desktop, SPDocument *)
882 {
883 if (!sp_document_undo(sp_desktop_document(desktop)))
884 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
885 }
887 void
888 sp_redo(SPDesktop *desktop, SPDocument *)
889 {
890 if (!sp_document_redo(sp_desktop_document(desktop)))
891 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
892 }
894 void sp_selection_cut(SPDesktop *desktop)
895 {
896 sp_selection_copy();
897 sp_selection_delete(desktop);
898 }
900 /**
901 * \pre item != NULL
902 */
903 SPCSSAttr *
904 take_style_from_item(SPItem *item)
905 {
906 // write the complete cascaded style, context-free
907 SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
908 if (css == NULL)
909 return NULL;
911 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
912 (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
913 // if this is a text with exactly one tspan child, merge the style of that tspan as well
914 // If this is a group, merge the style of its topmost (last) child with style
915 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
916 if (SP_OBJECT_STYLE(last_element) != NULL) {
917 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
918 if (temp) {
919 sp_repr_css_merge(css, temp);
920 sp_repr_css_attr_unref(temp);
921 }
922 break;
923 }
924 }
925 }
926 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
927 // do not copy text properties from non-text objects, it's confusing
928 css = sp_css_attr_unset_text(css);
929 }
931 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
932 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
933 if (ex != 1.0) {
934 css = sp_css_attr_scale(css, ex);
935 }
937 return css;
938 }
941 void sp_selection_copy()
942 {
943 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
944 cm->copy();
945 }
947 void sp_selection_paste(SPDesktop *desktop, bool in_place)
948 {
949 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
950 if (cm->paste(in_place))
951 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
952 }
954 void sp_selection_paste_style(SPDesktop *desktop)
955 {
956 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
957 if (cm->pasteStyle())
958 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
959 }
962 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
963 {
964 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
965 if (cm->pastePathEffect())
966 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
967 _("Paste live path effect"));
968 }
971 void sp_selection_remove_livepatheffect_impl(SPItem *item)
972 {
973 if ( item && SP_IS_LPE_ITEM(item) &&
974 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
975 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
976 }
977 }
979 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
980 {
981 if (desktop == NULL) return;
983 Inkscape::Selection *selection = sp_desktop_selection(desktop);
985 // check if something is selected
986 if (selection->isEmpty()) {
987 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
988 return;
989 }
991 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
992 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
994 sp_selection_remove_livepatheffect_impl(item);
996 }
998 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
999 _("Remove live path effect"));
1000 }
1002 void sp_selection_remove_filter(SPDesktop *desktop)
1003 {
1004 if (desktop == NULL) return;
1006 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1008 // check if something is selected
1009 if (selection->isEmpty()) {
1010 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1011 return;
1012 }
1014 SPCSSAttr *css = sp_repr_css_attr_new();
1015 sp_repr_css_unset_property(css, "filter");
1016 sp_desktop_set_style(desktop, css);
1017 sp_repr_css_attr_unref(css);
1019 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1020 _("Remove filter"));
1021 }
1024 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1025 {
1026 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1027 if (cm->pasteSize(false, apply_x, apply_y))
1028 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1029 _("Paste size"));
1030 }
1032 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1033 {
1034 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1035 if (cm->pasteSize(true, apply_x, apply_y))
1036 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1037 _("Paste size separately"));
1038 }
1040 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1041 {
1042 Inkscape::Selection *selection = sp_desktop_selection(dt);
1044 // check if something is selected
1045 if (selection->isEmpty()) {
1046 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1047 return;
1048 }
1050 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1052 bool no_more = false; // Set to true, if no more layers above
1053 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1054 if (next) {
1055 GSList *temp_clip = NULL;
1056 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1057 sp_selection_delete_impl(items, false, false);
1058 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1059 GSList *copied;
1060 if (next) {
1061 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1062 } else {
1063 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1064 no_more = true;
1065 }
1066 selection->setReprList((GSList const *) copied);
1067 g_slist_free(copied);
1068 if (temp_clip) g_slist_free(temp_clip);
1069 if (next) dt->setCurrentLayer(next);
1070 if ( !suppressDone ) {
1071 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1072 _("Raise to next layer"));
1073 }
1074 } else {
1075 no_more = true;
1076 }
1078 if (no_more) {
1079 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1080 }
1082 g_slist_free((GSList *) items);
1083 }
1085 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1086 {
1087 Inkscape::Selection *selection = sp_desktop_selection(dt);
1089 // check if something is selected
1090 if (selection->isEmpty()) {
1091 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1092 return;
1093 }
1095 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1097 bool no_more = false; // Set to true, if no more layers below
1098 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1099 if (next) {
1100 GSList *temp_clip = NULL;
1101 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
1102 sp_selection_delete_impl(items, false, false);
1103 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1104 GSList *copied;
1105 if (next) {
1106 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1107 } else {
1108 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1109 no_more = true;
1110 }
1111 selection->setReprList((GSList const *) copied);
1112 g_slist_free(copied);
1113 if (temp_clip) g_slist_free(temp_clip);
1114 if (next) dt->setCurrentLayer(next);
1115 if ( !suppressDone ) {
1116 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1117 _("Lower to previous layer"));
1118 }
1119 } else {
1120 no_more = true;
1121 }
1123 if (no_more) {
1124 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1125 }
1127 g_slist_free((GSList *) items);
1128 }
1130 bool
1131 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1132 {
1133 bool contains_original = false;
1135 bool is_use = SP_IS_USE(item);
1136 SPItem *item_use = item;
1137 SPItem *item_use_first = item;
1138 while (is_use && item_use && !contains_original)
1139 {
1140 item_use = sp_use_get_original(SP_USE(item_use));
1141 contains_original |= selection->includes(item_use);
1142 if (item_use == item_use_first)
1143 break;
1144 is_use = SP_IS_USE(item_use);
1145 }
1147 // If it's a tref, check whether the object containing the character
1148 // data is part of the selection
1149 if (!contains_original && SP_IS_TREF(item)) {
1150 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1151 }
1153 return contains_original;
1154 }
1157 bool
1158 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1159 {
1160 bool clone_with_original = false;
1161 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1162 SPItem *item = SP_ITEM(l->data);
1163 clone_with_original |= selection_contains_original(item, selection);
1164 if (clone_with_original)
1165 break;
1166 }
1167 return clone_with_original;
1168 }
1171 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1172 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1173 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1174 that case, items are already in the new position, but the repr is in the old, and this function
1175 then simply updates the repr from item->transform.
1176 */
1177 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1178 {
1179 if (selection->isEmpty())
1180 return;
1182 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1183 SPItem *item = SP_ITEM(l->data);
1185 Geom::Point old_center(0,0);
1186 if (set_i2d && item->isCenterSet())
1187 old_center = item->getCenter();
1189 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1190 At the time of writing, this is the only place to re-enable. */
1191 sp_item_update_cns(*item, selection->desktop());
1192 #endif
1194 // we're moving both a clone and its original or any ancestor in clone chain?
1195 bool transform_clone_with_original = selection_contains_original(item, selection);
1196 // ...both a text-on-path and its path?
1197 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)))) ));
1198 // ...both a flowtext and its frame?
1199 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)
1200 // ...both an offset and its source?
1201 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1203 // If we're moving a connector, we want to detach it
1204 // from shapes that aren't part of the selection, but
1205 // leave it attached if they are
1206 if (cc_item_is_connector(item)) {
1207 SPItem *attItem[2];
1208 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1210 for (int n = 0; n < 2; ++n) {
1211 if (!selection->includes(attItem[n])) {
1212 sp_conn_end_detach(item, n);
1213 }
1214 }
1215 }
1217 // "clones are unmoved when original is moved" preference
1218 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1219 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1220 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1221 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1223 /* If this is a clone and it's selected along with its original, do not move it;
1224 * it will feel the transform of its original and respond to it itself.
1225 * Without this, a clone is doubly transformed, very unintuitive.
1226 *
1227 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1228 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1229 * Same for linked offset if we are also moving its source: do not move it. */
1230 if (transform_textpath_with_path || transform_offset_with_source) {
1231 // Restore item->transform field from the repr, in case it was changed by seltrans.
1232 sp_object_read_attr(SP_OBJECT(item), "transform");
1233 } else if (transform_flowtext_with_frame) {
1234 // apply the inverse of the region's transform to the <use> so that the flow remains
1235 // the same (even though the output itself gets transformed)
1236 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1237 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1238 continue;
1239 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1240 if (!SP_IS_USE(use)) continue;
1241 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1242 }
1243 }
1244 } else if (transform_clone_with_original) {
1245 // We are transforming a clone along with its original. The below matrix juggling is
1246 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1247 // transform and its move compensation are both cancelled out.
1249 // restore item->transform field from the repr, in case it was changed by seltrans
1250 sp_object_read_attr(SP_OBJECT(item), "transform");
1252 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1253 Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1254 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1255 Geom::Matrix t_inv = t.inverse();
1256 Geom::Matrix result = t_inv * item->transform * t;
1258 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1259 // we need to cancel out the move compensation, too
1261 // find out the clone move, same as in sp_use_move_compensate
1262 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1263 Geom::Matrix clone_move = parent.inverse() * t * parent;
1265 if (prefs_parallel) {
1266 Geom::Matrix move = result * clone_move * t_inv;
1267 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1269 } else if (prefs_unmoved) {
1270 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1271 // clone_move = Geom::identity();
1272 Geom::Matrix move = result * clone_move;
1273 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1274 }
1276 } else {
1277 // just apply the result
1278 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1279 }
1281 } else {
1282 if (set_i2d) {
1283 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1284 }
1285 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1286 }
1288 // if we're moving the actual object, not just updating the repr, we can transform the
1289 // center by the same matrix (only necessary for non-translations)
1290 if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1291 item->setCenter(old_center * affine);
1292 SP_OBJECT(item)->updateRepr();
1293 }
1294 }
1295 }
1297 void sp_selection_remove_transform(SPDesktop *desktop)
1298 {
1299 if (desktop == NULL)
1300 return;
1302 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1304 GSList const *l = (GSList *) selection->reprList();
1305 while (l != NULL) {
1306 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1307 l = l->next;
1308 }
1310 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1311 _("Remove transform"));
1312 }
1314 void
1315 sp_selection_scale_absolute(Inkscape::Selection *selection,
1316 double const x0, double const x1,
1317 double const y0, double const y1)
1318 {
1319 if (selection->isEmpty())
1320 return;
1322 Geom::OptRect const bbox(selection->bounds());
1323 if ( !bbox ) {
1324 return;
1325 }
1327 Geom::Translate const p2o(-bbox->min());
1329 Geom::Scale const newSize(x1 - x0,
1330 y1 - y0);
1331 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1332 Geom::Translate const o2n(x0, y0);
1333 Geom::Matrix const final( p2o * scale * o2n );
1335 sp_selection_apply_affine(selection, final);
1336 }
1339 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1340 {
1341 if (selection->isEmpty())
1342 return;
1344 Geom::OptRect const bbox(selection->bounds());
1346 if ( !bbox ) {
1347 return;
1348 }
1350 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1351 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1352 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1353 {
1354 return;
1355 }
1357 Geom::Translate const n2d(-align);
1358 Geom::Translate const d2n(align);
1359 Geom::Matrix const final( n2d * scale * d2n );
1360 sp_selection_apply_affine(selection, final);
1361 }
1363 void
1364 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1365 {
1366 Geom::Translate const d2n(center);
1367 Geom::Translate const n2d(-center);
1368 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1369 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1370 sp_selection_apply_affine(selection, final);
1371 }
1373 void
1374 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1375 {
1376 Geom::Translate const d2n(align);
1377 Geom::Translate const n2d(-align);
1378 Geom::Matrix const skew(1, dy,
1379 dx, 1,
1380 0, 0);
1381 Geom::Matrix const final( n2d * skew * d2n );
1382 sp_selection_apply_affine(selection, final);
1383 }
1385 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1386 {
1387 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)));
1388 }
1390 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1391 {
1392 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1393 }
1395 /**
1396 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1397 */
1398 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1399 {
1400 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1402 if (selection->isEmpty())
1403 return;
1405 GSList const *l = selection->itemList();
1406 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1407 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1408 SPItem *item = SP_ITEM(l2->data);
1409 sp_item_rotate_rel(item, rot_90);
1410 }
1412 sp_document_done(sp_desktop_document(desktop),
1413 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1414 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1415 }
1417 void
1418 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1419 {
1420 if (selection->isEmpty())
1421 return;
1423 boost::optional<Geom::Point> center = selection->center();
1424 if (!center) {
1425 return;
1426 }
1428 sp_selection_rotate_relative(selection, *center, angle_degrees);
1430 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1431 ( ( angle_degrees > 0 )
1432 ? "selector:rotate:ccw"
1433 : "selector:rotate:cw" ),
1434 SP_VERB_CONTEXT_SELECT,
1435 _("Rotate"));
1436 }
1438 // helper function:
1439 static
1440 Geom::Point
1441 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1442 Geom::Point m = r.midpoint();
1443 unsigned i = 0;
1444 if (p[X] < m[X]) {
1445 i = 1;
1446 }
1447 if (p[Y] < m[Y]) {
1448 i = 3 - i;
1449 }
1450 return r.corner(i);
1451 }
1453 /**
1454 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1455 */
1456 void
1457 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1458 {
1459 if (selection->isEmpty())
1460 return;
1462 Geom::OptRect const bbox(selection->bounds());
1463 boost::optional<Geom::Point> center = selection->center();
1465 if ( !bbox || !center ) {
1466 return;
1467 }
1469 gdouble const zoom = selection->desktop()->current_zoom();
1470 gdouble const zmove = angle / zoom;
1471 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1473 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1475 sp_selection_rotate_relative(selection, *center, zangle);
1477 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1478 ( (angle > 0)
1479 ? "selector:rotate:ccw"
1480 : "selector:rotate:cw" ),
1481 SP_VERB_CONTEXT_SELECT,
1482 _("Rotate by pixels"));
1483 }
1485 void
1486 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1487 {
1488 if (selection->isEmpty())
1489 return;
1491 Geom::OptRect const bbox(selection->bounds());
1492 if (!bbox) {
1493 return;
1494 }
1496 Geom::Point const center(bbox->midpoint());
1498 // you can't scale "do nizhe pola" (below zero)
1499 double const max_len = bbox->maxExtent();
1500 if ( max_len + grow <= 1e-3 ) {
1501 return;
1502 }
1504 double const times = 1.0 + grow / max_len;
1505 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1507 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1508 ( (grow > 0)
1509 ? "selector:scale:larger"
1510 : "selector:scale:smaller" ),
1511 SP_VERB_CONTEXT_SELECT,
1512 _("Scale"));
1513 }
1515 void
1516 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1517 {
1518 sp_selection_scale(selection,
1519 grow_pixels / selection->desktop()->current_zoom());
1520 }
1522 void
1523 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1524 {
1525 if (selection->isEmpty())
1526 return;
1528 Geom::OptRect sel_bbox = selection->bounds();
1530 if (!sel_bbox) {
1531 return;
1532 }
1534 Geom::Point const center(sel_bbox->midpoint());
1535 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1536 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1537 _("Scale by whole factor"));
1538 }
1540 void
1541 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1542 {
1543 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1544 if (selection->isEmpty()) {
1545 return;
1546 }
1548 sp_selection_move_relative(selection, dx, dy);
1550 if (dx == 0) {
1551 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1552 _("Move vertically"));
1553 } else if (dy == 0) {
1554 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1555 _("Move horizontally"));
1556 } else {
1557 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1558 _("Move"));
1559 }
1560 }
1562 void
1563 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1564 {
1565 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1566 if (selection->isEmpty()) {
1567 return;
1568 }
1570 // same as sp_selection_move but divide deltas by zoom factor
1571 gdouble const zoom = desktop->current_zoom();
1572 gdouble const zdx = dx / zoom;
1573 gdouble const zdy = dy / zoom;
1574 sp_selection_move_relative(selection, zdx, zdy);
1576 if (dx == 0) {
1577 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1578 _("Move vertically by pixels"));
1579 } else if (dy == 0) {
1580 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1581 _("Move horizontally by pixels"));
1582 } else {
1583 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1584 _("Move"));
1585 }
1586 }
1588 namespace {
1590 template <typename D>
1591 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1592 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1594 template <typename D>
1595 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1596 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1598 struct Forward {
1599 typedef SPObject *Iterator;
1601 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1602 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1603 static void dispose(Iterator /*i*/) {}
1605 static SPObject *object(Iterator i) { return i; }
1606 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1607 };
1609 struct Reverse {
1610 typedef GSList *Iterator;
1612 static Iterator children(SPObject *o) {
1613 return make_list(o->firstChild(), NULL);
1614 }
1615 static Iterator siblings_after(SPObject *o) {
1616 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1617 }
1618 static void dispose(Iterator i) {
1619 g_slist_free(i);
1620 }
1622 static SPObject *object(Iterator i) {
1623 return reinterpret_cast<SPObject *>(i->data);
1624 }
1625 static Iterator next(Iterator i) { return i->next; }
1627 private:
1628 static GSList *make_list(SPObject *object, SPObject *limit) {
1629 GSList *list=NULL;
1630 while ( object != limit ) {
1631 list = g_slist_prepend(list, object);
1632 object = SP_OBJECT_NEXT(object);
1633 }
1634 return list;
1635 }
1636 };
1638 }
1640 void
1641 sp_selection_item_next(SPDesktop *desktop)
1642 {
1643 g_return_if_fail(desktop != NULL);
1644 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1646 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1647 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1648 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1649 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1651 SPObject *root;
1652 if (PREFS_SELECTION_ALL != inlayer) {
1653 root = selection->activeContext();
1654 } else {
1655 root = desktop->currentRoot();
1656 }
1658 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1660 if (item) {
1661 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1662 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1663 scroll_to_show_item(desktop, item);
1664 }
1665 }
1666 }
1668 void
1669 sp_selection_item_prev(SPDesktop *desktop)
1670 {
1671 SPDocument *document = sp_desktop_document(desktop);
1672 g_return_if_fail(document != NULL);
1673 g_return_if_fail(desktop != NULL);
1674 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1676 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1677 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1678 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1679 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1681 SPObject *root;
1682 if (PREFS_SELECTION_ALL != inlayer) {
1683 root = selection->activeContext();
1684 } else {
1685 root = desktop->currentRoot();
1686 }
1688 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1690 if (item) {
1691 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1692 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1693 scroll_to_show_item(desktop, item);
1694 }
1695 }
1696 }
1698 void sp_selection_next_patheffect_param(SPDesktop * dt)
1699 {
1700 if (!dt) return;
1702 Inkscape::Selection *selection = sp_desktop_selection(dt);
1703 if ( selection && !selection->isEmpty() ) {
1704 SPItem *item = selection->singleItem();
1705 if ( item && SP_IS_SHAPE(item)) {
1706 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1707 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1708 } else {
1709 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1710 }
1711 }
1712 }
1713 }
1715 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1716 {
1717 if (!dt) return;
1719 Inkscape::Selection *selection = sp_desktop_selection(dt);
1720 if ( selection && !selection->isEmpty() ) {
1721 SPItem *item = selection->singleItem();
1722 if ( item ) {
1723 SPObject *obj = NULL;
1724 if (clip)
1725 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1726 else
1727 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1729 if (obj) {
1730 // obj is a group object, the children are the actual clippers
1731 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1732 if ( SP_IS_ITEM(child) ) {
1733 // If not already in nodecontext, goto it!
1734 if (!tools_isactive(dt, TOOLS_NODES)) {
1735 tools_switch(dt, TOOLS_NODES);
1736 }
1738 ShapeEditor * shape_editor = dt->event_context->shape_editor;
1739 // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1740 shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1741 shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1742 Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1743 if (np) {
1744 // take colors from prefs (same as used in outline mode)
1745 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1746 np->helperpath_rgba = clip ?
1747 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) :
1748 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1749 np->helperpath_width = 1.0;
1750 sp_nodepath_show_helperpath(np, true);
1751 }
1752 break; // break out of for loop after 1st encountered item
1753 }
1754 }
1755 } else if (clip) {
1756 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1757 } else {
1758 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1759 }
1760 }
1761 }
1762 }
1765 namespace {
1767 template <typename D>
1768 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1769 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1770 {
1771 SPObject *current=root;
1772 while (items) {
1773 SPItem *item=SP_ITEM(items->data);
1774 if ( root->isAncestorOf(item) &&
1775 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1776 {
1777 current = item;
1778 break;
1779 }
1780 items = items->next;
1781 }
1783 GSList *path=NULL;
1784 while ( current != root ) {
1785 path = g_slist_prepend(path, current);
1786 current = SP_OBJECT_PARENT(current);
1787 }
1789 SPItem *next;
1790 // first, try from the current object
1791 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1792 g_slist_free(path);
1794 if (!next) { // if we ran out of objects, start over at the root
1795 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1796 }
1798 return next;
1799 }
1801 template <typename D>
1802 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1803 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1804 {
1805 typename D::Iterator children;
1806 typename D::Iterator iter;
1808 SPItem *found=NULL;
1810 if (path) {
1811 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1812 g_assert(SP_OBJECT_PARENT(object) == root);
1813 if (desktop->isLayer(object)) {
1814 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1815 }
1816 iter = children = D::siblings_after(object);
1817 } else {
1818 iter = children = D::children(root);
1819 }
1821 while ( iter && !found ) {
1822 SPObject *object=D::object(iter);
1823 if (desktop->isLayer(object)) {
1824 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1825 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1826 }
1827 } else if ( SP_IS_ITEM(object) &&
1828 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1829 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1830 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1831 !desktop->isLayer(SP_ITEM(object)) )
1832 {
1833 found = SP_ITEM(object);
1834 }
1835 iter = D::next(iter);
1836 }
1838 D::dispose(children);
1840 return found;
1841 }
1843 }
1845 /**
1846 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1847 * \a item.
1848 */
1849 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1850 {
1851 Geom::Rect dbox = desktop->get_display_area();
1852 Geom::OptRect sbox = sp_item_bbox_desktop(item);
1854 if ( sbox && dbox.contains(*sbox) == false ) {
1855 Geom::Point const s_dt = sbox->midpoint();
1856 Geom::Point const s_w = desktop->d2w(s_dt);
1857 Geom::Point const d_dt = dbox.midpoint();
1858 Geom::Point const d_w = desktop->d2w(d_dt);
1859 Geom::Point const moved_w( d_w - s_w );
1860 gint const dx = (gint) moved_w[X];
1861 gint const dy = (gint) moved_w[Y];
1862 desktop->scroll_world(dx, dy);
1863 }
1864 }
1867 void
1868 sp_selection_clone(SPDesktop *desktop)
1869 {
1870 if (desktop == NULL)
1871 return;
1873 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1875 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1877 // check if something is selected
1878 if (selection->isEmpty()) {
1879 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1880 return;
1881 }
1883 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1885 selection->clear();
1887 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1888 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1890 GSList *newsel = NULL;
1892 while (reprs) {
1893 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1894 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1896 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1897 clone->setAttribute("x", "0", false);
1898 clone->setAttribute("y", "0", false);
1899 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1901 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1902 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1904 // add the new clone to the top of the original's parent
1905 parent->appendChild(clone);
1907 newsel = g_slist_prepend(newsel, clone);
1908 reprs = g_slist_remove(reprs, sel_repr);
1909 Inkscape::GC::release(clone);
1910 }
1912 // TRANSLATORS: only translate "string" in "context|string".
1913 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1914 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1915 Q_("action|Clone"));
1917 selection->setReprList(newsel);
1919 g_slist_free(newsel);
1920 }
1922 void
1923 sp_selection_relink(SPDesktop *desktop)
1924 {
1925 if (!desktop)
1926 return;
1928 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1930 if (selection->isEmpty()) {
1931 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1932 return;
1933 }
1935 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1936 const gchar *newid = cm->getFirstObjectID();
1937 if (!newid) {
1938 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1939 return;
1940 }
1941 gchar *newref = g_strdup_printf("#%s", newid);
1943 // Get a copy of current selection.
1944 bool relinked = false;
1945 for (GSList *items = (GSList *) selection->itemList();
1946 items != NULL;
1947 items = items->next)
1948 {
1949 SPItem *item = (SPItem *) items->data;
1951 if (!SP_IS_USE(item))
1952 continue;
1954 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1955 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1956 relinked = true;
1957 }
1959 g_free(newref);
1961 if (!relinked) {
1962 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1963 } else {
1964 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1965 _("Relink clone"));
1966 }
1967 }
1970 void
1971 sp_selection_unlink(SPDesktop *desktop)
1972 {
1973 if (!desktop)
1974 return;
1976 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1978 if (selection->isEmpty()) {
1979 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1980 return;
1981 }
1983 // Get a copy of current selection.
1984 GSList *new_select = NULL;
1985 bool unlinked = false;
1986 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1987 items != NULL;
1988 items = items->next)
1989 {
1990 SPItem *item = (SPItem *) items->data;
1992 if (SP_IS_TEXT(item)) {
1993 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1995 if (tspan) {
1996 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1997 }
1999 // Set unlink to true, and fall into the next if which
2000 // will include this text item in the new selection
2001 unlinked = true;
2002 }
2004 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2005 // keep the non-use item in the new selection
2006 new_select = g_slist_prepend(new_select, item);
2007 continue;
2008 }
2010 SPItem *unlink;
2011 if (SP_IS_USE(item)) {
2012 unlink = sp_use_unlink(SP_USE(item));
2013 } else /*if (SP_IS_TREF(use))*/ {
2014 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2015 }
2017 unlinked = true;
2018 // Add ungrouped items to the new selection.
2019 new_select = g_slist_prepend(new_select, unlink);
2020 }
2022 if (new_select) { // set new selection
2023 selection->clear();
2024 selection->setList(new_select);
2025 g_slist_free(new_select);
2026 }
2027 if (!unlinked) {
2028 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2029 }
2031 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2032 _("Unlink clone"));
2033 }
2035 void
2036 sp_select_clone_original(SPDesktop *desktop)
2037 {
2038 if (desktop == NULL)
2039 return;
2041 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2043 SPItem *item = selection->singleItem();
2045 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.");
2047 // Check if other than two objects are selected
2048 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2049 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2050 return;
2051 }
2053 SPItem *original = NULL;
2054 if (SP_IS_USE(item)) {
2055 original = sp_use_get_original(SP_USE(item));
2056 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2057 original = sp_offset_get_source(SP_OFFSET(item));
2058 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2059 original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2060 } else if (SP_IS_FLOWTEXT(item)) {
2061 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2062 } else { // it's an object that we don't know what to do with
2063 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2064 return;
2065 }
2067 if (!original) {
2068 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2069 return;
2070 }
2072 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2073 if (SP_IS_DEFS(o)) {
2074 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2075 return;
2076 }
2077 }
2079 if (original) {
2080 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2081 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2082 if (highlight) {
2083 Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2084 Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2085 if ( a && b ) {
2086 // draw a flashing line between the objects
2087 SPCurve *curve = new SPCurve();
2088 curve->moveto(a->midpoint());
2089 curve->lineto(b->midpoint());
2091 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2092 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2093 sp_canvas_item_show(canvasitem);
2094 curve->unref();
2095 desktop->add_temporary_canvasitem(canvasitem, 1000);
2096 }
2097 }
2099 selection->clear();
2100 selection->set(original);
2101 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2102 scroll_to_show_item(desktop, original);
2103 }
2104 }
2105 }
2108 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2109 {
2110 if (desktop == NULL)
2111 return;
2113 SPDocument *doc = sp_desktop_document(desktop);
2114 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2116 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2118 // check if something is selected
2119 if (selection->isEmpty()) {
2120 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2121 return;
2122 }
2124 sp_document_ensure_up_to_date(doc);
2125 Geom::OptRect r = selection->bounds();
2126 boost::optional<Geom::Point> c = selection->center();
2127 if ( !r || !c ) {
2128 return;
2129 }
2131 // calculate the transform to be applied to objects to move them to 0,0
2132 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2133 move_p[Geom::Y] = -move_p[Geom::Y];
2134 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2136 GSList *items = g_slist_copy((GSList *) selection->itemList());
2138 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2140 // bottommost object, after sorting
2141 SPObject *parent = SP_OBJECT_PARENT(items->data);
2143 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2145 // remember the position of the first item
2146 gint pos = SP_OBJECT_REPR(items->data)->position();
2147 (void)pos; // TODO check why this was remembered
2149 // create a list of duplicates
2150 GSList *repr_copies = NULL;
2151 for (GSList *i = items; i != NULL; i = i->next) {
2152 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2153 repr_copies = g_slist_prepend(repr_copies, dup);
2154 }
2156 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2158 if (apply) {
2159 // delete objects so that their clones don't get alerted; this object will be restored shortly
2160 for (GSList *i = items; i != NULL; i = i->next) {
2161 SPObject *item = SP_OBJECT(i->data);
2162 item->deleteObject(false);
2163 }
2164 }
2166 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2167 // without disturbing clones.
2168 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2169 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2170 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2171 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2173 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2174 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2175 Geom::Point(r->min()[Geom::X],
2176 r->max()[Geom::Y]))))
2177 * parent_transform.inverse() ),
2178 parent_transform * move);
2179 (void)mark_id;
2181 // restore compensation setting
2182 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2185 g_slist_free(items);
2187 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2188 _("Objects to marker"));
2189 }
2191 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2192 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2193 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2194 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2195 }
2196 } else {
2197 sp_item_convert_item_to_guides(item);
2199 if (deleteitem) {
2200 SP_OBJECT(item)->deleteObject(true);
2201 }
2202 }
2203 }
2205 void sp_selection_to_guides(SPDesktop *desktop)
2206 {
2207 if (desktop == NULL)
2208 return;
2210 SPDocument *doc = sp_desktop_document(desktop);
2211 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2212 // we need to copy the list because it gets reset when objects are deleted
2213 GSList *items = g_slist_copy((GSList *) selection->itemList());
2215 if (!items) {
2216 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2217 return;
2218 }
2220 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2221 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2222 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2224 for (GSList const *i = items; i != NULL; i = i->next) {
2225 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2226 }
2228 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2229 }
2231 void
2232 sp_selection_tile(SPDesktop *desktop, bool apply)
2233 {
2234 if (desktop == NULL)
2235 return;
2237 SPDocument *doc = sp_desktop_document(desktop);
2238 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2240 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2242 // check if something is selected
2243 if (selection->isEmpty()) {
2244 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2245 return;
2246 }
2248 sp_document_ensure_up_to_date(doc);
2249 Geom::OptRect r = selection->bounds();
2250 if ( !r ) {
2251 return;
2252 }
2254 // calculate the transform to be applied to objects to move them to 0,0
2255 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2256 move_p[Geom::Y] = -move_p[Geom::Y];
2257 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2259 GSList *items = g_slist_copy((GSList *) selection->itemList());
2261 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2263 // bottommost object, after sorting
2264 SPObject *parent = SP_OBJECT_PARENT(items->data);
2266 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2268 // remember the position of the first item
2269 gint pos = SP_OBJECT_REPR(items->data)->position();
2271 // create a list of duplicates
2272 GSList *repr_copies = NULL;
2273 for (GSList *i = items; i != NULL; i = i->next) {
2274 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2275 repr_copies = g_slist_prepend(repr_copies, dup);
2276 }
2277 // restore the z-order after prepends
2278 repr_copies = g_slist_reverse(repr_copies);
2280 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2282 if (apply) {
2283 // delete objects so that their clones don't get alerted; this object will be restored shortly
2284 for (GSList *i = items; i != NULL; i = i->next) {
2285 SPObject *item = SP_OBJECT(i->data);
2286 item->deleteObject(false);
2287 }
2288 }
2290 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2291 // without disturbing clones.
2292 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2293 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2294 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2295 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2297 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2298 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2299 r->max()[Geom::Y]))))
2300 * to_2geom(parent_transform.inverse()) ),
2301 parent_transform * move);
2303 // restore compensation setting
2304 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2306 if (apply) {
2307 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2308 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2310 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2311 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2313 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2314 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2315 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2316 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2318 // restore parent and position
2319 SP_OBJECT_REPR(parent)->appendChild(rect);
2320 rect->setPosition(pos > 0 ? pos : 0);
2321 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2323 Inkscape::GC::release(rect);
2325 selection->clear();
2326 selection->set(rectangle);
2327 }
2329 g_slist_free(items);
2331 sp_document_done(doc, SP_VERB_EDIT_TILE,
2332 _("Objects to pattern"));
2333 }
2335 void
2336 sp_selection_untile(SPDesktop *desktop)
2337 {
2338 if (desktop == NULL)
2339 return;
2341 SPDocument *doc = sp_desktop_document(desktop);
2342 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2344 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2346 // check if something is selected
2347 if (selection->isEmpty()) {
2348 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2349 return;
2350 }
2352 GSList *new_select = NULL;
2354 bool did = false;
2356 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2357 items != NULL;
2358 items = items->next) {
2360 SPItem *item = (SPItem *) items->data;
2362 SPStyle *style = SP_OBJECT_STYLE(item);
2364 if (!style || !style->fill.isPaintserver())
2365 continue;
2367 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2369 if (!SP_IS_PATTERN(server))
2370 continue;
2372 did = true;
2374 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2376 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2377 pat_transform *= item->transform;
2379 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2380 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2381 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2383 // FIXME: relink clones to the new canvas objects
2384 // use SPObject::setid when mental finishes it to steal ids of
2386 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2387 sp_document_ensure_up_to_date(doc);
2389 Geom::Matrix transform( i->transform * pat_transform );
2390 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2392 new_select = g_slist_prepend(new_select, i);
2393 }
2395 SPCSSAttr *css = sp_repr_css_attr_new();
2396 sp_repr_css_set_property(css, "fill", "none");
2397 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2398 }
2400 if (!did) {
2401 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2402 } else {
2403 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2404 _("Pattern to objects"));
2405 selection->setList(new_select);
2406 }
2407 }
2409 void
2410 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2411 {
2412 if (selection->isEmpty()) {
2413 return;
2414 }
2416 GSList const *reprlst = selection->reprList();
2417 bool filename_search = TRUE;
2418 bool xdpi_search = TRUE;
2419 bool ydpi_search = TRUE;
2421 for (; reprlst != NULL &&
2422 filename_search &&
2423 xdpi_search &&
2424 ydpi_search;
2425 reprlst = reprlst->next) {
2426 gchar const *dpi_string;
2427 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2429 if (filename_search) {
2430 *filename = repr->attribute("inkscape:export-filename");
2431 if (*filename != NULL)
2432 filename_search = FALSE;
2433 }
2435 if (xdpi_search) {
2436 dpi_string = NULL;
2437 dpi_string = repr->attribute("inkscape:export-xdpi");
2438 if (dpi_string != NULL) {
2439 *xdpi = atof(dpi_string);
2440 xdpi_search = FALSE;
2441 }
2442 }
2444 if (ydpi_search) {
2445 dpi_string = NULL;
2446 dpi_string = repr->attribute("inkscape:export-ydpi");
2447 if (dpi_string != NULL) {
2448 *ydpi = atof(dpi_string);
2449 ydpi_search = FALSE;
2450 }
2451 }
2452 }
2453 }
2455 void
2456 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2457 {
2458 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2459 gchar const *dpi_string;
2461 *filename = repr->attribute("inkscape:export-filename");
2463 dpi_string = NULL;
2464 dpi_string = repr->attribute("inkscape:export-xdpi");
2465 if (dpi_string != NULL) {
2466 *xdpi = atof(dpi_string);
2467 }
2469 dpi_string = NULL;
2470 dpi_string = repr->attribute("inkscape:export-ydpi");
2471 if (dpi_string != NULL) {
2472 *ydpi = atof(dpi_string);
2473 }
2474 }
2476 void
2477 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2478 {
2479 if (desktop == NULL)
2480 return;
2482 SPDocument *document = sp_desktop_document(desktop);
2483 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2485 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2487 // check if something is selected
2488 if (selection->isEmpty()) {
2489 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2490 return;
2491 }
2493 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2494 // set "busy" cursor
2495 desktop->setWaitingCursor();
2497 // Get the bounding box of the selection
2498 NRRect bbox;
2499 sp_document_ensure_up_to_date(document);
2500 selection->bounds(&bbox);
2501 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2502 desktop->clearWaitingCursor();
2503 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2504 }
2506 // List of the items to show; all others will be hidden
2507 GSList *items = g_slist_copy((GSList *) selection->itemList());
2509 // Sort items so that the topmost comes last
2510 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2512 // Generate a random value from the current time (you may create bitmap from the same object(s)
2513 // multiple times, and this is done so that they don't clash)
2514 GTimeVal cu;
2515 g_get_current_time(&cu);
2516 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2518 // Create the filename
2519 gchar *filename = g_strdup_printf("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2520 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2521 // digits, and a few other chars, with "_"
2522 g_strcanon(filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2524 // Build the complete path by adding document base dir, if set, otherwise home dir
2525 gchar * directory = NULL;
2526 if (SP_DOCUMENT_URI(document)) {
2527 directory = g_dirname(SP_DOCUMENT_URI(document));
2528 }
2529 if (directory == NULL) {
2530 directory = homedir_path(NULL);
2531 }
2532 gchar *filepath = g_build_filename(directory, filename, NULL);
2534 //g_print("%s\n", filepath);
2536 // Remember parent and z-order of the topmost one
2537 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2538 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2539 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2541 // Calculate resolution
2542 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2543 double res;
2544 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2545 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2546 if (0 < prefs_res) {
2547 // If it's given explicitly in prefs, take it
2548 res = prefs_res;
2549 } else if (0 < prefs_min) {
2550 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2551 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2552 } else {
2553 float hint_xdpi = 0, hint_ydpi = 0;
2554 char const *hint_filename;
2555 // take resolution hint from the selected objects
2556 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2557 if (hint_xdpi != 0) {
2558 res = hint_xdpi;
2559 } else {
2560 // take resolution hint from the document
2561 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2562 if (hint_xdpi != 0) {
2563 res = hint_xdpi;
2564 } else {
2565 // if all else fails, take the default 90 dpi
2566 res = PX_PER_IN;
2567 }
2568 }
2569 }
2571 // The width and height of the bitmap in pixels
2572 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2573 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2575 // Find out if we have to run an external filter
2576 gchar const *run = NULL;
2577 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2578 if (!filter.empty()) {
2579 // filter command is given;
2580 // see if we have a parameter to pass to it
2581 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2582 if (!param1.empty()) {
2583 if (param1[param1.length() - 1] == '%') {
2584 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2585 gchar p1[256];
2586 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2587 // the first param is always the image filename, the second is param1
2588 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2589 } else {
2590 // otherwise pass the param1 unchanged
2591 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2592 }
2593 } else {
2594 // run without extra parameter
2595 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2596 }
2597 }
2599 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2600 Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2601 Geom::Matrix t;
2603 double shift_x = bbox.x0;
2604 double shift_y = bbox.y1;
2605 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2606 shift_x = round(shift_x);
2607 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2608 }
2609 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2611 // Do the export
2612 sp_export_png_file(document, filepath,
2613 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2614 width, height, res, res,
2615 (guint32) 0xffffff00,
2616 NULL, NULL,
2617 true, /*bool force_overwrite,*/
2618 items);
2620 g_slist_free(items);
2622 // Run filter, if any
2623 if (run) {
2624 g_print("Running external filter: %s\n", run);
2625 int retval;
2626 retval = system(run);
2627 }
2629 // Import the image back
2630 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2631 if (pb) {
2632 // Create the repr for the image
2633 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2634 repr->setAttribute("xlink:href", filename);
2635 repr->setAttribute("sodipodi:absref", filepath);
2636 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2637 sp_repr_set_svg_double(repr, "width", width);
2638 sp_repr_set_svg_double(repr, "height", height);
2639 } else {
2640 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2641 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2642 }
2644 // Write transform
2645 gchar *c=sp_svg_transform_write(t);
2646 repr->setAttribute("transform", c);
2647 g_free(c);
2649 // add the new repr to the parent
2650 parent->appendChild(repr);
2652 // move to the saved position
2653 repr->setPosition(pos > 0 ? pos + 1 : 1);
2655 // Set selection to the new image
2656 selection->clear();
2657 selection->add(repr);
2659 // Clean up
2660 Inkscape::GC::release(repr);
2661 gdk_pixbuf_unref(pb);
2663 // Complete undoable transaction
2664 sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2665 _("Create bitmap"));
2666 }
2668 desktop->clearWaitingCursor();
2670 g_free(filename);
2671 g_free(filepath);
2672 }
2674 /**
2675 * \brief Creates a mask or clipPath from selection
2676 * Two different modes:
2677 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2678 * and is applied to current layer
2679 * otherwise, topmost object is used as mask for other objects
2680 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2681 *
2682 */
2683 void
2684 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2685 {
2686 if (desktop == NULL)
2687 return;
2689 SPDocument *doc = sp_desktop_document(desktop);
2690 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2692 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2694 // check if something is selected
2695 bool is_empty = selection->isEmpty();
2696 if ( apply_to_layer && is_empty) {
2697 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2698 return;
2699 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2700 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2701 return;
2702 }
2704 // FIXME: temporary patch to prevent crash!
2705 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2706 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2707 if (clone_with_original) {
2708 return; // in this version, you cannot clip/mask an object with its own clone
2709 }
2710 // /END FIXME
2712 sp_document_ensure_up_to_date(doc);
2714 GSList *items = g_slist_copy((GSList *) selection->itemList());
2716 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2718 // create a list of duplicates
2719 GSList *mask_items = NULL;
2720 GSList *apply_to_items = NULL;
2721 GSList *items_to_delete = NULL;
2722 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2723 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2724 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2726 if (apply_to_layer) {
2727 // all selected items are used for mask, which is applied to a layer
2728 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2730 for (GSList *i = items; i != NULL; i = i->next) {
2731 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2732 mask_items = g_slist_prepend(mask_items, dup);
2734 if (remove_original) {
2735 SPObject *item = SP_OBJECT(i->data);
2736 items_to_delete = g_slist_prepend(items_to_delete, item);
2737 }
2738 }
2739 } else if (!topmost) {
2740 // topmost item is used as a mask, which is applied to other items in a selection
2741 GSList *i = items;
2742 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2743 mask_items = g_slist_prepend(mask_items, dup);
2745 if (remove_original) {
2746 SPObject *item = SP_OBJECT(i->data);
2747 items_to_delete = g_slist_prepend(items_to_delete, item);
2748 }
2750 for (i = i->next; i != NULL; i = i->next) {
2751 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2752 }
2753 } else {
2754 GSList *i = NULL;
2755 for (i = items; NULL != i->next; i = i->next) {
2756 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2757 }
2759 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2760 mask_items = g_slist_prepend(mask_items, dup);
2762 if (remove_original) {
2763 SPObject *item = SP_OBJECT(i->data);
2764 items_to_delete = g_slist_prepend(items_to_delete, item);
2765 }
2766 }
2768 g_slist_free(items);
2769 items = NULL;
2771 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2772 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2773 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2774 // inverted object transform should be applied to a mask object,
2775 // as mask is calculated in user space (after applying transform)
2776 Geom::Matrix maskTransform(item->transform.inverse());
2778 GSList *mask_items_dup = NULL;
2779 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2780 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2781 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2782 }
2784 gchar const *mask_id = NULL;
2785 if (apply_clip_path) {
2786 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2787 } else {
2788 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2789 }
2791 g_slist_free(mask_items_dup);
2792 mask_items_dup = NULL;
2794 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2795 }
2797 g_slist_free(mask_items);
2798 g_slist_free(apply_to_items);
2800 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2801 SPObject *item = SP_OBJECT(i->data);
2802 item->deleteObject(false);
2803 }
2804 g_slist_free(items_to_delete);
2806 if (apply_clip_path)
2807 sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2808 else
2809 sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2810 }
2812 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2813 if (desktop == NULL)
2814 return;
2816 SPDocument *doc = sp_desktop_document(desktop);
2817 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2818 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2820 // check if something is selected
2821 if (selection->isEmpty()) {
2822 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2823 return;
2824 }
2826 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2827 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2828 sp_document_ensure_up_to_date(doc);
2830 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2831 std::map<SPObject*,SPItem*> referenced_objects;
2832 // SPObject* refers to a group containing the clipped path or mask itself,
2833 // whereas SPItem* refers to the item being clipped or masked
2834 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2835 if (remove_original) {
2836 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2837 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2838 Inkscape::URIReference *uri_ref = NULL;
2840 if (apply_clip_path) {
2841 uri_ref = item->clip_ref;
2842 } else {
2843 uri_ref = item->mask_ref;
2844 }
2846 // collect distinct mask object (and associate with item to apply transform)
2847 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2848 referenced_objects[uri_ref->getObject()] = item;
2849 }
2850 }
2852 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2853 }
2855 // restore mask objects into a document
2856 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2857 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2858 GSList *items_to_move = NULL;
2859 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2860 // Collect all clipped paths and masks within a single group
2861 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2862 items_to_move = g_slist_prepend(items_to_move, copy);
2863 }
2865 if (!obj->isReferenced()) {
2866 // delete from defs if no other object references this mask
2867 obj->deleteObject(false);
2868 }
2870 // remember parent and position of the item to which the clippath/mask was applied
2871 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2872 gint pos = SP_OBJECT_REPR((*it).second)->position();
2874 // Iterate through all clipped paths / masks
2875 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2876 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2878 // insert into parent, restore pos
2879 parent->appendChild(repr);
2880 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2882 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
2883 selection->add(repr);
2885 // transform mask, so it is moved the same spot where mask was applied
2886 Geom::Matrix transform(mask_item->transform);
2887 transform *= (*it).second->transform;
2888 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2889 }
2891 g_slist_free(items_to_move);
2892 }
2894 if (apply_clip_path)
2895 sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2896 else
2897 sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2898 }
2900 /**
2901 * Returns true if an undoable change should be recorded.
2902 */
2903 bool
2904 fit_canvas_to_selection(SPDesktop *desktop)
2905 {
2906 g_return_val_if_fail(desktop != NULL, false);
2907 SPDocument *doc = sp_desktop_document(desktop);
2909 g_return_val_if_fail(doc != NULL, false);
2910 g_return_val_if_fail(desktop->selection != NULL, false);
2912 if (desktop->selection->isEmpty()) {
2913 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2914 return false;
2915 }
2916 Geom::OptRect const bbox(desktop->selection->bounds());
2917 if (bbox) {
2918 doc->fitToRect(*bbox);
2919 return true;
2920 } else {
2921 return false;
2922 }
2923 }
2925 /**
2926 * Fit canvas to the bounding box of the selection, as an undoable action.
2927 */
2928 void
2929 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2930 {
2931 if (fit_canvas_to_selection(desktop)) {
2932 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2933 _("Fit Page to Selection"));
2934 }
2935 }
2937 bool
2938 fit_canvas_to_drawing(SPDocument *doc)
2939 {
2940 g_return_val_if_fail(doc != NULL, false);
2942 sp_document_ensure_up_to_date(doc);
2943 SPItem const *const root = SP_ITEM(doc->root);
2944 Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
2945 if (bbox) {
2946 doc->fitToRect(*bbox);
2947 return true;
2948 } else {
2949 return false;
2950 }
2951 }
2953 void
2954 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2955 {
2956 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2957 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2958 _("Fit Page to Drawing"));
2959 }
2960 }
2962 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2963 g_return_if_fail(desktop != NULL);
2964 SPDocument *doc = sp_desktop_document(desktop);
2966 g_return_if_fail(doc != NULL);
2967 g_return_if_fail(desktop->selection != NULL);
2969 bool const changed = ( desktop->selection->isEmpty()
2970 ? fit_canvas_to_drawing(doc)
2971 : fit_canvas_to_selection(desktop) );
2972 if (changed) {
2973 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2974 _("Fit Page to Selection or Drawing"));
2975 }
2976 };
2978 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2979 // don't operate on layers
2980 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2981 f(SP_ITEM(root), desktop);
2982 }
2983 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2984 //don't recurse into locked layers
2985 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2986 itemtree_map(f, iter, desktop);
2987 }
2988 }
2989 }
2991 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2992 if (item->isLocked()) {
2993 item->setLocked(FALSE);
2994 }
2995 }
2997 static void unhide(SPItem *item, SPDesktop *desktop) {
2998 if (desktop->itemIsHidden(item)) {
2999 item->setExplicitlyHidden(FALSE);
3000 }
3001 }
3003 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3004 if (!dt) return;
3006 SPObject *root;
3007 if (layer_only) {
3008 root = dt->currentLayer();
3009 } else {
3010 root = dt->currentRoot();
3011 }
3013 itemtree_map(f, root, dt);
3014 }
3016 void unlock_all(SPDesktop *dt) {
3017 process_all(&unlock, dt, true);
3018 }
3020 void unlock_all_in_all_layers(SPDesktop *dt) {
3021 process_all(&unlock, dt, false);
3022 }
3024 void unhide_all(SPDesktop *dt) {
3025 process_all(&unhide, dt, true);
3026 }
3028 void unhide_all_in_all_layers(SPDesktop *dt) {
3029 process_all(&unhide, dt, false);
3030 }
3033 /*
3034 Local Variables:
3035 mode:c++
3036 c-file-style:"stroustrup"
3037 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3038 indent-tabs-mode:nil
3039 fill-column:99
3040 End:
3041 */
3042 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :