1 #define __SP_SELECTION_CHEMISTRY_C__
3 /** @file
4 * @brief Miscellanous operations on selected items
5 */
6 /* Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * Frank Felfe <innerspace@iname.com>
9 * MenTaLguY <mental@rydia.net>
10 * bulia byak <buliabyak@users.sf.net>
11 * Andrius R. <knutux@gmail.com>
12 *
13 * Copyright (C) 1999-2006 authors
14 * Copyright (C) 2001-2002 Ximian, Inc.
15 *
16 * Released under GNU GPL, read the file 'COPYING' for more information
17 */
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #endif
23 #include "selection-chemistry.h"
25 #include <gtkmm/clipboard.h>
27 #include "svg/svg.h"
28 #include "desktop.h"
29 #include "desktop-style.h"
30 #include "selection.h"
31 #include "tools-switch.h"
32 #include "desktop-handles.h"
33 #include "message-stack.h"
34 #include "sp-item-transform.h"
35 #include "marker.h"
36 #include "sp-use.h"
37 #include "sp-textpath.h"
38 #include "sp-tspan.h"
39 #include "sp-tref.h"
40 #include "sp-flowtext.h"
41 #include "sp-flowregion.h"
42 #include "text-editing.h"
43 #include "text-context.h"
44 #include "connector-context.h"
45 #include "sp-path.h"
46 #include "sp-conn-end.h"
47 #include "dropper-context.h"
48 #include <glibmm/i18n.h>
49 #include "libnr/nr-matrix-rotate-ops.h"
50 #include "libnr/nr-matrix-translate-ops.h"
51 #include "libnr/nr-scale-ops.h"
52 #include <libnr/nr-matrix-ops.h>
53 #include <2geom/transforms.h>
54 #include "xml/repr.h"
55 #include "style.h"
56 #include "document-private.h"
57 #include "sp-gradient.h"
58 #include "sp-gradient-reference.h"
59 #include "sp-linear-gradient-fns.h"
60 #include "sp-pattern.h"
61 #include "sp-radial-gradient-fns.h"
62 #include "sp-namedview.h"
63 #include "preferences.h"
64 #include "sp-offset.h"
65 #include "sp-clippath.h"
66 #include "sp-mask.h"
67 #include "file.h"
68 #include "helper/png-write.h"
69 #include "layer-fns.h"
70 #include "context-fns.h"
71 #include <map>
72 #include <cstring>
73 #include <string>
74 #include "helper/units.h"
75 #include "sp-item.h"
76 #include "box3d.h"
77 #include "unit-constants.h"
78 #include "xml/simple-document.h"
79 #include "sp-filter-reference.h"
80 #include "gradient-drag.h"
81 #include "uri-references.h"
82 #include "libnr/nr-convert2geom.h"
83 #include "display/curve.h"
84 #include "display/canvas-bpath.h"
86 // For clippath editing
87 #include "tools-switch.h"
88 #include "shape-editor.h"
89 #include "node-context.h"
90 #include "nodepath.h"
92 #include "ui/clipboard.h"
94 using NR::X;
95 using NR::Y;
97 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
98 because the layer manipulation code uses them. It should be rewritten specifically
99 for that purpose. */
101 /**
102 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
103 * then prepends the copy to 'clip'.
104 */
105 void sp_selection_copy_one (Inkscape::XML::Node *repr, NR::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
106 {
107 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
109 // copy complete inherited style
110 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
111 sp_repr_css_set(copy, css, "style");
112 sp_repr_css_attr_unref(css);
114 // write the complete accumulated transform passed to us
115 // (we're dealing with unattached repr, so we write to its attr
116 // instead of using sp_item_set_transform)
117 gchar *affinestr=sp_svg_transform_write(full_t);
118 copy->setAttribute("transform", affinestr);
119 g_free(affinestr);
121 *clip = g_slist_prepend(*clip, copy);
122 }
124 void sp_selection_copy_impl (GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
125 {
126 // Sort items:
127 GSList *sorted_items = g_slist_copy ((GSList *) items);
128 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
130 // Copy item reprs:
131 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
132 sp_selection_copy_one (SP_OBJECT_REPR (i->data), sp_item_i2doc_affine(SP_ITEM (i->data)), clip, xml_doc);
133 }
135 *clip = g_slist_reverse(*clip);
136 g_slist_free ((GSList *) sorted_items);
137 }
139 GSList *sp_selection_paste_impl (SPDocument *doc, SPObject *parent, GSList **clip)
140 {
141 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
143 GSList *copied = NULL;
144 // add objects to document
145 for (GSList *l = *clip; l != NULL; l = l->next) {
146 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
147 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
149 // premultiply the item transform by the accumulated parent transform in the paste layer
150 NR::Matrix local (sp_item_i2doc_affine(SP_ITEM(parent)));
151 if (!local.test_identity()) {
152 gchar const *t_str = copy->attribute("transform");
153 Geom::Matrix item_t (Geom::identity());
154 if (t_str)
155 sp_svg_transform_read(t_str, &item_t);
156 item_t *= local.inverse();
157 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
158 gchar *affinestr=sp_svg_transform_write(item_t);
159 copy->setAttribute("transform", affinestr);
160 g_free(affinestr);
161 }
163 parent->appendChildRepr(copy);
164 copied = g_slist_prepend(copied, copy);
165 Inkscape::GC::release(copy);
166 }
167 return copied;
168 }
170 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
171 {
172 for (GSList const *i = items ; i ; i = i->next ) {
173 sp_object_ref((SPObject *)i->data, NULL);
174 }
175 for (GSList const *i = items; i != NULL; i = i->next) {
176 SPItem *item = (SPItem *) i->data;
177 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
178 sp_object_unref((SPObject *)item, NULL);
179 }
180 }
183 void sp_selection_delete(SPDesktop *desktop)
184 {
185 if (desktop == NULL) {
186 return;
187 }
189 if (tools_isactive (desktop, TOOLS_TEXT))
190 if (sp_text_delete_selection(desktop->event_context)) {
191 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
192 _("Delete text"));
193 return;
194 }
196 Inkscape::Selection *selection = sp_desktop_selection(desktop);
198 // check if something is selected
199 if (selection->isEmpty()) {
200 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
201 return;
202 }
204 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
205 selection->clear();
206 sp_selection_delete_impl (selected);
207 g_slist_free ((GSList *) selected);
209 /* a tool may have set up private information in it's selection context
210 * that depends on desktop items. I think the only sane way to deal with
211 * this currently is to reset the current tool, which will reset it's
212 * associated selection context. For example: deleting an object
213 * while moving it around the canvas.
214 */
215 tools_switch ( desktop, tools_active ( desktop ) );
217 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
218 _("Delete"));
219 }
221 void add_ids_recursive (std::vector<const gchar *> &ids, SPObject *obj)
222 {
223 if (!obj)
224 return;
226 ids.push_back(SP_OBJECT_ID(obj));
228 if (SP_IS_GROUP(obj)) {
229 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
230 add_ids_recursive (ids, child);
231 }
232 }
233 }
235 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
236 {
237 if (desktop == NULL)
238 return;
240 SPDocument *doc = desktop->doc();
241 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
242 Inkscape::Selection *selection = sp_desktop_selection(desktop);
244 // check if something is selected
245 if (selection->isEmpty()) {
246 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
247 return;
248 }
250 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
252 selection->clear();
254 // sorting items from different parents sorts each parent's subset without possibly mixing
255 // them, just what we need
256 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
258 GSList *newsel = NULL;
260 std::vector<const gchar *> old_ids;
261 std::vector<const gchar *> new_ids;
262 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
263 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
265 while (reprs) {
266 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
267 Inkscape::XML::Node *parent = old_repr->parent();
268 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
270 parent->appendChild(copy);
272 if (relink_clones) {
273 SPObject *old_obj = doc->getObjectByRepr(old_repr);
274 SPObject *new_obj = doc->getObjectByRepr(copy);
275 add_ids_recursive (old_ids, old_obj);
276 add_ids_recursive (new_ids, new_obj);
277 }
279 newsel = g_slist_prepend(newsel, copy);
280 reprs = g_slist_remove(reprs, reprs->data);
281 Inkscape::GC::release(copy);
282 }
284 if (relink_clones) {
286 g_assert (old_ids.size() == new_ids.size());
288 for(unsigned int i = 0; i < old_ids.size(); i++) {
289 const gchar *id = old_ids[i];
290 SPObject *old_clone = doc->getObjectById(id);
291 if (SP_IS_USE(old_clone)) {
292 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
293 for(unsigned int j = 0; j < old_ids.size(); j++) {
294 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
295 // we have both orig and clone in selection, relink
296 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
297 gchar *newref = g_strdup_printf ("#%s", new_ids[j]);
298 SPObject *new_clone = doc->getObjectById(new_ids[i]);
299 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
300 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
301 g_free (newref);
302 }
303 }
304 }
305 }
306 }
309 if ( !suppressDone ) {
310 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
311 _("Duplicate"));
312 }
314 selection->setReprList(newsel);
316 g_slist_free(newsel);
317 }
319 void sp_edit_clear_all(SPDesktop *dt)
320 {
321 if (!dt)
322 return;
324 SPDocument *doc = sp_desktop_document(dt);
325 sp_desktop_selection(dt)->clear();
327 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
328 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
330 while (items) {
331 SP_OBJECT (items->data)->deleteObject();
332 items = g_slist_remove(items, items->data);
333 }
335 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
336 _("Delete all"));
337 }
339 GSList *
340 get_all_items (GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
341 {
342 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
343 if (SP_IS_ITEM(child) &&
344 !desktop->isLayer(SP_ITEM(child)) &&
345 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
346 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
347 (!exclude || !g_slist_find ((GSList *) exclude, child))
348 )
349 {
350 list = g_slist_prepend (list, SP_ITEM(child));
351 }
353 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
354 list = get_all_items (list, child, desktop, onlyvisible, onlysensitive, exclude);
355 }
356 }
358 return list;
359 }
361 void sp_edit_select_all_full (SPDesktop *dt, bool force_all_layers, bool invert)
362 {
363 if (!dt)
364 return;
366 Inkscape::Selection *selection = sp_desktop_selection(dt);
368 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
370 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
371 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
372 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
373 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
375 GSList *items = NULL;
377 GSList const *exclude = NULL;
378 if (invert) {
379 exclude = selection->itemList();
380 }
382 if (force_all_layers)
383 inlayer = PREFS_SELECTION_ALL;
385 switch (inlayer) {
386 case PREFS_SELECTION_LAYER: {
387 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
388 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
389 return;
391 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
393 for (GSList *i = all_items; i; i = i->next) {
394 SPItem *item = SP_ITEM (i->data);
396 if (item && (!onlysensitive || !item->isLocked())) {
397 if (!onlyvisible || !dt->itemIsHidden(item)) {
398 if (!dt->isLayer(item)) {
399 if (!invert || !g_slist_find ((GSList *) exclude, item)) {
400 items = g_slist_prepend (items, item); // leave it in the list
401 }
402 }
403 }
404 }
405 }
407 g_slist_free (all_items);
408 break;
409 }
410 case PREFS_SELECTION_LAYER_RECURSIVE: {
411 items = get_all_items (NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
412 break;
413 }
414 default: {
415 items = get_all_items (NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
416 break;
417 }
418 }
420 selection->setList (items);
422 if (items) {
423 g_slist_free (items);
424 }
425 }
427 void sp_edit_select_all (SPDesktop *desktop)
428 {
429 sp_edit_select_all_full (desktop, false, false);
430 }
432 void sp_edit_select_all_in_all_layers (SPDesktop *desktop)
433 {
434 sp_edit_select_all_full (desktop, true, false);
435 }
437 void sp_edit_invert (SPDesktop *desktop)
438 {
439 sp_edit_select_all_full (desktop, false, true);
440 }
442 void sp_edit_invert_in_all_layers (SPDesktop *desktop)
443 {
444 sp_edit_select_all_full (desktop, true, true);
445 }
447 void sp_selection_group(SPDesktop *desktop)
448 {
449 if (desktop == NULL)
450 return;
452 SPDocument *doc = sp_desktop_document (desktop);
453 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
455 Inkscape::Selection *selection = sp_desktop_selection(desktop);
457 // Check if something is selected.
458 if (selection->isEmpty()) {
459 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
460 return;
461 }
463 GSList const *l = (GSList *) selection->reprList();
465 GSList *p = g_slist_copy((GSList *) l);
467 selection->clear();
469 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
471 // Remember the position and parent of the topmost object.
472 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
473 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
475 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
477 while (p) {
478 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
480 if (current->parent() == topmost_parent) {
481 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
482 sp_repr_unparent(current);
483 group->appendChild(spnew);
484 Inkscape::GC::release(spnew);
485 topmost --; // only reduce count for those items deleted from topmost_parent
486 } else { // move it to topmost_parent first
487 GSList *temp_clip = NULL;
489 // At this point, current may already have no item, due to its being a clone whose original is already moved away
490 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
491 gchar const *t_str = current->attribute("transform");
492 Geom::Matrix item_t (Geom::identity());
493 if (t_str)
494 sp_svg_transform_read(t_str, &item_t);
495 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
496 //FIXME: when moving both clone and original from a transformed group (either by
497 //grouping into another parent, or by cut/paste) the transform from the original's
498 //parent becomes embedded into original itself, and this affects its clones. Fix
499 //this by remembering the transform diffs we write to each item into an array and
500 //then, if this is clone, looking up its original in that array and pre-multiplying
501 //it by the inverse of that original's transform diff.
503 sp_selection_copy_one (current, item_t, &temp_clip, xml_doc);
504 sp_repr_unparent(current);
506 // paste into topmost_parent (temporarily)
507 GSList *copied = sp_selection_paste_impl (doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
508 if (temp_clip) g_slist_free (temp_clip);
509 if (copied) { // if success,
510 // take pasted object (now in topmost_parent)
511 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
512 // make a copy
513 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
514 // remove pasted
515 sp_repr_unparent(in_topmost);
516 // put its copy into group
517 group->appendChild(spnew);
518 Inkscape::GC::release(spnew);
519 g_slist_free (copied);
520 }
521 }
522 p = g_slist_remove(p, current);
523 }
525 // Add the new group to the topmost members' parent
526 topmost_parent->appendChild(group);
528 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
529 group->setPosition(topmost + 1);
531 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
532 _("Group"));
534 selection->set(group);
535 Inkscape::GC::release(group);
536 }
538 void sp_selection_ungroup(SPDesktop *desktop)
539 {
540 if (desktop == NULL)
541 return;
543 Inkscape::Selection *selection = sp_desktop_selection(desktop);
545 if (selection->isEmpty()) {
546 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
547 return;
548 }
550 GSList *items = g_slist_copy((GSList *) selection->itemList());
551 selection->clear();
553 // Get a copy of current selection.
554 GSList *new_select = NULL;
555 bool ungrouped = false;
556 for (GSList *i = items;
557 i != NULL;
558 i = i->next)
559 {
560 SPItem *group = (SPItem *) i->data;
562 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
563 if (!SP_IS_OBJECT(group)) {
564 continue;
565 }
567 /* We do not allow ungrouping <svg> etc. (lauris) */
568 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
569 // keep the non-group item in the new selection
570 selection->add(group);
571 continue;
572 }
574 GSList *children = NULL;
575 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
576 sp_item_group_ungroup(SP_GROUP(group), &children, false);
577 ungrouped = true;
578 // Add ungrouped items to the new selection.
579 new_select = g_slist_concat(new_select, children);
580 }
582 if (new_select) { // Set new selection.
583 selection->addList(new_select);
584 g_slist_free(new_select);
585 }
586 if (!ungrouped) {
587 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
588 }
590 g_slist_free(items);
592 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
593 _("Ungroup"));
594 }
596 static SPGroup *
597 sp_item_list_common_parent_group(GSList const *items)
598 {
599 if (!items) {
600 return NULL;
601 }
602 SPObject *parent = SP_OBJECT_PARENT(items->data);
603 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
604 if (!SP_IS_GROUP(parent)) {
605 return NULL;
606 }
607 for (items = items->next; items; items = items->next) {
608 if (SP_OBJECT_PARENT(items->data) != parent) {
609 return NULL;
610 }
611 }
613 return SP_GROUP(parent);
614 }
616 /** Finds out the minimum common bbox of the selected items. */
617 static boost::optional<Geom::Rect>
618 enclose_items(GSList const *items)
619 {
620 g_assert(items != NULL);
622 boost::optional<Geom::Rect> r;
623 for (GSList const *i = items; i; i = i->next) {
624 r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
625 }
626 return r;
627 }
629 SPObject *
630 prev_sibling(SPObject *child)
631 {
632 SPObject *parent = SP_OBJECT_PARENT(child);
633 if (!SP_IS_GROUP(parent)) {
634 return NULL;
635 }
636 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
637 if (i->next == child)
638 return i;
639 }
640 return NULL;
641 }
643 void
644 sp_selection_raise(SPDesktop *desktop)
645 {
646 if (!desktop)
647 return;
649 Inkscape::Selection *selection = sp_desktop_selection(desktop);
651 GSList const *items = (GSList *) selection->itemList();
652 if (!items) {
653 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
654 return;
655 }
657 SPGroup const *group = sp_item_list_common_parent_group(items);
658 if (!group) {
659 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
660 return;
661 }
663 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
665 /* Construct reverse-ordered list of selected children. */
666 GSList *rev = g_slist_copy((GSList *) items);
667 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
669 // Determine the common bbox of the selected items.
670 boost::optional<Geom::Rect> selected = enclose_items(items);
672 // Iterate over all objects in the selection (starting from top).
673 if (selected) {
674 while (rev) {
675 SPObject *child = SP_OBJECT(rev->data);
676 // for each selected object, find the next sibling
677 for (SPObject *newref = child->next; newref; newref = newref->next) {
678 // if the sibling is an item AND overlaps our selection,
679 if (SP_IS_ITEM(newref)) {
680 boost::optional<Geom::Rect> newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
681 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
682 // AND if it's not one of our selected objects,
683 if (!g_slist_find((GSList *) items, newref)) {
684 // move the selected object after that sibling
685 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
686 }
687 break;
688 }
689 }
690 }
691 rev = g_slist_remove(rev, child);
692 }
693 } else {
694 g_slist_free(rev);
695 }
697 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
698 //TRANSLATORS: Only put the word "Raise" in the translation. Means "to raise an object" in the undo history
699 Q_("undo_action|Raise"));
700 }
702 void sp_selection_raise_to_top(SPDesktop *desktop)
703 {
704 if (desktop == NULL)
705 return;
707 SPDocument *document = sp_desktop_document(desktop);
708 Inkscape::Selection *selection = sp_desktop_selection(desktop);
710 if (selection->isEmpty()) {
711 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
712 return;
713 }
715 GSList const *items = (GSList *) selection->itemList();
717 SPGroup const *group = sp_item_list_common_parent_group(items);
718 if (!group) {
719 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
720 return;
721 }
723 GSList *rl = g_slist_copy((GSList *) selection->reprList());
724 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
726 for (GSList *l = rl; l != NULL; l = l->next) {
727 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
728 repr->setPosition(-1);
729 }
731 g_slist_free(rl);
733 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
734 _("Raise to top"));
735 }
737 void
738 sp_selection_lower(SPDesktop *desktop)
739 {
740 if (desktop == NULL)
741 return;
743 Inkscape::Selection *selection = sp_desktop_selection(desktop);
745 GSList const *items = (GSList *) selection->itemList();
746 if (!items) {
747 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
748 return;
749 }
751 SPGroup const *group = sp_item_list_common_parent_group(items);
752 if (!group) {
753 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
754 return;
755 }
757 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
759 // Determine the common bbox of the selected items.
760 boost::optional<Geom::Rect> selected = enclose_items(items);
762 /* Construct direct-ordered list of selected children. */
763 GSList *rev = g_slist_copy((GSList *) items);
764 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
765 rev = g_slist_reverse(rev);
767 // Iterate over all objects in the selection (starting from top).
768 if (selected) {
769 while (rev) {
770 SPObject *child = SP_OBJECT(rev->data);
771 // for each selected object, find the prev sibling
772 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
773 // if the sibling is an item AND overlaps our selection,
774 if (SP_IS_ITEM(newref)) {
775 boost::optional<Geom::Rect> ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
776 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
777 // AND if it's not one of our selected objects,
778 if (!g_slist_find((GSList *) items, newref)) {
779 // move the selected object before that sibling
780 SPObject *put_after = prev_sibling(newref);
781 if (put_after)
782 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
783 else
784 SP_OBJECT_REPR(child)->setPosition(0);
785 }
786 break;
787 }
788 }
789 }
790 rev = g_slist_remove(rev, child);
791 }
792 } else {
793 g_slist_free(rev);
794 }
796 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
797 _("Lower"));
798 }
800 void sp_selection_lower_to_bottom(SPDesktop *desktop)
801 {
802 if (desktop == NULL)
803 return;
805 SPDocument *document = sp_desktop_document(desktop);
806 Inkscape::Selection *selection = sp_desktop_selection(desktop);
808 if (selection->isEmpty()) {
809 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
810 return;
811 }
813 GSList const *items = (GSList *) selection->itemList();
815 SPGroup const *group = sp_item_list_common_parent_group(items);
816 if (!group) {
817 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
818 return;
819 }
821 GSList *rl;
822 rl = g_slist_copy((GSList *) selection->reprList());
823 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
824 rl = g_slist_reverse(rl);
826 for (GSList *l = rl; l != NULL; l = l->next) {
827 gint minpos;
828 SPObject *pp, *pc;
829 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
830 pp = document->getObjectByRepr(sp_repr_parent(repr));
831 minpos = 0;
832 g_assert(SP_IS_GROUP(pp));
833 pc = sp_object_first_child(pp);
834 while (!SP_IS_ITEM(pc)) {
835 minpos += 1;
836 pc = pc->next;
837 }
838 repr->setPosition(minpos);
839 }
841 g_slist_free(rl);
843 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
844 _("Lower to bottom"));
845 }
847 void
848 sp_undo(SPDesktop *desktop, SPDocument *)
849 {
850 if (!sp_document_undo(sp_desktop_document(desktop)))
851 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
852 }
854 void
855 sp_redo(SPDesktop *desktop, SPDocument *)
856 {
857 if (!sp_document_redo(sp_desktop_document(desktop)))
858 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
859 }
861 void sp_selection_cut(SPDesktop *desktop)
862 {
863 sp_selection_copy();
864 sp_selection_delete(desktop);
865 }
867 /**
868 * \pre item != NULL
869 */
870 SPCSSAttr *
871 take_style_from_item (SPItem *item)
872 {
873 // write the complete cascaded style, context-free
874 SPCSSAttr *css = sp_css_attr_from_object (SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
875 if (css == NULL)
876 return NULL;
878 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
879 (SP_IS_TEXT (item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
880 // if this is a text with exactly one tspan child, merge the style of that tspan as well
881 // If this is a group, merge the style of its topmost (last) child with style
882 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV (last_element)) {
883 if (SP_OBJECT_STYLE (last_element) != NULL) {
884 SPCSSAttr *temp = sp_css_attr_from_object (last_element, SP_STYLE_FLAG_IFSET);
885 if (temp) {
886 sp_repr_css_merge (css, temp);
887 sp_repr_css_attr_unref (temp);
888 }
889 break;
890 }
891 }
892 }
893 if (!(SP_IS_TEXT (item) || SP_IS_TSPAN (item) || SP_IS_TREF(item) || SP_IS_STRING (item))) {
894 // do not copy text properties from non-text objects, it's confusing
895 css = sp_css_attr_unset_text (css);
896 }
898 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
899 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
900 if (ex != 1.0) {
901 css = sp_css_attr_scale (css, ex);
902 }
904 return css;
905 }
908 void sp_selection_copy()
909 {
910 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
911 cm->copy();
912 }
914 void sp_selection_paste(SPDesktop *desktop, bool in_place)
915 {
916 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
917 if(cm->paste(in_place))
918 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
919 }
921 void sp_selection_paste_style(SPDesktop *desktop)
922 {
923 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
924 if(cm->pasteStyle())
925 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
926 }
929 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
930 {
931 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
932 if(cm->pastePathEffect())
933 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
934 _("Paste live path effect"));
935 }
938 void sp_selection_remove_livepatheffect_impl(SPItem *item)
939 {
940 if ( item && SP_IS_LPE_ITEM(item) ) {
941 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
942 }
943 }
945 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
946 {
947 if (desktop == NULL) return;
949 Inkscape::Selection *selection = sp_desktop_selection(desktop);
951 // check if something is selected
952 if (selection->isEmpty()) {
953 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
954 return;
955 }
957 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
958 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
960 sp_selection_remove_livepatheffect_impl(item);
962 }
964 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
965 _("Remove live path effect"));
966 }
968 void sp_selection_remove_filter (SPDesktop *desktop)
969 {
970 if (desktop == NULL) return;
972 Inkscape::Selection *selection = sp_desktop_selection(desktop);
974 // check if something is selected
975 if (selection->isEmpty()) {
976 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
977 return;
978 }
980 SPCSSAttr *css = sp_repr_css_attr_new();
981 sp_repr_css_unset_property(css, "filter");
982 sp_desktop_set_style(desktop, css);
983 sp_repr_css_attr_unref(css);
985 sp_document_done(sp_desktop_document (desktop), SP_VERB_EDIT_REMOVE_FILTER,
986 _("Remove filter"));
987 }
990 void sp_selection_paste_size (SPDesktop *desktop, bool apply_x, bool apply_y)
991 {
992 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
993 if(cm->pasteSize(false, apply_x, apply_y))
994 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
995 _("Paste size"));
996 }
998 void sp_selection_paste_size_separately (SPDesktop *desktop, bool apply_x, bool apply_y)
999 {
1000 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1001 if(cm->pasteSize(true, apply_x, apply_y))
1002 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1003 _("Paste size separately"));
1004 }
1006 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1007 {
1008 Inkscape::Selection *selection = sp_desktop_selection(dt);
1010 // check if something is selected
1011 if (selection->isEmpty()) {
1012 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1013 return;
1014 }
1016 GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1018 bool no_more = false; // Set to true, if no more layers above
1019 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1020 if (next) {
1021 GSList *temp_clip = NULL;
1022 sp_selection_copy_impl (items, &temp_clip, sp_document_repr_doc(dt->doc()));
1023 sp_selection_delete_impl (items, false, false);
1024 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1025 GSList *copied;
1026 if(next) {
1027 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1028 } else {
1029 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1030 no_more = true;
1031 }
1032 selection->setReprList((GSList const *) copied);
1033 g_slist_free (copied);
1034 if (temp_clip) g_slist_free (temp_clip);
1035 if (next) dt->setCurrentLayer(next);
1036 if ( !suppressDone ) {
1037 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1038 _("Raise to next layer"));
1039 }
1040 } else {
1041 no_more = true;
1042 }
1044 if (no_more) {
1045 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1046 }
1048 g_slist_free ((GSList *) items);
1049 }
1051 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1052 {
1053 Inkscape::Selection *selection = sp_desktop_selection(dt);
1055 // check if something is selected
1056 if (selection->isEmpty()) {
1057 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1058 return;
1059 }
1061 GSList const *items = g_slist_copy ((GSList *) selection->itemList());
1063 bool no_more = false; // Set to true, if no more layers below
1064 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1065 if (next) {
1066 GSList *temp_clip = NULL;
1067 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
1068 sp_selection_delete_impl (items, false, false);
1069 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1070 GSList *copied;
1071 if(next) {
1072 copied = sp_selection_paste_impl (sp_desktop_document (dt), next, &temp_clip);
1073 } else {
1074 copied = sp_selection_paste_impl (sp_desktop_document (dt), dt->currentLayer(), &temp_clip);
1075 no_more = true;
1076 }
1077 selection->setReprList((GSList const *) copied);
1078 g_slist_free (copied);
1079 if (temp_clip) g_slist_free (temp_clip);
1080 if (next) dt->setCurrentLayer(next);
1081 if ( !suppressDone ) {
1082 sp_document_done(sp_desktop_document (dt), SP_VERB_LAYER_MOVE_TO_PREV,
1083 _("Lower to previous layer"));
1084 }
1085 } else {
1086 no_more = true;
1087 }
1089 if (no_more) {
1090 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1091 }
1093 g_slist_free ((GSList *) items);
1094 }
1096 bool
1097 selection_contains_original (SPItem *item, Inkscape::Selection *selection)
1098 {
1099 bool contains_original = false;
1101 bool is_use = SP_IS_USE(item);
1102 SPItem *item_use = item;
1103 SPItem *item_use_first = item;
1104 while (is_use && item_use && !contains_original)
1105 {
1106 item_use = sp_use_get_original (SP_USE(item_use));
1107 contains_original |= selection->includes(item_use);
1108 if (item_use == item_use_first)
1109 break;
1110 is_use = SP_IS_USE(item_use);
1111 }
1113 // If it's a tref, check whether the object containing the character
1114 // data is part of the selection
1115 if (!contains_original && SP_IS_TREF(item)) {
1116 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1117 }
1119 return contains_original;
1120 }
1123 bool
1124 selection_contains_both_clone_and_original (Inkscape::Selection *selection)
1125 {
1126 bool clone_with_original = false;
1127 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1128 SPItem *item = SP_ITEM(l->data);
1129 clone_with_original |= selection_contains_original(item, selection);
1130 if (clone_with_original)
1131 break;
1132 }
1133 return clone_with_original;
1134 }
1137 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1138 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1139 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1140 that case, items are already in the new position, but the repr is in the old, and this function
1141 then simply updates the repr from item->transform.
1142 */
1143 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d)
1144 {
1145 if (selection->isEmpty())
1146 return;
1148 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1149 SPItem *item = SP_ITEM(l->data);
1151 Geom::Point old_center(0,0);
1152 if (set_i2d && item->isCenterSet())
1153 old_center = item->getCenter();
1155 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1156 At the time of writing, this is the only place to re-enable. */
1157 sp_item_update_cns(*item, selection->desktop());
1158 #endif
1160 // we're moving both a clone and its original or any ancestor in clone chain?
1161 bool transform_clone_with_original = selection_contains_original(item, selection);
1162 // ...both a text-on-path and its path?
1163 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)))) ));
1164 // ...both a flowtext and its frame?
1165 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)
1166 // ...both an offset and its source?
1167 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) && selection->includes( sp_offset_get_source (SP_OFFSET(item)) );
1169 // If we're moving a connector, we want to detach it
1170 // from shapes that aren't part of the selection, but
1171 // leave it attached if they are
1172 if (cc_item_is_connector(item)) {
1173 SPItem *attItem[2];
1174 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1176 for (int n = 0; n < 2; ++n) {
1177 if (!selection->includes(attItem[n])) {
1178 sp_conn_end_detach(item, n);
1179 }
1180 }
1181 }
1183 // "clones are unmoved when original is moved" preference
1184 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1185 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1186 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1187 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1189 // If this is a clone and it's selected along with its original, do not move it; it will feel the
1190 // transform of its original and respond to it itself. Without this, a clone is doubly
1191 // transformed, very unintuitive.
1192 // Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1193 // letters cannot be squeezed or rotated anyway, they only refill the changed path.
1194 // Same for linked offset if we are also moving its source: do not move it.
1195 if (transform_textpath_with_path || transform_offset_with_source) {
1196 // restore item->transform field from the repr, in case it was changed by seltrans
1197 sp_object_read_attr (SP_OBJECT (item), "transform");
1199 } else if (transform_flowtext_with_frame) {
1200 // apply the inverse of the region's transform to the <use> so that the flow remains
1201 // the same (even though the output itself gets transformed)
1202 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1203 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1204 continue;
1205 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1206 if (!SP_IS_USE(use)) continue;
1207 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL);
1208 }
1209 }
1210 } else if (transform_clone_with_original) {
1211 // We are transforming a clone along with its original. The below matrix juggling is
1212 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1213 // transform and its move compensation are both cancelled out.
1215 // restore item->transform field from the repr, in case it was changed by seltrans
1216 sp_object_read_attr (SP_OBJECT (item), "transform");
1218 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1219 Geom::Matrix parent_transform = sp_item_i2root_affine(SP_ITEM(SP_OBJECT_PARENT (item)));
1220 Geom::Matrix t = parent_transform * matrix_to_desktop (matrix_from_desktop (affine, item), item) * parent_transform.inverse();
1221 Geom::Matrix t_inv =parent_transform * matrix_to_desktop (matrix_from_desktop (affine.inverse(), item), item) * parent_transform.inverse();
1222 Geom::Matrix result = t_inv * item->transform * t;
1224 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1225 // we need to cancel out the move compensation, too
1227 // find out the clone move, same as in sp_use_move_compensate
1228 Geom::Matrix parent = sp_use_get_parent_transform (SP_USE(item));
1229 Geom::Matrix clone_move = parent.inverse() * t * parent;
1231 if (prefs_parallel) {
1232 Geom::Matrix move = result * clone_move * t_inv;
1233 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move);
1235 } else if (prefs_unmoved) {
1236 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1237 // clone_move = NR::identity();
1238 Geom::Matrix move = result * clone_move;
1239 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t);
1240 }
1242 } else {
1243 // just apply the result
1244 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t);
1245 }
1247 } else {
1248 if (set_i2d) {
1249 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1250 }
1251 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL);
1252 }
1254 // if we're moving the actual object, not just updating the repr, we can transform the
1255 // center by the same matrix (only necessary for non-translations)
1256 if (set_i2d && item->isCenterSet() && !affine.isTranslation()) {
1257 item->setCenter(old_center * affine);
1258 SP_OBJECT(item)->updateRepr();
1259 }
1260 }
1261 }
1263 void sp_selection_remove_transform(SPDesktop *desktop)
1264 {
1265 if (desktop == NULL)
1266 return;
1268 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1270 GSList const *l = (GSList *) selection->reprList();
1271 while (l != NULL) {
1272 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1273 l = l->next;
1274 }
1276 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1277 _("Remove transform"));
1278 }
1280 void
1281 sp_selection_scale_absolute(Inkscape::Selection *selection,
1282 double const x0, double const x1,
1283 double const y0, double const y1)
1284 {
1285 if (selection->isEmpty())
1286 return;
1288 boost::optional<Geom::Rect> const bbox(selection->bounds());
1289 if ( !bbox || bbox->isEmpty() ) {
1290 return;
1291 }
1293 Geom::Translate const p2o(-bbox->min());
1295 Geom::Scale const newSize(x1 - x0,
1296 y1 - y0);
1297 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1298 Geom::Translate const o2n(x0, y0);
1299 NR::Matrix const final( p2o * scale * o2n );
1301 sp_selection_apply_affine(selection, final);
1302 }
1305 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1306 {
1307 if (selection->isEmpty())
1308 return;
1310 boost::optional<Geom::Rect> const bbox(selection->bounds());
1312 if ( !bbox || bbox->isEmpty() ) {
1313 return;
1314 }
1316 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1317 if ( bbox->dimensions()[NR::X] * scale[Geom::X] > 1e6 ||
1318 bbox->dimensions()[NR::Y] * scale[Geom::Y] > 1e6 )
1319 {
1320 return;
1321 }
1323 Geom::Translate const n2d(-align);
1324 Geom::Translate const d2n(align);
1325 Geom::Matrix const final( n2d * scale * d2n );
1326 sp_selection_apply_affine(selection, final);
1327 }
1329 void
1330 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1331 {
1332 Geom::Translate const d2n(center);
1333 Geom::Translate const n2d(-center);
1334 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1335 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1336 sp_selection_apply_affine(selection, final);
1337 }
1339 void
1340 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1341 {
1342 Geom::Translate const d2n(align);
1343 Geom::Translate const n2d(-align);
1344 Geom::Matrix const skew(1, dy,
1345 dx, 1,
1346 0, 0);
1347 Geom::Matrix const final( n2d * skew * d2n );
1348 sp_selection_apply_affine(selection, final);
1349 }
1351 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move)
1352 {
1353 sp_selection_apply_affine(selection, NR::Matrix(Geom::Translate(move)));
1354 }
1356 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1357 {
1358 sp_selection_apply_affine(selection, NR::Matrix(Geom::Translate(dx, dy)));
1359 }
1361 /**
1362 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1363 */
1364 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1365 {
1366 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1368 if (selection->isEmpty())
1369 return;
1371 GSList const *l = selection->itemList();
1372 Geom::Rotate const rot_90(NR::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1373 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1374 SPItem *item = SP_ITEM(l2->data);
1375 sp_item_rotate_rel(item, rot_90);
1376 }
1378 sp_document_done(sp_desktop_document(desktop),
1379 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1380 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1381 }
1383 void
1384 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1385 {
1386 if (selection->isEmpty())
1387 return;
1389 boost::optional<Geom::Point> center = selection->center();
1390 if (!center) {
1391 return;
1392 }
1394 sp_selection_rotate_relative(selection, *center, angle_degrees);
1396 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1397 ( ( angle_degrees > 0 )
1398 ? "selector:rotate:ccw"
1399 : "selector:rotate:cw" ),
1400 SP_VERB_CONTEXT_SELECT,
1401 _("Rotate"));
1402 }
1404 // helper function:
1405 static
1406 Geom::Point
1407 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1408 Geom::Point m = r.midpoint();
1409 unsigned i = 0;
1410 if (p[X] < m[X]) {
1411 i = 1;
1412 }
1413 if (p[Y] < m[Y]) {
1414 i = 3 - i;
1415 }
1416 return r.corner(i);
1417 }
1419 /**
1420 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1421 */
1422 void
1423 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1424 {
1425 if (selection->isEmpty())
1426 return;
1428 boost::optional<Geom::Rect> const bbox(selection->bounds());
1429 boost::optional<Geom::Point> center = selection->center();
1431 if ( !bbox || !center ) {
1432 return;
1433 }
1435 gdouble const zoom = selection->desktop()->current_zoom();
1436 gdouble const zmove = angle / zoom;
1437 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1439 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1441 sp_selection_rotate_relative(selection, *center, zangle);
1443 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1444 ( (angle > 0)
1445 ? "selector:rotate:ccw"
1446 : "selector:rotate:cw" ),
1447 SP_VERB_CONTEXT_SELECT,
1448 _("Rotate by pixels"));
1449 }
1451 void
1452 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1453 {
1454 if (selection->isEmpty())
1455 return;
1457 boost::optional<Geom::Rect> const bbox(selection->bounds());
1458 if (!bbox) {
1459 return;
1460 }
1462 Geom::Point const center(bbox->midpoint());
1464 // you can't scale "do nizhe pola" (below zero)
1465 double const max_len = bbox->maxExtent();
1466 if ( max_len + grow <= 1e-3 ) {
1467 return;
1468 }
1470 double const times = 1.0 + grow / max_len;
1471 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1473 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1474 ( (grow > 0)
1475 ? "selector:scale:larger"
1476 : "selector:scale:smaller" ),
1477 SP_VERB_CONTEXT_SELECT,
1478 _("Scale"));
1479 }
1481 void
1482 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1483 {
1484 sp_selection_scale(selection,
1485 grow_pixels / selection->desktop()->current_zoom());
1486 }
1488 void
1489 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1490 {
1491 if (selection->isEmpty())
1492 return;
1494 boost::optional<Geom::Rect> sel_bbox = selection->bounds();
1496 if (!sel_bbox) {
1497 return;
1498 }
1500 Geom::Point const center(sel_bbox->midpoint());
1501 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1502 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1503 _("Scale by whole factor"));
1504 }
1506 void
1507 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1508 {
1509 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1510 if (selection->isEmpty()) {
1511 return;
1512 }
1514 sp_selection_move_relative(selection, dx, dy);
1516 if (dx == 0) {
1517 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1518 _("Move vertically"));
1519 } else if (dy == 0) {
1520 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1521 _("Move horizontally"));
1522 } else {
1523 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1524 _("Move"));
1525 }
1526 }
1528 void
1529 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1530 {
1531 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1532 if (selection->isEmpty()) {
1533 return;
1534 }
1536 // same as sp_selection_move but divide deltas by zoom factor
1537 gdouble const zoom = desktop->current_zoom();
1538 gdouble const zdx = dx / zoom;
1539 gdouble const zdy = dy / zoom;
1540 sp_selection_move_relative(selection, zdx, zdy);
1542 if (dx == 0) {
1543 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1544 _("Move vertically by pixels"));
1545 } else if (dy == 0) {
1546 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1547 _("Move horizontally by pixels"));
1548 } else {
1549 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1550 _("Move"));
1551 }
1552 }
1554 namespace {
1556 template <typename D>
1557 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1558 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1560 template <typename D>
1561 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1562 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1564 struct Forward {
1565 typedef SPObject *Iterator;
1567 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1568 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1569 static void dispose(Iterator /*i*/) {}
1571 static SPObject *object(Iterator i) { return i; }
1572 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1573 };
1575 struct Reverse {
1576 typedef GSList *Iterator;
1578 static Iterator children(SPObject *o) {
1579 return make_list(o->firstChild(), NULL);
1580 }
1581 static Iterator siblings_after(SPObject *o) {
1582 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1583 }
1584 static void dispose(Iterator i) {
1585 g_slist_free(i);
1586 }
1588 static SPObject *object(Iterator i) {
1589 return reinterpret_cast<SPObject *>(i->data);
1590 }
1591 static Iterator next(Iterator i) { return i->next; }
1593 private:
1594 static GSList *make_list(SPObject *object, SPObject *limit) {
1595 GSList *list=NULL;
1596 while ( object != limit ) {
1597 list = g_slist_prepend(list, object);
1598 object = SP_OBJECT_NEXT(object);
1599 }
1600 return list;
1601 }
1602 };
1604 }
1606 void
1607 sp_selection_item_next(SPDesktop *desktop)
1608 {
1609 g_return_if_fail(desktop != NULL);
1610 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1612 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1613 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1614 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1615 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1617 SPObject *root;
1618 if (PREFS_SELECTION_ALL != inlayer) {
1619 root = selection->activeContext();
1620 } else {
1621 root = desktop->currentRoot();
1622 }
1624 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1626 if (item) {
1627 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1628 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1629 scroll_to_show_item(desktop, item);
1630 }
1631 }
1632 }
1634 void
1635 sp_selection_item_prev(SPDesktop *desktop)
1636 {
1637 SPDocument *document = sp_desktop_document(desktop);
1638 g_return_if_fail(document != NULL);
1639 g_return_if_fail(desktop != NULL);
1640 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1642 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1643 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1644 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1645 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1647 SPObject *root;
1648 if (PREFS_SELECTION_ALL != inlayer) {
1649 root = selection->activeContext();
1650 } else {
1651 root = desktop->currentRoot();
1652 }
1654 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1656 if (item) {
1657 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1658 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1659 scroll_to_show_item(desktop, item);
1660 }
1661 }
1662 }
1664 void sp_selection_next_patheffect_param(SPDesktop * dt)
1665 {
1666 if (!dt) return;
1668 Inkscape::Selection *selection = sp_desktop_selection(dt);
1669 if ( selection && !selection->isEmpty() ) {
1670 SPItem *item = selection->singleItem();
1671 if ( item && SP_IS_SHAPE(item)) {
1672 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1673 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1674 } else {
1675 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1676 }
1677 }
1678 }
1679 }
1681 void sp_selection_edit_clip_or_mask(SPDesktop * dt, bool clip)
1682 {
1683 if (!dt) return;
1685 Inkscape::Selection *selection = sp_desktop_selection(dt);
1686 if ( selection && !selection->isEmpty() ) {
1687 SPItem *item = selection->singleItem();
1688 if ( item ) {
1689 SPObject *obj = NULL;
1690 if (clip)
1691 obj = item->clip_ref ? SP_OBJECT(item->clip_ref->getObject()) : NULL;
1692 else
1693 obj = item->mask_ref ? SP_OBJECT(item->mask_ref->getObject()) : NULL;
1695 if (obj) {
1696 // obj is a group object, the children are the actual clippers
1697 for ( SPObject *child = obj->children ; child ; child = child->next ) {
1698 if ( SP_IS_ITEM(child) ) {
1699 // If not already in nodecontext, goto it!
1700 if (!tools_isactive(dt, TOOLS_NODES)) {
1701 tools_switch(dt, TOOLS_NODES);
1702 }
1704 ShapeEditor * shape_editor = SP_NODE_CONTEXT( dt->event_context )->shape_editor;
1705 // TODO: should we set the item for nodepath or knotholder or both? seems to work with both.
1706 shape_editor->set_item(SP_ITEM(child), SH_NODEPATH);
1707 shape_editor->set_item(SP_ITEM(child), SH_KNOTHOLDER);
1708 Inkscape::NodePath::Path *np = shape_editor->get_nodepath();
1709 if (np) {
1710 // take colors from prefs (same as used in outline mode)
1711 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1712 np->helperpath_rgba = clip ?
1713 prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff) :
1714 prefs->getInt("/options/wireframecolors/masks", 0x0000ffff);
1715 np->helperpath_width = 1.0;
1716 sp_nodepath_show_helperpath(np, true);
1717 }
1718 break; // break out of for loop after 1st encountered item
1719 }
1720 }
1721 } else if (clip) {
1722 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied clip path."));
1723 } else {
1724 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied mask."));
1725 }
1726 }
1727 }
1728 }
1731 namespace {
1733 template <typename D>
1734 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1735 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1736 {
1737 SPObject *current=root;
1738 while (items) {
1739 SPItem *item=SP_ITEM(items->data);
1740 if ( root->isAncestorOf(item) &&
1741 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1742 {
1743 current = item;
1744 break;
1745 }
1746 items = items->next;
1747 }
1749 GSList *path=NULL;
1750 while ( current != root ) {
1751 path = g_slist_prepend(path, current);
1752 current = SP_OBJECT_PARENT(current);
1753 }
1755 SPItem *next;
1756 // first, try from the current object
1757 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1758 g_slist_free(path);
1760 if (!next) { // if we ran out of objects, start over at the root
1761 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1762 }
1764 return next;
1765 }
1767 template <typename D>
1768 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1769 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1770 {
1771 typename D::Iterator children;
1772 typename D::Iterator iter;
1774 SPItem *found=NULL;
1776 if (path) {
1777 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1778 g_assert(SP_OBJECT_PARENT(object) == root);
1779 if (desktop->isLayer(object)) {
1780 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1781 }
1782 iter = children = D::siblings_after(object);
1783 } else {
1784 iter = children = D::children(root);
1785 }
1787 while ( iter && !found ) {
1788 SPObject *object=D::object(iter);
1789 if (desktop->isLayer(object)) {
1790 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1791 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1792 }
1793 } else if ( SP_IS_ITEM(object) &&
1794 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1795 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1796 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1797 !desktop->isLayer(SP_ITEM(object)) )
1798 {
1799 found = SP_ITEM(object);
1800 }
1801 iter = D::next(iter);
1802 }
1804 D::dispose(children);
1806 return found;
1807 }
1809 }
1811 /**
1812 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1813 * \a item.
1814 */
1815 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1816 {
1817 Geom::Rect dbox = desktop->get_display_area();
1818 boost::optional<Geom::Rect> sbox = sp_item_bbox_desktop(item);
1820 if ( sbox && dbox.contains(*sbox) == false ) {
1821 Geom::Point const s_dt = sbox->midpoint();
1822 Geom::Point const s_w = desktop->d2w(s_dt);
1823 Geom::Point const d_dt = dbox.midpoint();
1824 Geom::Point const d_w = desktop->d2w(d_dt);
1825 Geom::Point const moved_w( d_w - s_w );
1826 gint const dx = (gint) moved_w[X];
1827 gint const dy = (gint) moved_w[Y];
1828 desktop->scroll_world(dx, dy);
1829 }
1830 }
1833 void
1834 sp_selection_clone(SPDesktop *desktop)
1835 {
1836 if (desktop == NULL)
1837 return;
1839 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1841 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1843 // check if something is selected
1844 if (selection->isEmpty()) {
1845 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
1846 return;
1847 }
1849 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
1851 selection->clear();
1853 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
1854 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
1856 GSList *newsel = NULL;
1858 while (reprs) {
1859 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
1860 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
1862 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
1863 clone->setAttribute("x", "0", false);
1864 clone->setAttribute("y", "0", false);
1865 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
1867 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
1868 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
1870 // add the new clone to the top of the original's parent
1871 parent->appendChild(clone);
1873 newsel = g_slist_prepend(newsel, clone);
1874 reprs = g_slist_remove(reprs, sel_repr);
1875 Inkscape::GC::release(clone);
1876 }
1878 // TRANSLATORS: only translate "string" in "context|string".
1879 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
1880 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
1881 Q_("action|Clone"));
1883 selection->setReprList(newsel);
1885 g_slist_free(newsel);
1886 }
1888 void
1889 sp_selection_relink(SPDesktop *desktop)
1890 {
1891 if (!desktop)
1892 return;
1894 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1896 if (selection->isEmpty()) {
1897 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
1898 return;
1899 }
1901 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1902 const gchar *newid = cm->getFirstObjectID();
1903 if (!newid) {
1904 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
1905 return;
1906 }
1907 gchar *newref = g_strdup_printf ("#%s", newid);
1909 // Get a copy of current selection.
1910 bool relinked = false;
1911 for (GSList *items = (GSList *) selection->itemList();
1912 items != NULL;
1913 items = items->next)
1914 {
1915 SPItem *item = (SPItem *) items->data;
1917 if (!SP_IS_USE(item))
1918 continue;
1920 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
1921 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1922 relinked = true;
1923 }
1925 g_free(newref);
1927 if (!relinked) {
1928 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
1929 } else {
1930 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1931 _("Relink clone"));
1932 }
1933 }
1936 void
1937 sp_selection_unlink(SPDesktop *desktop)
1938 {
1939 if (!desktop)
1940 return;
1942 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1944 if (selection->isEmpty()) {
1945 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
1946 return;
1947 }
1949 // Get a copy of current selection.
1950 GSList *new_select = NULL;
1951 bool unlinked = false;
1952 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
1953 items != NULL;
1954 items = items->next)
1955 {
1956 SPItem *item = (SPItem *) items->data;
1958 if (SP_IS_TEXT(item)) {
1959 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
1961 if (tspan) {
1962 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
1963 }
1965 // Set unlink to true, and fall into the next if which
1966 // will include this text item in the new selection
1967 unlinked = true;
1968 }
1970 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
1971 // keep the non-use item in the new selection
1972 new_select = g_slist_prepend(new_select, item);
1973 continue;
1974 }
1976 SPItem *unlink;
1977 if (SP_IS_USE(item)) {
1978 unlink = sp_use_unlink(SP_USE(item));
1979 } else /*if (SP_IS_TREF(use))*/ {
1980 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
1981 }
1983 unlinked = true;
1984 // Add ungrouped items to the new selection.
1985 new_select = g_slist_prepend(new_select, unlink);
1986 }
1988 if (new_select) { // set new selection
1989 selection->clear();
1990 selection->setList(new_select);
1991 g_slist_free(new_select);
1992 }
1993 if (!unlinked) {
1994 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
1995 }
1997 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
1998 _("Unlink clone"));
1999 }
2001 void
2002 sp_select_clone_original(SPDesktop *desktop)
2003 {
2004 if (desktop == NULL)
2005 return;
2007 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2009 SPItem *item = selection->singleItem();
2011 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.");
2013 // Check if other than two objects are selected
2014 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2015 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2016 return;
2017 }
2019 SPItem *original = NULL;
2020 if (SP_IS_USE(item)) {
2021 original = sp_use_get_original (SP_USE(item));
2022 } else if (SP_IS_OFFSET(item) && SP_OFFSET (item)->sourceHref) {
2023 original = sp_offset_get_source (SP_OFFSET(item));
2024 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2025 original = sp_textpath_get_path_item (SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2026 } else if (SP_IS_FLOWTEXT(item)) {
2027 original = SP_FLOWTEXT(item)->get_frame (NULL); // first frame only
2028 } else { // it's an object that we don't know what to do with
2029 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2030 return;
2031 }
2033 if (!original) {
2034 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2035 return;
2036 }
2038 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT (o)) {
2039 if (SP_IS_DEFS (o)) {
2040 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2041 return;
2042 }
2043 }
2045 if (original) {
2046 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2047 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2048 if (highlight) {
2049 boost::optional<Geom::Rect> a = item->getBounds(sp_item_i2d_affine(item));
2050 boost::optional<Geom::Rect> b = original->getBounds(sp_item_i2d_affine(original));
2051 if ( a && b ) {
2052 // draw a flashing line between the objects
2053 SPCurve *curve = new SPCurve();
2054 curve->moveto(a->midpoint());
2055 curve->lineto(b->midpoint());
2057 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2058 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2059 sp_canvas_item_show(canvasitem);
2060 curve->unref();
2061 desktop->add_temporary_canvasitem (canvasitem, 1000);
2062 }
2063 }
2065 selection->clear();
2066 selection->set(original);
2067 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2068 scroll_to_show_item(desktop, original);
2069 }
2070 }
2071 }
2074 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2075 {
2076 if (desktop == NULL)
2077 return;
2079 SPDocument *doc = sp_desktop_document(desktop);
2080 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2082 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2084 // check if something is selected
2085 if (selection->isEmpty()) {
2086 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2087 return;
2088 }
2090 sp_document_ensure_up_to_date(doc);
2091 boost::optional<Geom::Rect> r = selection->bounds();
2092 boost::optional<Geom::Point> c = selection->center();
2093 if ( !r || !c || r->isEmpty() ) {
2094 return;
2095 }
2097 // calculate the transform to be applied to objects to move them to 0,0
2098 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2099 move_p[Geom::Y] = -move_p[Geom::Y];
2100 Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2102 GSList *items = g_slist_copy((GSList *) selection->itemList());
2104 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2106 // bottommost object, after sorting
2107 SPObject *parent = SP_OBJECT_PARENT (items->data);
2109 Geom::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2111 // remember the position of the first item
2112 gint pos = SP_OBJECT_REPR (items->data)->position();
2113 (void)pos; // TODO check why this was remembered
2115 // create a list of duplicates
2116 GSList *repr_copies = NULL;
2117 for (GSList *i = items; i != NULL; i = i->next) {
2118 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2119 repr_copies = g_slist_prepend (repr_copies, dup);
2120 }
2122 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2124 if (apply) {
2125 // delete objects so that their clones don't get alerted; this object will be restored shortly
2126 for (GSList *i = items; i != NULL; i = i->next) {
2127 SPObject *item = SP_OBJECT (i->data);
2128 item->deleteObject (false);
2129 }
2130 }
2132 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2133 // without disturbing clones.
2134 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2135 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2136 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2137 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2139 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2140 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2141 Geom::Point(r->min()[Geom::X],
2142 r->max()[Geom::Y]))))
2143 * parent_transform.inverse() ),
2144 parent_transform * move);
2145 (void)mark_id;
2147 // restore compensation setting
2148 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2151 g_slist_free (items);
2153 sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2154 _("Objects to marker"));
2155 }
2157 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2158 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2159 for (GSList *i = sp_item_group_item_list (SP_GROUP(item)); i != NULL; i = i->next) {
2160 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2161 }
2162 } else {
2163 sp_item_convert_item_to_guides(item);
2165 if (deleteitem) {
2166 SP_OBJECT(item)->deleteObject(true);
2167 }
2168 }
2169 }
2171 void sp_selection_to_guides(SPDesktop *desktop)
2172 {
2173 if (desktop == NULL)
2174 return;
2176 SPDocument *doc = sp_desktop_document(desktop);
2177 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2178 // we need to copy the list because it gets reset when objects are deleted
2179 GSList *items = g_slist_copy((GSList *) selection->itemList());
2181 if (!items) {
2182 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2183 return;
2184 }
2186 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2187 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2188 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2190 for (GSList const *i = items; i != NULL; i = i->next) {
2191 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2192 }
2194 sp_document_done (doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2195 }
2197 void
2198 sp_selection_tile(SPDesktop *desktop, bool apply)
2199 {
2200 if (desktop == NULL)
2201 return;
2203 SPDocument *doc = sp_desktop_document(desktop);
2204 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2206 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2208 // check if something is selected
2209 if (selection->isEmpty()) {
2210 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2211 return;
2212 }
2214 sp_document_ensure_up_to_date(doc);
2215 boost::optional<Geom::Rect> r = selection->bounds();
2216 if ( !r || r->isEmpty() ) {
2217 return;
2218 }
2220 // calculate the transform to be applied to objects to move them to 0,0
2221 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point (0, r->dimensions()[NR::Y]));
2222 move_p[Geom::Y] = -move_p[Geom::Y];
2223 Geom::Matrix move = Geom::Matrix (Geom::Translate (move_p));
2225 GSList *items = g_slist_copy((GSList *) selection->itemList());
2227 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2229 // bottommost object, after sorting
2230 SPObject *parent = SP_OBJECT_PARENT (items->data);
2232 Geom::Matrix parent_transform (sp_item_i2root_affine(SP_ITEM(parent)));
2234 // remember the position of the first item
2235 gint pos = SP_OBJECT_REPR (items->data)->position();
2237 // create a list of duplicates
2238 GSList *repr_copies = NULL;
2239 for (GSList *i = items; i != NULL; i = i->next) {
2240 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2241 repr_copies = g_slist_prepend (repr_copies, dup);
2242 }
2243 // restore the z-order after prepends
2244 repr_copies = g_slist_reverse (repr_copies);
2246 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2248 if (apply) {
2249 // delete objects so that their clones don't get alerted; this object will be restored shortly
2250 for (GSList *i = items; i != NULL; i = i->next) {
2251 SPObject *item = SP_OBJECT (i->data);
2252 item->deleteObject (false);
2253 }
2254 }
2256 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2257 // without disturbing clones.
2258 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2259 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2260 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2261 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2263 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2264 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2265 r->max()[Geom::Y]))))
2266 * to_2geom(parent_transform.inverse()) ),
2267 parent_transform * move);
2269 // restore compensation setting
2270 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2272 if (apply) {
2273 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2274 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2276 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2277 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2279 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2280 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2281 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2282 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2284 // restore parent and position
2285 SP_OBJECT_REPR (parent)->appendChild(rect);
2286 rect->setPosition(pos > 0 ? pos : 0);
2287 SPItem *rectangle = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(rect);
2289 Inkscape::GC::release(rect);
2291 selection->clear();
2292 selection->set(rectangle);
2293 }
2295 g_slist_free (items);
2297 sp_document_done (doc, SP_VERB_EDIT_TILE,
2298 _("Objects to pattern"));
2299 }
2301 void
2302 sp_selection_untile(SPDesktop *desktop)
2303 {
2304 if (desktop == NULL)
2305 return;
2307 SPDocument *doc = sp_desktop_document(desktop);
2308 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2310 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2312 // check if something is selected
2313 if (selection->isEmpty()) {
2314 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2315 return;
2316 }
2318 GSList *new_select = NULL;
2320 bool did = false;
2322 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2323 items != NULL;
2324 items = items->next) {
2326 SPItem *item = (SPItem *) items->data;
2328 SPStyle *style = SP_OBJECT_STYLE (item);
2330 if (!style || !style->fill.isPaintserver())
2331 continue;
2333 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2335 if (!SP_IS_PATTERN(server))
2336 continue;
2338 did = true;
2340 SPPattern *pattern = pattern_getroot (SP_PATTERN (server));
2342 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform (SP_PATTERN (server)));
2343 pat_transform *= item->transform;
2345 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2346 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2347 SPItem *i = SP_ITEM (desktop->currentLayer()->appendChildRepr(copy));
2349 // FIXME: relink clones to the new canvas objects
2350 // use SPObject::setid when mental finishes it to steal ids of
2352 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2353 sp_document_ensure_up_to_date (doc);
2355 Geom::Matrix transform( i->transform * pat_transform );
2356 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2358 new_select = g_slist_prepend(new_select, i);
2359 }
2361 SPCSSAttr *css = sp_repr_css_attr_new ();
2362 sp_repr_css_set_property (css, "fill", "none");
2363 sp_repr_css_change (SP_OBJECT_REPR (item), css, "style");
2364 }
2366 if (!did) {
2367 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2368 } else {
2369 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2370 _("Pattern to objects"));
2371 selection->setList(new_select);
2372 }
2373 }
2375 void
2376 sp_selection_get_export_hints (Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2377 {
2378 if (selection->isEmpty()) {
2379 return;
2380 }
2382 GSList const *reprlst = selection->reprList();
2383 bool filename_search = TRUE;
2384 bool xdpi_search = TRUE;
2385 bool ydpi_search = TRUE;
2387 for(; reprlst != NULL &&
2388 filename_search &&
2389 xdpi_search &&
2390 ydpi_search;
2391 reprlst = reprlst->next) {
2392 gchar const *dpi_string;
2393 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2395 if (filename_search) {
2396 *filename = repr->attribute("inkscape:export-filename");
2397 if (*filename != NULL)
2398 filename_search = FALSE;
2399 }
2401 if (xdpi_search) {
2402 dpi_string = NULL;
2403 dpi_string = repr->attribute("inkscape:export-xdpi");
2404 if (dpi_string != NULL) {
2405 *xdpi = atof(dpi_string);
2406 xdpi_search = FALSE;
2407 }
2408 }
2410 if (ydpi_search) {
2411 dpi_string = NULL;
2412 dpi_string = repr->attribute("inkscape:export-ydpi");
2413 if (dpi_string != NULL) {
2414 *ydpi = atof(dpi_string);
2415 ydpi_search = FALSE;
2416 }
2417 }
2418 }
2419 }
2421 void
2422 sp_document_get_export_hints (SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2423 {
2424 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2425 gchar const *dpi_string;
2427 *filename = repr->attribute("inkscape:export-filename");
2429 dpi_string = NULL;
2430 dpi_string = repr->attribute("inkscape:export-xdpi");
2431 if (dpi_string != NULL) {
2432 *xdpi = atof(dpi_string);
2433 }
2435 dpi_string = NULL;
2436 dpi_string = repr->attribute("inkscape:export-ydpi");
2437 if (dpi_string != NULL) {
2438 *ydpi = atof(dpi_string);
2439 }
2440 }
2442 void
2443 sp_selection_create_bitmap_copy (SPDesktop *desktop)
2444 {
2445 if (desktop == NULL)
2446 return;
2448 SPDocument *document = sp_desktop_document(desktop);
2449 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2451 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2453 // check if something is selected
2454 if (selection->isEmpty()) {
2455 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2456 return;
2457 }
2459 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2460 // set "busy" cursor
2461 desktop->setWaitingCursor();
2463 // Get the bounding box of the selection
2464 NRRect bbox;
2465 sp_document_ensure_up_to_date (document);
2466 selection->bounds(&bbox);
2467 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2468 desktop->clearWaitingCursor();
2469 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2470 }
2472 // List of the items to show; all others will be hidden
2473 GSList *items = g_slist_copy ((GSList *) selection->itemList());
2475 // Sort items so that the topmost comes last
2476 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2478 // Generate a random value from the current time (you may create bitmap from the same object(s)
2479 // multiple times, and this is done so that they don't clash)
2480 GTimeVal cu;
2481 g_get_current_time (&cu);
2482 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2484 // Create the filename
2485 gchar *filename = g_strdup_printf ("%s-%s-%u.png", document->name, SP_OBJECT_REPR(items->data)->attribute("id"), current);
2486 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2487 // digits, and a few other chars, with "_"
2488 filename = g_strcanon (filename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2489 // Build the complete path by adding document->base if set
2490 gchar *filepath = g_build_filename (document->base?document->base:"", filename, NULL);
2492 //g_print ("%s\n", filepath);
2494 // Remember parent and z-order of the topmost one
2495 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2496 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2497 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2499 // Calculate resolution
2500 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2501 double res;
2502 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2503 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2504 if (0 < prefs_res) {
2505 // If it's given explicitly in prefs, take it
2506 res = prefs_res;
2507 } else if (0 < prefs_min) {
2508 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2509 res = PX_PER_IN * prefs_min / MIN ((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2510 } else {
2511 float hint_xdpi = 0, hint_ydpi = 0;
2512 char const *hint_filename;
2513 // take resolution hint from the selected objects
2514 sp_selection_get_export_hints (selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2515 if (hint_xdpi != 0) {
2516 res = hint_xdpi;
2517 } else {
2518 // take resolution hint from the document
2519 sp_document_get_export_hints (document, &hint_filename, &hint_xdpi, &hint_ydpi);
2520 if (hint_xdpi != 0) {
2521 res = hint_xdpi;
2522 } else {
2523 // if all else fails, take the default 90 dpi
2524 res = PX_PER_IN;
2525 }
2526 }
2527 }
2529 // The width and height of the bitmap in pixels
2530 unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2531 unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2533 // Find out if we have to run an external filter
2534 gchar const *run = NULL;
2535 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2536 if (!filter.empty()) {
2537 // filter command is given;
2538 // see if we have a parameter to pass to it
2539 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2540 if (!param1.empty()) {
2541 if (param1[param1.length() - 1] == '%') {
2542 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2543 gchar p1[256];
2544 g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1.data(), NULL) * MAX(width, height) / 100));
2545 // the first param is always the image filename, the second is param1
2546 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, p1);
2547 } else {
2548 // otherwise pass the param1 unchanged
2549 run = g_strdup_printf ("%s \"%s\" %s", filter.data(), filepath, param1.data());
2550 }
2551 } else {
2552 // run without extra parameter
2553 run = g_strdup_printf ("%s \"%s\"", filter.data(), filepath);
2554 }
2555 }
2557 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2558 Geom::Matrix eek (sp_item_i2d_affine (SP_ITEM(parent_object)));
2559 Geom::Matrix t;
2561 double shift_x = bbox.x0;
2562 double shift_y = bbox.y1;
2563 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2564 shift_x = round (shift_x);
2565 shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2566 }
2567 t = Geom::Scale(1, -1) * Geom::Translate (shift_x, shift_y) * eek.inverse();
2569 // Do the export
2570 sp_export_png_file(document, filepath,
2571 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2572 width, height, res, res,
2573 (guint32) 0xffffff00,
2574 NULL, NULL,
2575 true, /*bool force_overwrite,*/
2576 items);
2578 g_slist_free (items);
2580 // Run filter, if any
2581 if (run) {
2582 g_print ("Running external filter: %s\n", run);
2583 int retval;
2584 retval = system (run);
2585 }
2587 // Import the image back
2588 GdkPixbuf *pb = gdk_pixbuf_new_from_file (filepath, NULL);
2589 if (pb) {
2590 // Create the repr for the image
2591 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2592 repr->setAttribute("xlink:href", filename);
2593 repr->setAttribute("sodipodi:absref", filepath);
2594 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2595 sp_repr_set_svg_double(repr, "width", width);
2596 sp_repr_set_svg_double(repr, "height", height);
2597 } else {
2598 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2599 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2600 }
2602 // Write transform
2603 gchar *c=sp_svg_transform_write(t);
2604 repr->setAttribute("transform", c);
2605 g_free(c);
2607 // add the new repr to the parent
2608 parent->appendChild(repr);
2610 // move to the saved position
2611 repr->setPosition(pos > 0 ? pos + 1 : 1);
2613 // Set selection to the new image
2614 selection->clear();
2615 selection->add(repr);
2617 // Clean up
2618 Inkscape::GC::release(repr);
2619 gdk_pixbuf_unref (pb);
2621 // Complete undoable transaction
2622 sp_document_done (document, SP_VERB_SELECTION_CREATE_BITMAP,
2623 _("Create bitmap"));
2624 }
2626 desktop->clearWaitingCursor();
2628 g_free (filename);
2629 g_free (filepath);
2630 }
2632 /**
2633 * \brief Creates a mask or clipPath from selection
2634 * Two different modes:
2635 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2636 * and is applied to current layer
2637 * otherwise, topmost object is used as mask for other objects
2638 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2639 *
2640 */
2641 void
2642 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2643 {
2644 if (desktop == NULL)
2645 return;
2647 SPDocument *doc = sp_desktop_document(desktop);
2648 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2650 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2652 // check if something is selected
2653 bool is_empty = selection->isEmpty();
2654 if ( apply_to_layer && is_empty) {
2655 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2656 return;
2657 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2658 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2659 return;
2660 }
2662 // FIXME: temporary patch to prevent crash!
2663 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2664 bool clone_with_original = selection_contains_both_clone_and_original (selection);
2665 if (clone_with_original) {
2666 return; // in this version, you cannot clip/mask an object with its own clone
2667 }
2668 // /END FIXME
2670 sp_document_ensure_up_to_date(doc);
2672 GSList *items = g_slist_copy((GSList *) selection->itemList());
2674 items = g_slist_sort (items, (GCompareFunc) sp_object_compare_position);
2676 // create a list of duplicates
2677 GSList *mask_items = NULL;
2678 GSList *apply_to_items = NULL;
2679 GSList *items_to_delete = NULL;
2680 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2681 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2682 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2684 if (apply_to_layer) {
2685 // all selected items are used for mask, which is applied to a layer
2686 apply_to_items = g_slist_prepend (apply_to_items, desktop->currentLayer());
2688 for (GSList *i = items; i != NULL; i = i->next) {
2689 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2690 mask_items = g_slist_prepend (mask_items, dup);
2692 if (remove_original) {
2693 SPObject *item = SP_OBJECT (i->data);
2694 items_to_delete = g_slist_prepend (items_to_delete, item);
2695 }
2696 }
2697 } else if (!topmost) {
2698 // topmost item is used as a mask, which is applied to other items in a selection
2699 GSList *i = items;
2700 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2701 mask_items = g_slist_prepend (mask_items, dup);
2703 if (remove_original) {
2704 SPObject *item = SP_OBJECT (i->data);
2705 items_to_delete = g_slist_prepend (items_to_delete, item);
2706 }
2708 for (i = i->next; i != NULL; i = i->next) {
2709 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2710 }
2711 } else {
2712 GSList *i = NULL;
2713 for (i = items; NULL != i->next; i = i->next) {
2714 apply_to_items = g_slist_prepend (apply_to_items, i->data);
2715 }
2717 Inkscape::XML::Node *dup = (SP_OBJECT_REPR (i->data))->duplicate(xml_doc);
2718 mask_items = g_slist_prepend (mask_items, dup);
2720 if (remove_original) {
2721 SPObject *item = SP_OBJECT (i->data);
2722 items_to_delete = g_slist_prepend (items_to_delete, item);
2723 }
2724 }
2726 g_slist_free (items);
2727 items = NULL;
2729 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2730 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2731 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2732 // inverted object transform should be applied to a mask object,
2733 // as mask is calculated in user space (after applying transform)
2734 NR::Matrix maskTransform (item->transform.inverse());
2736 GSList *mask_items_dup = NULL;
2737 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2738 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2739 mask_items_dup = g_slist_prepend (mask_items_dup, dup);
2740 }
2742 gchar const *mask_id = NULL;
2743 if (apply_clip_path) {
2744 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2745 } else {
2746 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2747 }
2749 g_slist_free (mask_items_dup);
2750 mask_items_dup = NULL;
2752 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2753 }
2755 g_slist_free (mask_items);
2756 g_slist_free (apply_to_items);
2758 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2759 SPObject *item = SP_OBJECT (i->data);
2760 item->deleteObject (false);
2761 }
2762 g_slist_free (items_to_delete);
2764 if (apply_clip_path)
2765 sp_document_done (doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2766 else
2767 sp_document_done (doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2768 }
2770 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2771 if (desktop == NULL)
2772 return;
2774 SPDocument *doc = sp_desktop_document(desktop);
2775 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2776 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2778 // check if something is selected
2779 if (selection->isEmpty()) {
2780 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2781 return;
2782 }
2784 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2785 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2786 sp_document_ensure_up_to_date(doc);
2788 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2789 std::map<SPObject*,SPItem*> referenced_objects;
2790 // SPObject* refers to a group containing the clipped path or mask itself,
2791 // whereas SPItem* refers to the item being clipped or masked
2792 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2793 if (remove_original) {
2794 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2795 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2796 Inkscape::URIReference *uri_ref = NULL;
2798 if (apply_clip_path) {
2799 uri_ref = item->clip_ref;
2800 } else {
2801 uri_ref = item->mask_ref;
2802 }
2804 // collect distinct mask object (and associate with item to apply transform)
2805 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2806 referenced_objects[uri_ref->getObject()] = item;
2807 }
2808 }
2810 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2811 }
2813 // restore mask objects into a document
2814 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2815 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2816 GSList *items_to_move = NULL;
2817 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2818 // Collect all clipped paths and masks within a single group
2819 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2820 items_to_move = g_slist_prepend (items_to_move, copy);
2821 }
2823 if (!obj->isReferenced()) {
2824 // delete from defs if no other object references this mask
2825 obj->deleteObject(false);
2826 }
2828 // remember parent and position of the item to which the clippath/mask was applied
2829 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
2830 gint pos = SP_OBJECT_REPR((*it).second)->position();
2832 // Iterate through all clipped paths / masks
2833 for (GSList *i = items_to_move; NULL != i; i = i->next) {
2834 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
2836 // insert into parent, restore pos
2837 parent->appendChild(repr);
2838 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
2840 SPItem *mask_item = (SPItem *) sp_desktop_document (desktop)->getObjectByRepr(repr);
2841 selection->add(repr);
2843 // transform mask, so it is moved the same spot where mask was applied
2844 NR::Matrix transform (mask_item->transform);
2845 transform *= (*it).second->transform;
2846 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
2847 }
2849 g_slist_free (items_to_move);
2850 }
2852 if (apply_clip_path)
2853 sp_document_done (doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
2854 else
2855 sp_document_done (doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
2856 }
2858 /**
2859 * Returns true if an undoable change should be recorded.
2860 */
2861 bool
2862 fit_canvas_to_selection(SPDesktop *desktop)
2863 {
2864 g_return_val_if_fail(desktop != NULL, false);
2865 SPDocument *doc = sp_desktop_document(desktop);
2867 g_return_val_if_fail(doc != NULL, false);
2868 g_return_val_if_fail(desktop->selection != NULL, false);
2870 if (desktop->selection->isEmpty()) {
2871 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
2872 return false;
2873 }
2874 boost::optional<Geom::Rect> const bbox(desktop->selection->bounds());
2875 if (bbox && !bbox->isEmpty()) {
2876 doc->fitToRect(*bbox);
2877 return true;
2878 } else {
2879 return false;
2880 }
2881 }
2883 /**
2884 * Fit canvas to the bounding box of the selection, as an undoable action.
2885 */
2886 void
2887 verb_fit_canvas_to_selection(SPDesktop *const desktop)
2888 {
2889 if (fit_canvas_to_selection(desktop)) {
2890 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
2891 _("Fit Page to Selection"));
2892 }
2893 }
2895 bool
2896 fit_canvas_to_drawing(SPDocument *doc)
2897 {
2898 g_return_val_if_fail(doc != NULL, false);
2900 sp_document_ensure_up_to_date(doc);
2901 SPItem const *const root = SP_ITEM(doc->root);
2902 boost::optional<Geom::Rect> const bbox(root->getBounds(sp_item_i2r_affine(root)));
2903 if (bbox && !bbox->isEmpty()) {
2904 doc->fitToRect(*bbox);
2905 return true;
2906 } else {
2907 return false;
2908 }
2909 }
2911 void
2912 verb_fit_canvas_to_drawing(SPDesktop *desktop)
2913 {
2914 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
2915 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
2916 _("Fit Page to Drawing"));
2917 }
2918 }
2920 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
2921 g_return_if_fail(desktop != NULL);
2922 SPDocument *doc = sp_desktop_document(desktop);
2924 g_return_if_fail(doc != NULL);
2925 g_return_if_fail(desktop->selection != NULL);
2927 bool const changed = ( desktop->selection->isEmpty()
2928 ? fit_canvas_to_drawing(doc)
2929 : fit_canvas_to_selection(desktop) );
2930 if (changed) {
2931 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
2932 _("Fit Page to Selection or Drawing"));
2933 }
2934 };
2936 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
2937 // don't operate on layers
2938 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
2939 f(SP_ITEM(root), desktop);
2940 }
2941 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
2942 //don't recurse into locked layers
2943 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
2944 itemtree_map(f, iter, desktop);
2945 }
2946 }
2947 }
2949 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
2950 if (item->isLocked()) {
2951 item->setLocked(FALSE);
2952 }
2953 }
2955 static void unhide(SPItem *item, SPDesktop *desktop) {
2956 if (desktop->itemIsHidden(item)) {
2957 item->setExplicitlyHidden(FALSE);
2958 }
2959 }
2961 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
2962 if (!dt) return;
2964 SPObject *root;
2965 if (layer_only) {
2966 root = dt->currentLayer();
2967 } else {
2968 root = dt->currentRoot();
2969 }
2971 itemtree_map(f, root, dt);
2972 }
2974 void unlock_all(SPDesktop *dt) {
2975 process_all(&unlock, dt, true);
2976 }
2978 void unlock_all_in_all_layers(SPDesktop *dt) {
2979 process_all(&unlock, dt, false);
2980 }
2982 void unhide_all(SPDesktop *dt) {
2983 process_all(&unhide, dt, true);
2984 }
2986 void unhide_all_in_all_layers(SPDesktop *dt) {
2987 process_all(&unhide, dt, false);
2988 }
2991 /*
2992 Local Variables:
2993 mode:c++
2994 c-file-style:"stroustrup"
2995 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
2996 indent-tabs-mode:nil
2997 fill-column:99
2998 End:
2999 */
3000 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :