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