1 /** @file
2 * @brief Miscellanous operations on selected items
3 */
4 /* Authors:
5 * Lauris Kaplinski <lauris@kaplinski.com>
6 * Frank Felfe <innerspace@iname.com>
7 * MenTaLguY <mental@rydia.net>
8 * bulia byak <buliabyak@users.sf.net>
9 * Andrius R. <knutux@gmail.com>
10 * Jon A. Cruz <jon@joncruz.org>
11 * Martin Sucha <martin.sucha-inkscape@jts-sro.sk>
12 * Abhishek Sharma
13 *
14 * Copyright (C) 1999-2010 authors
15 * Copyright (C) 2001-2002 Ximian, Inc.
16 *
17 * Released under GNU GPL, read the file 'COPYING' for more information
18 */
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
24 #include "selection-chemistry.h"
26 // TOOD fixme: This should be moved into preference repr
27 SPCycleType SP_CYCLING = SP_CYCLE_FOCUS;
30 #include <gtkmm/clipboard.h>
32 #include "svg/svg.h"
33 #include "desktop.h"
34 #include "desktop-style.h"
35 #include "dir-util.h"
36 #include "selection.h"
37 #include "tools-switch.h"
38 #include "desktop-handles.h"
39 #include "message-stack.h"
40 #include "sp-item-transform.h"
41 #include "marker.h"
42 #include "sp-use.h"
43 #include "sp-textpath.h"
44 #include "sp-tspan.h"
45 #include "sp-tref.h"
46 #include "sp-flowtext.h"
47 #include "sp-flowregion.h"
48 #include "sp-image.h"
49 #include "text-editing.h"
50 #include "text-context.h"
51 #include "connector-context.h"
52 #include "sp-path.h"
53 #include "sp-conn-end.h"
54 #include "dropper-context.h"
55 #include <glibmm/i18n.h>
56 #include "libnr/nr-matrix-rotate-ops.h"
57 #include "libnr/nr-matrix-translate-ops.h"
58 #include "libnr/nr-scale-ops.h"
59 #include <libnr/nr-matrix-ops.h>
60 #include <2geom/transforms.h>
61 #include "xml/repr.h"
62 #include "xml/rebase-hrefs.h"
63 #include "style.h"
64 #include "document-private.h"
65 #include "sp-gradient.h"
66 #include "sp-gradient-reference.h"
67 #include "sp-linear-gradient-fns.h"
68 #include "sp-pattern.h"
69 #include "sp-radial-gradient-fns.h"
70 #include "gradient-context.h"
71 #include "sp-namedview.h"
72 #include "preferences.h"
73 #include "sp-offset.h"
74 #include "sp-clippath.h"
75 #include "sp-mask.h"
76 #include "file.h"
77 #include "helper/png-write.h"
78 #include "layer-fns.h"
79 #include "context-fns.h"
80 #include <map>
81 #include <cstring>
82 #include <string>
83 #include "helper/units.h"
84 #include "sp-item.h"
85 #include "box3d.h"
86 #include "persp3d.h"
87 #include "unit-constants.h"
88 #include "xml/simple-document.h"
89 #include "sp-filter-reference.h"
90 #include "gradient-drag.h"
91 #include "uri-references.h"
92 #include "libnr/nr-convert2geom.h"
93 #include "display/curve.h"
94 #include "display/canvas-bpath.h"
95 #include "inkscape-private.h"
96 #include "path-chemistry.h"
97 #include "ui/tool/control-point-selection.h"
98 #include "ui/tool/multi-path-manipulator.h"
100 #include "enums.h"
101 #include "sp-item-group.h"
103 // For clippath editing
104 #include "tools-switch.h"
105 #include "ui/tool/node-tool.h"
107 #include "ui/clipboard.h"
109 using Inkscape::DocumentUndo;
110 using Geom::X;
111 using Geom::Y;
113 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
114 because the layer manipulation code uses them. It should be rewritten specifically
115 for that purpose. */
119 namespace Inkscape {
121 void SelectionHelper::selectAll(SPDesktop *dt)
122 {
123 if (tools_isactive(dt, TOOLS_NODES)) {
124 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
125 if (!nt->_multipath->empty()) {
126 nt->_multipath->selectSubpaths();
127 return;
128 }
129 }
130 sp_edit_select_all(dt);
131 }
133 void SelectionHelper::selectAllInAll(SPDesktop *dt)
134 {
135 if (tools_isactive(dt, TOOLS_NODES)) {
136 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
137 nt->_selected_nodes->selectAll();
138 } else {
139 sp_edit_select_all_in_all_layers(dt);
140 }
141 }
143 void SelectionHelper::selectNone(SPDesktop *dt)
144 {
145 if (tools_isactive(dt, TOOLS_NODES)) {
146 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
147 nt->_selected_nodes->clear();
148 } else {
149 sp_desktop_selection(dt)->clear();
150 }
151 }
153 void SelectionHelper::invert(SPDesktop *dt)
154 {
155 if (tools_isactive(dt, TOOLS_NODES)) {
156 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
157 nt->_multipath->invertSelectionInSubpaths();
158 } else {
159 sp_edit_invert(dt);
160 }
161 }
163 void SelectionHelper::invertAllInAll(SPDesktop *dt)
164 {
165 if (tools_isactive(dt, TOOLS_NODES)) {
166 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
167 nt->_selected_nodes->invertSelection();
168 } else {
169 sp_edit_invert_in_all_layers(dt);
170 }
171 }
173 void SelectionHelper::reverse(SPDesktop *dt)
174 {
175 // TODO make this a virtual method of event context!
176 if (tools_isactive(dt, TOOLS_NODES)) {
177 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
178 nt->_multipath->reverseSubpaths();
179 } else {
180 sp_selected_path_reverse(dt);
181 }
182 }
184 void SelectionHelper::selectNext(SPDesktop *dt)
185 {
186 SPEventContext *ec = dt->event_context;
187 if (tools_isactive(dt, TOOLS_NODES)) {
188 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
189 nt->_multipath->shiftSelection(1);
190 } else if (tools_isactive(dt, TOOLS_GRADIENT)
191 && ec->_grdrag->isNonEmpty()) {
192 sp_gradient_context_select_next(ec);
193 } else {
194 sp_selection_item_next(dt);
195 }
196 }
198 void SelectionHelper::selectPrev(SPDesktop *dt)
199 {
200 SPEventContext *ec = dt->event_context;
201 if (tools_isactive(dt, TOOLS_NODES)) {
202 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
203 nt->_multipath->shiftSelection(-1);
204 } else if (tools_isactive(dt, TOOLS_GRADIENT)
205 && ec->_grdrag->isNonEmpty()) {
206 sp_gradient_context_select_prev(ec);
207 } else {
208 sp_selection_item_prev(dt);
209 }
210 }
212 } // namespace Inkscape
215 /**
216 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
217 * then prepends the copy to 'clip'.
218 */
219 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
220 {
221 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
223 // copy complete inherited style
224 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
225 sp_repr_css_set(copy, css, "style");
226 sp_repr_css_attr_unref(css);
228 // write the complete accumulated transform passed to us
229 // (we're dealing with unattached repr, so we write to its attr
230 // instead of using sp_item_set_transform)
231 gchar *affinestr=sp_svg_transform_write(full_t);
232 copy->setAttribute("transform", affinestr);
233 g_free(affinestr);
235 *clip = g_slist_prepend(*clip, copy);
236 }
238 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
239 {
240 // Sort items:
241 GSList *sorted_items = g_slist_copy((GSList *) items);
242 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
244 // Copy item reprs:
245 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
246 sp_selection_copy_one(SP_OBJECT_REPR(i->data), SP_ITEM(i->data)->i2doc_affine(), clip, xml_doc);
247 }
249 *clip = g_slist_reverse(*clip);
250 g_slist_free((GSList *) sorted_items);
251 }
253 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
254 {
255 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
257 GSList *copied = NULL;
258 // add objects to document
259 for (GSList *l = *clip; l != NULL; l = l->next) {
260 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
261 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
263 // premultiply the item transform by the accumulated parent transform in the paste layer
264 Geom::Matrix local(SP_ITEM(parent)->i2doc_affine());
265 if (!local.isIdentity()) {
266 gchar const *t_str = copy->attribute("transform");
267 Geom::Matrix item_t(Geom::identity());
268 if (t_str)
269 sp_svg_transform_read(t_str, &item_t);
270 item_t *= local.inverse();
271 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
272 gchar *affinestr=sp_svg_transform_write(item_t);
273 copy->setAttribute("transform", affinestr);
274 g_free(affinestr);
275 }
277 parent->appendChildRepr(copy);
278 copied = g_slist_prepend(copied, copy);
279 Inkscape::GC::release(copy);
280 }
281 return copied;
282 }
284 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
285 {
286 for (GSList const *i = items ; i ; i = i->next ) {
287 sp_object_ref((SPObject *)i->data, NULL);
288 }
289 for (GSList const *i = items; i != NULL; i = i->next) {
290 SPItem *item = reinterpret_cast<SPItem *>(i->data);
291 item->deleteObject(propagate, propagate_descendants);
292 sp_object_unref(item, NULL);
293 }
294 }
297 void sp_selection_delete(SPDesktop *desktop)
298 {
299 if (desktop == NULL) {
300 return;
301 }
303 if (tools_isactive(desktop, TOOLS_TEXT))
304 if (sp_text_delete_selection(desktop->event_context)) {
305 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
306 _("Delete text"));
307 return;
308 }
310 Inkscape::Selection *selection = sp_desktop_selection(desktop);
312 // check if something is selected
313 if (selection->isEmpty()) {
314 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
315 return;
316 }
318 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
319 selection->clear();
320 sp_selection_delete_impl(selected);
321 g_slist_free((GSList *) selected);
323 /* a tool may have set up private information in it's selection context
324 * that depends on desktop items. I think the only sane way to deal with
325 * this currently is to reset the current tool, which will reset it's
326 * associated selection context. For example: deleting an object
327 * while moving it around the canvas.
328 */
329 tools_switch( desktop, tools_active( desktop ) );
331 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
332 _("Delete"));
333 }
335 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
336 {
337 if (obj) {
338 ids.push_back(obj->getId());
340 if (SP_IS_GROUP(obj)) {
341 for (SPObject *child = obj->firstChild() ; child; child = child->getNext() ) {
342 add_ids_recursive(ids, child);
343 }
344 }
345 }
346 }
348 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
349 {
350 if (desktop == NULL) {
351 return;
352 }
354 SPDocument *doc = desktop->doc();
355 Inkscape::XML::Document* xml_doc = doc->getReprDoc();
356 Inkscape::Selection *selection = sp_desktop_selection(desktop);
358 // check if something is selected
359 if (selection->isEmpty()) {
360 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
361 return;
362 }
364 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
366 selection->clear();
368 // sorting items from different parents sorts each parent's subset without possibly mixing
369 // them, just what we need
370 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
372 GSList *newsel = NULL;
374 std::vector<const gchar *> old_ids;
375 std::vector<const gchar *> new_ids;
376 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
377 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
379 while (reprs) {
380 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
381 Inkscape::XML::Node *parent = old_repr->parent();
382 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
384 parent->appendChild(copy);
386 if (relink_clones) {
387 SPObject *old_obj = doc->getObjectByRepr(old_repr);
388 SPObject *new_obj = doc->getObjectByRepr(copy);
389 add_ids_recursive(old_ids, old_obj);
390 add_ids_recursive(new_ids, new_obj);
391 }
393 newsel = g_slist_prepend(newsel, copy);
394 reprs = g_slist_remove(reprs, reprs->data);
395 Inkscape::GC::release(copy);
396 }
398 if (relink_clones) {
400 g_assert(old_ids.size() == new_ids.size());
402 for (unsigned int i = 0; i < old_ids.size(); i++) {
403 const gchar *id = old_ids[i];
404 SPObject *old_clone = doc->getObjectById(id);
405 if (SP_IS_USE(old_clone)) {
406 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
407 if (!orig) // orphaned
408 continue;
409 for (unsigned int j = 0; j < old_ids.size(); j++) {
410 if (!strcmp(orig->getId(), old_ids[j])) {
411 // we have both orig and clone in selection, relink
412 // std::cout << id << " old, its ori: " << orig->getId() << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
413 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
414 SPObject *new_clone = doc->getObjectById(new_ids[i]);
415 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
416 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
417 g_free(newref);
418 }
419 }
420 } else if (SP_IS_OFFSET(old_clone)) {
421 for (guint j = 0; j < old_ids.size(); j++) {
422 gchar *source_href = SP_OFFSET(old_clone)->sourceHref;
423 if (source_href && source_href[0]=='#' && !strcmp(source_href+1, old_ids[j])) {
424 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
425 doc->getObjectById(new_ids[i])->getRepr()->setAttribute("xlink:href", newref);
426 g_free(newref);
427 }
428 }
429 }
430 }
431 }
434 if ( !suppressDone ) {
435 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
436 _("Duplicate"));
437 }
439 selection->setReprList(newsel);
441 g_slist_free(newsel);
442 }
444 void sp_edit_clear_all(SPDesktop *dt)
445 {
446 if (!dt)
447 return;
449 SPDocument *doc = sp_desktop_document(dt);
450 sp_desktop_selection(dt)->clear();
452 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
453 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
455 while (items) {
456 reinterpret_cast<SPObject*>(items->data)->deleteObject();
457 items = g_slist_remove(items, items->data);
458 }
460 DocumentUndo::done(doc, SP_VERB_EDIT_CLEAR_ALL,
461 _("Delete all"));
462 }
464 GSList *get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
465 {
466 for ( SPObject *child = from->firstChild() ; child; child = child->getNext() ) {
467 if (SP_IS_ITEM(child) &&
468 !desktop->isLayer(SP_ITEM(child)) &&
469 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
470 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
471 (!exclude || !g_slist_find((GSList *) exclude, child))
472 )
473 {
474 list = g_slist_prepend(list, SP_ITEM(child));
475 }
477 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
478 list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
479 }
480 }
482 return list;
483 }
485 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
486 {
487 if (!dt)
488 return;
490 Inkscape::Selection *selection = sp_desktop_selection(dt);
492 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
494 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
495 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
496 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
497 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
499 GSList *items = NULL;
501 GSList const *exclude = NULL;
502 if (invert) {
503 exclude = selection->itemList();
504 }
506 if (force_all_layers)
507 inlayer = PREFS_SELECTION_ALL;
509 switch (inlayer) {
510 case PREFS_SELECTION_LAYER: {
511 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
512 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
513 return;
515 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
517 for (GSList *i = all_items; i; i = i->next) {
518 SPItem *item = SP_ITEM(i->data);
520 if (item && (!onlysensitive || !item->isLocked())) {
521 if (!onlyvisible || !dt->itemIsHidden(item)) {
522 if (!dt->isLayer(item)) {
523 if (!invert || !g_slist_find((GSList *) exclude, item)) {
524 items = g_slist_prepend(items, item); // leave it in the list
525 }
526 }
527 }
528 }
529 }
531 g_slist_free(all_items);
532 break;
533 }
534 case PREFS_SELECTION_LAYER_RECURSIVE: {
535 items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
536 break;
537 }
538 default: {
539 items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
540 break;
541 }
542 }
544 selection->setList(items);
546 if (items) {
547 g_slist_free(items);
548 }
549 }
551 void sp_edit_select_all(SPDesktop *desktop)
552 {
553 sp_edit_select_all_full(desktop, false, false);
554 }
556 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
557 {
558 sp_edit_select_all_full(desktop, true, false);
559 }
561 void sp_edit_invert(SPDesktop *desktop)
562 {
563 sp_edit_select_all_full(desktop, false, true);
564 }
566 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
567 {
568 sp_edit_select_all_full(desktop, true, true);
569 }
571 void sp_selection_group_impl(GSList *p, Inkscape::XML::Node *group, Inkscape::XML::Document *xml_doc, SPDocument *doc) {
573 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
575 // Remember the position and parent of the topmost object.
576 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
577 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
579 while (p) {
580 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
582 if (current->parent() == topmost_parent) {
583 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
584 sp_repr_unparent(current);
585 group->appendChild(spnew);
586 Inkscape::GC::release(spnew);
587 topmost --; // only reduce count for those items deleted from topmost_parent
588 } else { // move it to topmost_parent first
589 GSList *temp_clip = NULL;
591 // At this point, current may already have no item, due to its being a clone whose original is already moved away
592 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
593 gchar const *t_str = current->attribute("transform");
594 Geom::Matrix item_t(Geom::identity());
595 if (t_str)
596 sp_svg_transform_read(t_str, &item_t);
597 item_t *= SP_ITEM(doc->getObjectByRepr(current->parent()))->i2doc_affine();
598 // FIXME: when moving both clone and original from a transformed group (either by
599 // grouping into another parent, or by cut/paste) the transform from the original's
600 // parent becomes embedded into original itself, and this affects its clones. Fix
601 // this by remembering the transform diffs we write to each item into an array and
602 // then, if this is clone, looking up its original in that array and pre-multiplying
603 // it by the inverse of that original's transform diff.
605 sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
606 sp_repr_unparent(current);
608 // paste into topmost_parent (temporarily)
609 GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
610 if (temp_clip) g_slist_free(temp_clip);
611 if (copied) { // if success,
612 // take pasted object (now in topmost_parent)
613 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
614 // make a copy
615 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
616 // remove pasted
617 sp_repr_unparent(in_topmost);
618 // put its copy into group
619 group->appendChild(spnew);
620 Inkscape::GC::release(spnew);
621 g_slist_free(copied);
622 }
623 }
624 p = g_slist_remove(p, current);
625 }
627 // Add the new group to the topmost members' parent
628 topmost_parent->appendChild(group);
630 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
631 group->setPosition(topmost + 1);
632 }
634 void sp_selection_group(SPDesktop *desktop)
635 {
636 if (desktop == NULL) {
637 return;
638 }
640 SPDocument *doc = sp_desktop_document(desktop);
641 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
643 Inkscape::Selection *selection = sp_desktop_selection(desktop);
645 // Check if something is selected.
646 if (selection->isEmpty()) {
647 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
648 return;
649 }
651 GSList const *l = (GSList *) selection->reprList();
653 GSList *p = g_slist_copy((GSList *) l);
655 selection->clear();
657 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
659 sp_selection_group_impl(p, group, xml_doc, doc);
661 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
662 _("Group"));
664 selection->set(group);
665 Inkscape::GC::release(group);
666 }
668 void sp_selection_ungroup(SPDesktop *desktop)
669 {
670 if (desktop == NULL)
671 return;
673 Inkscape::Selection *selection = sp_desktop_selection(desktop);
675 if (selection->isEmpty()) {
676 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
677 return;
678 }
680 GSList *items = g_slist_copy((GSList *) selection->itemList());
681 selection->clear();
683 // Get a copy of current selection.
684 GSList *new_select = NULL;
685 bool ungrouped = false;
686 for (GSList *i = items;
687 i != NULL;
688 i = i->next)
689 {
690 SPItem *group = (SPItem *) i->data;
692 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
693 if (!SP_IS_OBJECT(group)) {
694 continue;
695 }
697 /* We do not allow ungrouping <svg> etc. (lauris) */
698 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
699 // keep the non-group item in the new selection
700 new_select = g_slist_append(new_select, group);
701 continue;
702 }
704 GSList *children = NULL;
705 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
706 sp_item_group_ungroup(SP_GROUP(group), &children, false);
707 ungrouped = true;
708 // Add ungrouped items to the new selection.
709 new_select = g_slist_concat(new_select, children);
710 }
712 if (new_select) { // Set new selection.
713 selection->addList(new_select);
714 g_slist_free(new_select);
715 }
716 if (!ungrouped) {
717 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
718 }
720 g_slist_free(items);
722 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
723 _("Ungroup"));
724 }
726 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
727 GSList *
728 sp_degroup_list(GSList *items)
729 {
730 GSList *out = NULL;
731 bool has_groups = false;
732 for (GSList *item = items; item; item = item->next) {
733 if (!SP_IS_GROUP(item->data)) {
734 out = g_slist_prepend(out, item->data);
735 } else {
736 has_groups = true;
737 GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
738 for (GSList *member = members; member; member = member->next) {
739 out = g_slist_prepend(out, member->data);
740 }
741 g_slist_free(members);
742 }
743 }
744 out = g_slist_reverse(out);
745 g_slist_free(items);
747 if (has_groups) { // recurse if we unwrapped a group - it may have contained others
748 out = sp_degroup_list(out);
749 }
751 return out;
752 }
755 /** If items in the list have a common parent, return it, otherwise return NULL */
756 static SPGroup *
757 sp_item_list_common_parent_group(GSList const *items)
758 {
759 if (!items) {
760 return NULL;
761 }
762 SPObject *parent = SP_OBJECT_PARENT(items->data);
763 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
764 if (!SP_IS_GROUP(parent)) {
765 return NULL;
766 }
767 for (items = items->next; items; items = items->next) {
768 if (SP_OBJECT_PARENT(items->data) != parent) {
769 return NULL;
770 }
771 }
773 return SP_GROUP(parent);
774 }
776 /** Finds out the minimum common bbox of the selected items. */
777 static Geom::OptRect
778 enclose_items(GSList const *items)
779 {
780 g_assert(items != NULL);
782 Geom::OptRect r;
783 for (GSList const *i = items; i; i = i->next) {
784 r = Geom::unify(r, ((SPItem *) i->data)->getBboxDesktop());
785 }
786 return r;
787 }
789 // TODO determine if this is intentionally different from SPObject::getPrev()
790 SPObject *prev_sibling(SPObject *child)
791 {
792 SPObject *prev = 0;
793 if ( child && SP_IS_GROUP(child->parent) ) {
794 prev = child->getPrev();
795 }
796 return prev;
797 }
799 void
800 sp_selection_raise(SPDesktop *desktop)
801 {
802 if (!desktop)
803 return;
805 Inkscape::Selection *selection = sp_desktop_selection(desktop);
807 GSList const *items = (GSList *) selection->itemList();
808 if (!items) {
809 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
810 return;
811 }
813 SPGroup const *group = sp_item_list_common_parent_group(items);
814 if (!group) {
815 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
816 return;
817 }
819 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
821 /* Construct reverse-ordered list of selected children. */
822 GSList *rev = g_slist_copy((GSList *) items);
823 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
825 // Determine the common bbox of the selected items.
826 Geom::OptRect selected = enclose_items(items);
828 // Iterate over all objects in the selection (starting from top).
829 if (selected) {
830 while (rev) {
831 SPObject *child = reinterpret_cast<SPObject*>(rev->data);
832 // for each selected object, find the next sibling
833 for (SPObject *newref = child->next; newref; newref = newref->next) {
834 // if the sibling is an item AND overlaps our selection,
835 if (SP_IS_ITEM(newref)) {
836 Geom::OptRect newref_bbox = SP_ITEM(newref)->getBboxDesktop();
837 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
838 // AND if it's not one of our selected objects,
839 if (!g_slist_find((GSList *) items, newref)) {
840 // move the selected object after that sibling
841 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
842 }
843 break;
844 }
845 }
846 }
847 rev = g_slist_remove(rev, child);
848 }
849 } else {
850 g_slist_free(rev);
851 }
853 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
854 //TRANSLATORS: "Raise" means "to raise an object" in the undo history
855 C_("Undo action", "Raise"));
856 }
858 void sp_selection_raise_to_top(SPDesktop *desktop)
859 {
860 if (desktop == NULL)
861 return;
863 SPDocument *document = sp_desktop_document(desktop);
864 Inkscape::Selection *selection = sp_desktop_selection(desktop);
866 if (selection->isEmpty()) {
867 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
868 return;
869 }
871 GSList const *items = (GSList *) selection->itemList();
873 SPGroup const *group = sp_item_list_common_parent_group(items);
874 if (!group) {
875 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
876 return;
877 }
879 GSList *rl = g_slist_copy((GSList *) selection->reprList());
880 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
882 for (GSList *l = rl; l != NULL; l = l->next) {
883 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
884 repr->setPosition(-1);
885 }
887 g_slist_free(rl);
889 DocumentUndo::done(document, SP_VERB_SELECTION_TO_FRONT,
890 _("Raise to top"));
891 }
893 void
894 sp_selection_lower(SPDesktop *desktop)
895 {
896 if (desktop == NULL)
897 return;
899 Inkscape::Selection *selection = sp_desktop_selection(desktop);
901 GSList const *items = (GSList *) selection->itemList();
902 if (!items) {
903 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
904 return;
905 }
907 SPGroup const *group = sp_item_list_common_parent_group(items);
908 if (!group) {
909 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
910 return;
911 }
913 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
915 // Determine the common bbox of the selected items.
916 Geom::OptRect selected = enclose_items(items);
918 /* Construct direct-ordered list of selected children. */
919 GSList *rev = g_slist_copy((GSList *) items);
920 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
921 rev = g_slist_reverse(rev);
923 // Iterate over all objects in the selection (starting from top).
924 if (selected) {
925 while (rev) {
926 SPObject *child = reinterpret_cast<SPObject*>(rev->data);
927 // for each selected object, find the prev sibling
928 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
929 // if the sibling is an item AND overlaps our selection,
930 if (SP_IS_ITEM(newref)) {
931 Geom::OptRect ref_bbox = SP_ITEM(newref)->getBboxDesktop();
932 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
933 // AND if it's not one of our selected objects,
934 if (!g_slist_find((GSList *) items, newref)) {
935 // move the selected object before that sibling
936 SPObject *put_after = prev_sibling(newref);
937 if (put_after)
938 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
939 else
940 SP_OBJECT_REPR(child)->setPosition(0);
941 }
942 break;
943 }
944 }
945 }
946 rev = g_slist_remove(rev, child);
947 }
948 } else {
949 g_slist_free(rev);
950 }
952 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
953 _("Lower"));
954 }
956 void sp_selection_lower_to_bottom(SPDesktop *desktop)
957 {
958 if (desktop == NULL)
959 return;
961 SPDocument *document = sp_desktop_document(desktop);
962 Inkscape::Selection *selection = sp_desktop_selection(desktop);
964 if (selection->isEmpty()) {
965 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
966 return;
967 }
969 GSList const *items = (GSList *) selection->itemList();
971 SPGroup const *group = sp_item_list_common_parent_group(items);
972 if (!group) {
973 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
974 return;
975 }
977 GSList *rl;
978 rl = g_slist_copy((GSList *) selection->reprList());
979 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
980 rl = g_slist_reverse(rl);
982 for (GSList *l = rl; l != NULL; l = l->next) {
983 gint minpos;
984 SPObject *pp, *pc;
985 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
986 pp = document->getObjectByRepr(sp_repr_parent(repr));
987 minpos = 0;
988 g_assert(SP_IS_GROUP(pp));
989 pc = pp->firstChild();
990 while (!SP_IS_ITEM(pc)) {
991 minpos += 1;
992 pc = pc->next;
993 }
994 repr->setPosition(minpos);
995 }
997 g_slist_free(rl);
999 DocumentUndo::done(document, SP_VERB_SELECTION_TO_BACK,
1000 _("Lower to bottom"));
1001 }
1003 void
1004 sp_undo(SPDesktop *desktop, SPDocument *)
1005 {
1006 if (!DocumentUndo::undo(sp_desktop_document(desktop))) {
1007 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
1008 }
1009 }
1011 void
1012 sp_redo(SPDesktop *desktop, SPDocument *)
1013 {
1014 if (!DocumentUndo::redo(sp_desktop_document(desktop))) {
1015 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
1016 }
1017 }
1019 void sp_selection_cut(SPDesktop *desktop)
1020 {
1021 sp_selection_copy(desktop);
1022 sp_selection_delete(desktop);
1023 }
1025 /**
1026 * \pre item != NULL
1027 */
1028 SPCSSAttr *
1029 take_style_from_item(SPItem *item)
1030 {
1031 // write the complete cascaded style, context-free
1032 SPCSSAttr *css = sp_css_attr_from_object(item, SP_STYLE_FLAG_ALWAYS);
1033 if (css == NULL)
1034 return NULL;
1036 if ((SP_IS_GROUP(item) && item->children) ||
1037 (SP_IS_TEXT(item) && item->children && item->children->next == NULL)) {
1038 // if this is a text with exactly one tspan child, merge the style of that tspan as well
1039 // If this is a group, merge the style of its topmost (last) child with style
1040 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = last_element->getPrev()) {
1041 if ( last_element->style ) {
1042 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1043 if (temp) {
1044 sp_repr_css_merge(css, temp);
1045 sp_repr_css_attr_unref(temp);
1046 }
1047 break;
1048 }
1049 }
1050 }
1051 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1052 // do not copy text properties from non-text objects, it's confusing
1053 css = sp_css_attr_unset_text(css);
1054 }
1056 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1057 double ex = to_2geom(item->i2doc_affine()).descrim();
1058 if (ex != 1.0) {
1059 css = sp_css_attr_scale(css, ex);
1060 }
1062 return css;
1063 }
1066 void sp_selection_copy(SPDesktop *desktop)
1067 {
1068 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1069 cm->copy(desktop);
1070 }
1072 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1073 {
1074 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1075 if (cm->paste(desktop, in_place)) {
1076 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1077 }
1078 }
1080 void sp_selection_paste_style(SPDesktop *desktop)
1081 {
1082 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1083 if (cm->pasteStyle(desktop)) {
1084 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1085 }
1086 }
1089 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1090 {
1091 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1092 if (cm->pastePathEffect(desktop)) {
1093 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1094 _("Paste live path effect"));
1095 }
1096 }
1099 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1100 {
1101 if ( item && SP_IS_LPE_ITEM(item) &&
1102 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1103 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1104 }
1105 }
1107 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1108 {
1109 if (desktop == NULL) return;
1111 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1113 // check if something is selected
1114 if (selection->isEmpty()) {
1115 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1116 return;
1117 }
1119 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1120 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1122 sp_selection_remove_livepatheffect_impl(item);
1124 }
1126 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1127 _("Remove live path effect"));
1128 }
1130 void sp_selection_remove_filter(SPDesktop *desktop)
1131 {
1132 if (desktop == NULL) return;
1134 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1136 // check if something is selected
1137 if (selection->isEmpty()) {
1138 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1139 return;
1140 }
1142 SPCSSAttr *css = sp_repr_css_attr_new();
1143 sp_repr_css_unset_property(css, "filter");
1144 sp_desktop_set_style(desktop, css);
1145 sp_repr_css_attr_unref(css);
1147 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1148 _("Remove filter"));
1149 }
1152 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1153 {
1154 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1155 if (cm->pasteSize(desktop, false, apply_x, apply_y)) {
1156 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1157 _("Paste size"));
1158 }
1159 }
1161 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1162 {
1163 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1164 if (cm->pasteSize(desktop, true, apply_x, apply_y)) {
1165 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1166 _("Paste size separately"));
1167 }
1168 }
1170 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1171 {
1172 Inkscape::Selection *selection = sp_desktop_selection(dt);
1174 // check if something is selected
1175 if (selection->isEmpty()) {
1176 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1177 return;
1178 }
1180 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1182 bool no_more = false; // Set to true, if no more layers above
1183 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1184 if (next) {
1185 GSList *temp_clip = NULL;
1186 sp_selection_copy_impl(items, &temp_clip, dt->doc()->getReprDoc());
1187 sp_selection_delete_impl(items, false, false);
1188 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1189 GSList *copied;
1190 if (next) {
1191 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1192 } else {
1193 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1194 no_more = true;
1195 }
1196 selection->setReprList((GSList const *) copied);
1197 g_slist_free(copied);
1198 if (temp_clip) g_slist_free(temp_clip);
1199 if (next) dt->setCurrentLayer(next);
1200 if ( !suppressDone ) {
1201 DocumentUndo::done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1202 _("Raise to next layer"));
1203 }
1204 } else {
1205 no_more = true;
1206 }
1208 if (no_more) {
1209 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1210 }
1212 g_slist_free((GSList *) items);
1213 }
1215 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1216 {
1217 Inkscape::Selection *selection = sp_desktop_selection(dt);
1219 // check if something is selected
1220 if (selection->isEmpty()) {
1221 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1222 return;
1223 }
1225 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1227 bool no_more = false; // Set to true, if no more layers below
1228 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1229 if (next) {
1230 GSList *temp_clip = NULL;
1231 sp_selection_copy_impl(items, &temp_clip, dt->doc()->getReprDoc()); // we're in the same doc, so no need to copy defs
1232 sp_selection_delete_impl(items, false, false);
1233 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1234 GSList *copied;
1235 if (next) {
1236 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1237 } else {
1238 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1239 no_more = true;
1240 }
1241 selection->setReprList((GSList const *) copied);
1242 g_slist_free(copied);
1243 if (temp_clip) g_slist_free(temp_clip);
1244 if (next) dt->setCurrentLayer(next);
1245 if ( !suppressDone ) {
1246 DocumentUndo::done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1247 _("Lower to previous layer"));
1248 }
1249 } else {
1250 no_more = true;
1251 }
1253 if (no_more) {
1254 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1255 }
1257 g_slist_free((GSList *) items);
1258 }
1260 bool
1261 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1262 {
1263 bool contains_original = false;
1265 bool is_use = SP_IS_USE(item);
1266 SPItem *item_use = item;
1267 SPItem *item_use_first = item;
1268 while (is_use && item_use && !contains_original)
1269 {
1270 item_use = sp_use_get_original(SP_USE(item_use));
1271 contains_original |= selection->includes(item_use);
1272 if (item_use == item_use_first)
1273 break;
1274 is_use = SP_IS_USE(item_use);
1275 }
1277 // If it's a tref, check whether the object containing the character
1278 // data is part of the selection
1279 if (!contains_original && SP_IS_TREF(item)) {
1280 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1281 }
1283 return contains_original;
1284 }
1287 bool
1288 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1289 {
1290 bool clone_with_original = false;
1291 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1292 SPItem *item = SP_ITEM(l->data);
1293 clone_with_original |= selection_contains_original(item, selection);
1294 if (clone_with_original)
1295 break;
1296 }
1297 return clone_with_original;
1298 }
1300 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1301 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1302 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1303 that case, items are already in the new position, but the repr is in the old, and this function
1304 then simply updates the repr from item->transform.
1305 */
1306 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1307 {
1308 if (selection->isEmpty())
1309 return;
1311 // For each perspective with a box in selection, check whether all boxes are selected and
1312 // unlink all non-selected boxes.
1313 Persp3D *persp;
1314 Persp3D *transf_persp;
1315 std::list<Persp3D *> plist = selection->perspList();
1316 for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1317 persp = (Persp3D *) (*i);
1319 if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1320 std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1322 // create a new perspective as a copy of the current one and link the selected boxes to it
1323 transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1325 for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1326 box3d_switch_perspectives(*b, persp, transf_persp);
1327 } else {
1328 transf_persp = persp;
1329 }
1331 persp3d_apply_affine_transformation(transf_persp, affine);
1332 }
1334 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1335 SPItem *item = SP_ITEM(l->data);
1337 Geom::Point old_center(0,0);
1338 if (set_i2d && item->isCenterSet())
1339 old_center = item->getCenter();
1341 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1342 At the time of writing, this is the only place to re-enable. */
1343 sp_item_update_cns(*item, selection->desktop());
1344 #endif
1346 // we're moving both a clone and its original or any ancestor in clone chain?
1347 bool transform_clone_with_original = selection_contains_original(item, selection);
1348 // ...both a text-on-path and its path?
1349 bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item(SP_TEXTPATH(item->firstChild())) ));
1350 // ...both a flowtext and its frame?
1351 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)
1352 // ...both an offset and its source?
1353 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1355 // If we're moving a connector, we want to detach it
1356 // from shapes that aren't part of the selection, but
1357 // leave it attached if they are
1358 if (cc_item_is_connector(item)) {
1359 SPItem *attItem[2];
1360 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1362 for (int n = 0; n < 2; ++n) {
1363 if (!selection->includes(attItem[n])) {
1364 sp_conn_end_detach(item, n);
1365 }
1366 }
1367 }
1369 // "clones are unmoved when original is moved" preference
1370 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1371 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1372 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1373 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1375 /* If this is a clone and it's selected along with its original, do not move it;
1376 * it will feel the transform of its original and respond to it itself.
1377 * Without this, a clone is doubly transformed, very unintuitive.
1378 *
1379 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1380 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1381 * Same for linked offset if we are also moving its source: do not move it. */
1382 if (transform_textpath_with_path || transform_offset_with_source) {
1383 // Restore item->transform field from the repr, in case it was changed by seltrans.
1384 SP_OBJECT(item)->readAttr( "transform" );
1385 } else if (transform_flowtext_with_frame) {
1386 // apply the inverse of the region's transform to the <use> so that the flow remains
1387 // the same (even though the output itself gets transformed)
1388 for ( SPObject *region = item->firstChild() ; region ; region = region->getNext() ) {
1389 if (SP_IS_FLOWREGION(region) || SP_IS_FLOWREGIONEXCLUDE(region)) {
1390 for ( SPObject *use = region->firstChild() ; use ; use = use->getNext() ) {
1391 if ( SP_IS_USE(use) ) {
1392 SP_USE(use)->doWriteTransform(use->getRepr(), item->transform.inverse(), NULL, compensate);
1393 }
1394 }
1395 }
1396 }
1397 } else if (transform_clone_with_original) {
1398 // We are transforming a clone along with its original. The below matrix juggling is
1399 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1400 // transform and its move compensation are both cancelled out.
1402 // restore item->transform field from the repr, in case it was changed by seltrans
1403 SP_OBJECT(item)->readAttr( "transform" );
1405 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1406 Geom::Matrix parent2dt = SP_ITEM(SP_OBJECT_PARENT(item))->i2d_affine();
1407 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1408 Geom::Matrix t_inv = t.inverse();
1409 Geom::Matrix result = t_inv * item->transform * t;
1411 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1412 // we need to cancel out the move compensation, too
1414 // find out the clone move, same as in sp_use_move_compensate
1415 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1416 Geom::Matrix clone_move = parent.inverse() * t * parent;
1418 if (prefs_parallel) {
1419 Geom::Matrix move = result * clone_move * t_inv;
1420 item->doWriteTransform(SP_OBJECT_REPR(item), move, &move, compensate);
1422 } else if (prefs_unmoved) {
1423 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1424 // clone_move = Geom::identity();
1425 Geom::Matrix move = result * clone_move;
1426 item->doWriteTransform(SP_OBJECT_REPR(item), move, &t, compensate);
1427 }
1429 } else {
1430 // just apply the result
1431 item->doWriteTransform(SP_OBJECT_REPR(item), result, &t, compensate);
1432 }
1434 } else {
1435 if (set_i2d) {
1436 item->set_i2d_affine(item->i2d_affine() * (Geom::Matrix)affine);
1437 }
1438 item->doWriteTransform(SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1439 }
1441 // if we're moving the actual object, not just updating the repr, we can transform the
1442 // center by the same matrix (only necessary for non-translations)
1443 if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1444 item->setCenter(old_center * affine);
1445 item->updateRepr();
1446 }
1447 }
1448 }
1450 void sp_selection_remove_transform(SPDesktop *desktop)
1451 {
1452 if (desktop == NULL)
1453 return;
1455 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1457 GSList const *l = (GSList *) selection->reprList();
1458 while (l != NULL) {
1459 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1460 l = l->next;
1461 }
1463 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1464 _("Remove transform"));
1465 }
1467 void
1468 sp_selection_scale_absolute(Inkscape::Selection *selection,
1469 double const x0, double const x1,
1470 double const y0, double const y1)
1471 {
1472 if (selection->isEmpty())
1473 return;
1475 Geom::OptRect const bbox(selection->bounds());
1476 if ( !bbox ) {
1477 return;
1478 }
1480 Geom::Translate const p2o(-bbox->min());
1482 Geom::Scale const newSize(x1 - x0,
1483 y1 - y0);
1484 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1485 Geom::Translate const o2n(x0, y0);
1486 Geom::Matrix const final( p2o * scale * o2n );
1488 sp_selection_apply_affine(selection, final);
1489 }
1492 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1493 {
1494 if (selection->isEmpty())
1495 return;
1497 Geom::OptRect const bbox(selection->bounds());
1499 if ( !bbox ) {
1500 return;
1501 }
1503 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1504 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1505 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1506 {
1507 return;
1508 }
1510 Geom::Translate const n2d(-align);
1511 Geom::Translate const d2n(align);
1512 Geom::Matrix const final( n2d * scale * d2n );
1513 sp_selection_apply_affine(selection, final);
1514 }
1516 void
1517 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1518 {
1519 Geom::Translate const d2n(center);
1520 Geom::Translate const n2d(-center);
1521 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1522 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1523 sp_selection_apply_affine(selection, final);
1524 }
1526 void
1527 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1528 {
1529 Geom::Translate const d2n(align);
1530 Geom::Translate const n2d(-align);
1531 Geom::Matrix const skew(1, dy,
1532 dx, 1,
1533 0, 0);
1534 Geom::Matrix const final( n2d * skew * d2n );
1535 sp_selection_apply_affine(selection, final);
1536 }
1538 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1539 {
1540 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1541 }
1543 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1544 {
1545 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1546 }
1548 /**
1549 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1550 */
1551 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1552 {
1553 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1555 if (selection->isEmpty())
1556 return;
1558 GSList const *l = selection->itemList();
1559 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1560 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1561 SPItem *item = SP_ITEM(l2->data);
1562 sp_item_rotate_rel(item, rot_90);
1563 }
1565 DocumentUndo::done(sp_desktop_document(desktop),
1566 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1567 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1568 }
1570 void
1571 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1572 {
1573 if (selection->isEmpty())
1574 return;
1576 boost::optional<Geom::Point> center = selection->center();
1577 if (!center) {
1578 return;
1579 }
1581 sp_selection_rotate_relative(selection, *center, angle_degrees);
1583 DocumentUndo::maybeDone(sp_desktop_document(selection->desktop()),
1584 ( ( angle_degrees > 0 )
1585 ? "selector:rotate:ccw"
1586 : "selector:rotate:cw" ),
1587 SP_VERB_CONTEXT_SELECT,
1588 _("Rotate"));
1589 }
1591 // helper function:
1592 static
1593 Geom::Point
1594 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1595 Geom::Point m = r.midpoint();
1596 unsigned i = 0;
1597 if (p[X] < m[X]) {
1598 i = 1;
1599 }
1600 if (p[Y] < m[Y]) {
1601 i = 3 - i;
1602 }
1603 return r.corner(i);
1604 }
1606 /**
1607 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1608 */
1609 void
1610 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1611 {
1612 if (selection->isEmpty())
1613 return;
1615 Geom::OptRect const bbox(selection->bounds());
1616 boost::optional<Geom::Point> center = selection->center();
1618 if ( !bbox || !center ) {
1619 return;
1620 }
1622 gdouble const zoom = selection->desktop()->current_zoom();
1623 gdouble const zmove = angle / zoom;
1624 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1626 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1628 sp_selection_rotate_relative(selection, *center, zangle);
1630 DocumentUndo::maybeDone(sp_desktop_document(selection->desktop()),
1631 ( (angle > 0)
1632 ? "selector:rotate:ccw"
1633 : "selector:rotate:cw" ),
1634 SP_VERB_CONTEXT_SELECT,
1635 _("Rotate by pixels"));
1636 }
1638 void
1639 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1640 {
1641 if (selection->isEmpty())
1642 return;
1644 Geom::OptRect const bbox(selection->bounds());
1645 if (!bbox) {
1646 return;
1647 }
1649 Geom::Point const center(bbox->midpoint());
1651 // you can't scale "do nizhe pola" (below zero)
1652 double const max_len = bbox->maxExtent();
1653 if ( max_len + grow <= 1e-3 ) {
1654 return;
1655 }
1657 double const times = 1.0 + grow / max_len;
1658 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1660 DocumentUndo::maybeDone(sp_desktop_document(selection->desktop()),
1661 ( (grow > 0)
1662 ? "selector:scale:larger"
1663 : "selector:scale:smaller" ),
1664 SP_VERB_CONTEXT_SELECT,
1665 _("Scale"));
1666 }
1668 void
1669 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1670 {
1671 sp_selection_scale(selection,
1672 grow_pixels / selection->desktop()->current_zoom());
1673 }
1675 void
1676 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1677 {
1678 if (selection->isEmpty())
1679 return;
1681 Geom::OptRect sel_bbox = selection->bounds();
1683 if (!sel_bbox) {
1684 return;
1685 }
1687 Geom::Point const center(sel_bbox->midpoint());
1688 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1689 DocumentUndo::done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1690 _("Scale by whole factor"));
1691 }
1693 void
1694 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1695 {
1696 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1697 if (selection->isEmpty()) {
1698 return;
1699 }
1701 sp_selection_move_relative(selection, dx, dy);
1703 if (dx == 0) {
1704 DocumentUndo::maybeDone(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1705 _("Move vertically"));
1706 } else if (dy == 0) {
1707 DocumentUndo::maybeDone(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1708 _("Move horizontally"));
1709 } else {
1710 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1711 _("Move"));
1712 }
1713 }
1715 void
1716 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1717 {
1718 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1719 if (selection->isEmpty()) {
1720 return;
1721 }
1723 // same as sp_selection_move but divide deltas by zoom factor
1724 gdouble const zoom = desktop->current_zoom();
1725 gdouble const zdx = dx / zoom;
1726 gdouble const zdy = dy / zoom;
1727 sp_selection_move_relative(selection, zdx, zdy);
1729 if (dx == 0) {
1730 DocumentUndo::maybeDone(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1731 _("Move vertically by pixels"));
1732 } else if (dy == 0) {
1733 DocumentUndo::maybeDone(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1734 _("Move horizontally by pixels"));
1735 } else {
1736 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1737 _("Move"));
1738 }
1739 }
1741 namespace {
1743 template <typename D>
1744 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1745 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1747 template <typename D>
1748 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1749 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1751 struct Forward {
1752 typedef SPObject *Iterator;
1754 static Iterator children(SPObject *o) { return o->firstChild(); }
1755 static Iterator siblings_after(SPObject *o) { return o->getNext(); }
1756 static void dispose(Iterator /*i*/) {}
1758 static SPObject *object(Iterator i) { return i; }
1759 static Iterator next(Iterator i) { return i->getNext(); }
1760 };
1762 struct ListReverse {
1763 typedef GSList *Iterator;
1765 static Iterator children(SPObject *o) {
1766 return make_list(o->firstChild(), NULL);
1767 }
1768 static Iterator siblings_after(SPObject *o) {
1769 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1770 }
1771 static void dispose(Iterator i) {
1772 g_slist_free(i);
1773 }
1775 static SPObject *object(Iterator i) {
1776 return reinterpret_cast<SPObject *>(i->data);
1777 }
1778 static Iterator next(Iterator i) { return i->next; }
1780 private:
1781 static GSList *make_list(SPObject *object, SPObject *limit) {
1782 GSList *list = NULL;
1783 while ( object != limit ) {
1784 if (!object) { // TODO check if this happens in practice
1785 g_warning("Unexpected list overrun");
1786 break;
1787 }
1788 list = g_slist_prepend(list, object);
1789 object = object->getNext();
1790 }
1791 return list;
1792 }
1793 };
1795 }
1797 void
1798 sp_selection_item_next(SPDesktop *desktop)
1799 {
1800 g_return_if_fail(desktop != NULL);
1801 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1803 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1804 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1805 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1806 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1808 SPObject *root;
1809 if (PREFS_SELECTION_ALL != inlayer) {
1810 root = selection->activeContext();
1811 } else {
1812 root = desktop->currentRoot();
1813 }
1815 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1817 if (item) {
1818 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1819 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1820 scroll_to_show_item(desktop, item);
1821 }
1822 }
1823 }
1825 void
1826 sp_selection_item_prev(SPDesktop *desktop)
1827 {
1828 SPDocument *document = sp_desktop_document(desktop);
1829 g_return_if_fail(document != NULL);
1830 g_return_if_fail(desktop != NULL);
1831 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1833 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1834 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1835 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1836 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1838 SPObject *root;
1839 if (PREFS_SELECTION_ALL != inlayer) {
1840 root = selection->activeContext();
1841 } else {
1842 root = desktop->currentRoot();
1843 }
1845 SPItem *item=next_item_from_list<ListReverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1847 if (item) {
1848 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1849 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1850 scroll_to_show_item(desktop, item);
1851 }
1852 }
1853 }
1855 void sp_selection_next_patheffect_param(SPDesktop * dt)
1856 {
1857 if (!dt) return;
1859 Inkscape::Selection *selection = sp_desktop_selection(dt);
1860 if ( selection && !selection->isEmpty() ) {
1861 SPItem *item = selection->singleItem();
1862 if ( item && SP_IS_SHAPE(item)) {
1863 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1864 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1865 } else {
1866 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1867 }
1868 }
1869 }
1870 }
1872 /*bool has_path_recursive(SPObject *obj)
1873 {
1874 if (!obj) return false;
1875 if (SP_IS_PATH(obj)) {
1876 return true;
1877 }
1878 if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1879 for (SPObject *c = obj->children; c; c = c->next) {
1880 if (has_path_recursive(c)) return true;
1881 }
1882 }
1883 return false;
1884 }*/
1886 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1887 {
1888 return;
1889 /*if (!dt) return;
1890 using namespace Inkscape::UI;
1892 Inkscape::Selection *selection = sp_desktop_selection(dt);
1893 if (!selection || selection->isEmpty()) return;
1895 GSList const *items = selection->itemList();
1896 bool has_path = false;
1897 for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1898 SPItem *item = SP_ITEM(i->data);
1899 SPObject *search = clip
1900 ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1901 : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1902 has_path |= has_path_recursive(search);
1903 if (has_path) break;
1904 }
1905 if (has_path) {
1906 if (!tools_isactive(dt, TOOLS_NODES)) {
1907 tools_switch(dt, TOOLS_NODES);
1908 }
1909 ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1910 clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1911 } else if (clip) {
1912 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1913 _("The selection has no applied clip path."));
1914 } else {
1915 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1916 _("The selection has no applied mask."));
1917 }*/
1918 }
1921 namespace {
1923 template <typename D>
1924 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1925 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1926 {
1927 SPObject *current=root;
1928 while (items) {
1929 SPItem *item=SP_ITEM(items->data);
1930 if ( root->isAncestorOf(item) &&
1931 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1932 {
1933 current = item;
1934 break;
1935 }
1936 items = items->next;
1937 }
1939 GSList *path=NULL;
1940 while ( current != root ) {
1941 path = g_slist_prepend(path, current);
1942 current = SP_OBJECT_PARENT(current);
1943 }
1945 SPItem *next;
1946 // first, try from the current object
1947 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1948 g_slist_free(path);
1950 if (!next) { // if we ran out of objects, start over at the root
1951 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1952 }
1954 return next;
1955 }
1957 template <typename D>
1958 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1959 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1960 {
1961 typename D::Iterator children;
1962 typename D::Iterator iter;
1964 SPItem *found=NULL;
1966 if (path) {
1967 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1968 g_assert(SP_OBJECT_PARENT(object) == root);
1969 if (desktop->isLayer(object)) {
1970 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1971 }
1972 iter = children = D::siblings_after(object);
1973 } else {
1974 iter = children = D::children(root);
1975 }
1977 while ( iter && !found ) {
1978 SPObject *object=D::object(iter);
1979 if (desktop->isLayer(object)) {
1980 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1981 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1982 }
1983 } else if ( SP_IS_ITEM(object) &&
1984 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1985 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1986 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1987 !desktop->isLayer(SP_ITEM(object)) )
1988 {
1989 found = SP_ITEM(object);
1990 }
1991 iter = D::next(iter);
1992 }
1994 D::dispose(children);
1996 return found;
1997 }
1999 }
2001 /**
2002 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
2003 * \a item.
2004 */
2005 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
2006 {
2007 Geom::Rect dbox = desktop->get_display_area();
2008 Geom::OptRect sbox = item->getBboxDesktop();
2010 if ( sbox && dbox.contains(*sbox) == false ) {
2011 Geom::Point const s_dt = sbox->midpoint();
2012 Geom::Point const s_w = desktop->d2w(s_dt);
2013 Geom::Point const d_dt = dbox.midpoint();
2014 Geom::Point const d_w = desktop->d2w(d_dt);
2015 Geom::Point const moved_w( d_w - s_w );
2016 gint const dx = (gint) moved_w[X];
2017 gint const dy = (gint) moved_w[Y];
2018 desktop->scroll_world(dx, dy);
2019 }
2020 }
2023 void sp_selection_clone(SPDesktop *desktop)
2024 {
2025 if (desktop == NULL) {
2026 return;
2027 }
2029 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2031 Inkscape::XML::Document *xml_doc = desktop->doc()->getReprDoc();
2033 // check if something is selected
2034 if (selection->isEmpty()) {
2035 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2036 return;
2037 }
2039 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2041 selection->clear();
2043 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2044 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2046 GSList *newsel = NULL;
2048 while (reprs) {
2049 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2050 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2052 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2053 clone->setAttribute("x", "0", false);
2054 clone->setAttribute("y", "0", false);
2055 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2057 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2058 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2060 // add the new clone to the top of the original's parent
2061 parent->appendChild(clone);
2063 newsel = g_slist_prepend(newsel, clone);
2064 reprs = g_slist_remove(reprs, sel_repr);
2065 Inkscape::GC::release(clone);
2066 }
2068 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2069 C_("Action", "Clone"));
2071 selection->setReprList(newsel);
2073 g_slist_free(newsel);
2074 }
2076 void
2077 sp_selection_relink(SPDesktop *desktop)
2078 {
2079 if (!desktop)
2080 return;
2082 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2084 if (selection->isEmpty()) {
2085 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2086 return;
2087 }
2089 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2090 const gchar *newid = cm->getFirstObjectID();
2091 if (!newid) {
2092 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2093 return;
2094 }
2095 gchar *newref = g_strdup_printf("#%s", newid);
2097 // Get a copy of current selection.
2098 bool relinked = false;
2099 for (GSList *items = (GSList *) selection->itemList();
2100 items != NULL;
2101 items = items->next)
2102 {
2103 SPItem *item = (SPItem *) items->data;
2105 if (!SP_IS_USE(item))
2106 continue;
2108 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2109 item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2110 relinked = true;
2111 }
2113 g_free(newref);
2115 if (!relinked) {
2116 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2117 } else {
2118 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2119 _("Relink clone"));
2120 }
2121 }
2124 void
2125 sp_selection_unlink(SPDesktop *desktop)
2126 {
2127 if (!desktop)
2128 return;
2130 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2132 if (selection->isEmpty()) {
2133 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2134 return;
2135 }
2137 // Get a copy of current selection.
2138 GSList *new_select = NULL;
2139 bool unlinked = false;
2140 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2141 items != NULL;
2142 items = items->next)
2143 {
2144 SPItem *item = (SPItem *) items->data;
2146 if (SP_IS_TEXT(item)) {
2147 SPObject *tspan = sp_tref_convert_to_tspan(item);
2149 if (tspan) {
2150 item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2151 }
2153 // Set unlink to true, and fall into the next if which
2154 // will include this text item in the new selection
2155 unlinked = true;
2156 }
2158 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2159 // keep the non-use item in the new selection
2160 new_select = g_slist_prepend(new_select, item);
2161 continue;
2162 }
2164 SPItem *unlink;
2165 if (SP_IS_USE(item)) {
2166 unlink = sp_use_unlink(SP_USE(item));
2167 // Unable to unlink use (external or invalid href?)
2168 if (!unlink) {
2169 new_select = g_slist_prepend(new_select, item);
2170 continue;
2171 }
2172 } else /*if (SP_IS_TREF(use))*/ {
2173 unlink = SP_ITEM(sp_tref_convert_to_tspan(item));
2174 }
2176 unlinked = true;
2177 // Add ungrouped items to the new selection.
2178 new_select = g_slist_prepend(new_select, unlink);
2179 }
2181 if (new_select) { // set new selection
2182 selection->clear();
2183 selection->setList(new_select);
2184 g_slist_free(new_select);
2185 }
2186 if (!unlinked) {
2187 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2188 }
2190 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2191 _("Unlink clone"));
2192 }
2194 void
2195 sp_select_clone_original(SPDesktop *desktop)
2196 {
2197 if (desktop == NULL)
2198 return;
2200 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2202 SPItem *item = selection->singleItem();
2204 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.");
2206 // Check if other than two objects are selected
2207 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2208 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2209 return;
2210 }
2212 SPItem *original = NULL;
2213 if (SP_IS_USE(item)) {
2214 original = sp_use_get_original(SP_USE(item));
2215 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2216 original = sp_offset_get_source(SP_OFFSET(item));
2217 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2218 original = sp_textpath_get_path_item(SP_TEXTPATH(SP_OBJECT(item)->firstChild()));
2219 } else if (SP_IS_FLOWTEXT(item)) {
2220 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2221 } else { // it's an object that we don't know what to do with
2222 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2223 return;
2224 }
2226 if (!original) {
2227 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2228 return;
2229 }
2231 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2232 if (SP_IS_DEFS(o)) {
2233 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2234 return;
2235 }
2236 }
2238 if (original) {
2239 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2240 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2241 if (highlight) {
2242 Geom::OptRect a = item->getBounds(item->i2d_affine());
2243 Geom::OptRect b = original->getBounds(original->i2d_affine());
2244 if ( a && b ) {
2245 // draw a flashing line between the objects
2246 SPCurve *curve = new SPCurve();
2247 curve->moveto(a->midpoint());
2248 curve->lineto(b->midpoint());
2250 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2251 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2252 sp_canvas_item_show(canvasitem);
2253 curve->unref();
2254 desktop->add_temporary_canvasitem(canvasitem, 1000);
2255 }
2256 }
2258 selection->clear();
2259 selection->set(original);
2260 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2261 scroll_to_show_item(desktop, original);
2262 }
2263 }
2264 }
2267 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2268 {
2269 if (desktop == NULL) {
2270 return;
2271 }
2273 SPDocument *doc = sp_desktop_document(desktop);
2274 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
2276 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2278 // check if something is selected
2279 if (selection->isEmpty()) {
2280 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2281 return;
2282 }
2284 doc->ensureUpToDate();
2285 Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2286 boost::optional<Geom::Point> c = selection->center();
2287 if ( !r || !c ) {
2288 return;
2289 }
2291 // calculate the transform to be applied to objects to move them to 0,0
2292 Geom::Point move_p = Geom::Point(0, doc->getHeight()) - *c;
2293 move_p[Geom::Y] = -move_p[Geom::Y];
2294 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2296 GSList *items = g_slist_copy((GSList *) selection->itemList());
2298 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2300 // bottommost object, after sorting
2301 SPObject *parent = SP_OBJECT_PARENT(items->data);
2303 Geom::Matrix parent_transform(SP_ITEM(parent)->i2doc_affine());
2305 // remember the position of the first item
2306 gint pos = SP_OBJECT_REPR(items->data)->position();
2307 (void)pos; // TODO check why this was remembered
2309 // create a list of duplicates
2310 GSList *repr_copies = NULL;
2311 for (GSList *i = items; i != NULL; i = i->next) {
2312 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2313 repr_copies = g_slist_prepend(repr_copies, dup);
2314 }
2316 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2318 if (apply) {
2319 // delete objects so that their clones don't get alerted; this object will be restored shortly
2320 for (GSList *i = items; i != NULL; i = i->next) {
2321 SPObject *item = reinterpret_cast<SPObject*>(i->data);
2322 item->deleteObject(false);
2323 }
2324 }
2326 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2327 // without disturbing clones.
2328 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2329 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2330 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2331 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2333 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2334 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2335 Geom::Point(r->min()[Geom::X],
2336 r->max()[Geom::Y]))))
2337 * parent_transform.inverse() ),
2338 parent_transform * move);
2339 (void)mark_id;
2341 // restore compensation setting
2342 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2345 g_slist_free(items);
2347 DocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2348 _("Objects to marker"));
2349 }
2351 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2352 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2353 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2354 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2355 }
2356 } else {
2357 item->convert_item_to_guides();
2359 if (deleteitem) {
2360 item->deleteObject(true);
2361 }
2362 }
2363 }
2365 void sp_selection_to_guides(SPDesktop *desktop)
2366 {
2367 if (desktop == NULL)
2368 return;
2370 SPDocument *doc = sp_desktop_document(desktop);
2371 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2372 // we need to copy the list because it gets reset when objects are deleted
2373 GSList *items = g_slist_copy((GSList *) selection->itemList());
2375 if (!items) {
2376 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2377 return;
2378 }
2380 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2381 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2382 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2384 for (GSList const *i = items; i != NULL; i = i->next) {
2385 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2386 }
2388 DocumentUndo::done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2389 }
2391 void
2392 sp_selection_tile(SPDesktop *desktop, bool apply)
2393 {
2394 if (desktop == NULL) {
2395 return;
2396 }
2398 SPDocument *doc = sp_desktop_document(desktop);
2399 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
2401 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2403 // check if something is selected
2404 if (selection->isEmpty()) {
2405 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2406 return;
2407 }
2409 doc->ensureUpToDate();
2410 Geom::OptRect r = selection->bounds(SPItem::RENDERING_BBOX);
2411 if ( !r ) {
2412 return;
2413 }
2415 // calculate the transform to be applied to objects to move them to 0,0
2416 Geom::Point move_p = Geom::Point(0, doc->getHeight()) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2417 move_p[Geom::Y] = -move_p[Geom::Y];
2418 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2420 GSList *items = g_slist_copy((GSList *) selection->itemList());
2422 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2424 // bottommost object, after sorting
2425 SPObject *parent = SP_OBJECT_PARENT(items->data);
2427 Geom::Matrix parent_transform(SP_ITEM(parent)->i2doc_affine());
2429 // remember the position of the first item
2430 gint pos = SP_OBJECT_REPR(items->data)->position();
2432 // create a list of duplicates
2433 GSList *repr_copies = NULL;
2434 for (GSList *i = items; i != NULL; i = i->next) {
2435 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2436 repr_copies = g_slist_prepend(repr_copies, dup);
2437 }
2438 // restore the z-order after prepends
2439 repr_copies = g_slist_reverse(repr_copies);
2441 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2443 if (apply) {
2444 // delete objects so that their clones don't get alerted; this object will be restored shortly
2445 for (GSList *i = items; i != NULL; i = i->next) {
2446 SPObject *item = reinterpret_cast<SPObject*>(i->data);
2447 item->deleteObject(false);
2448 }
2449 }
2451 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2452 // without disturbing clones.
2453 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2454 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2455 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2456 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2458 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2459 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2460 r->max()[Geom::Y]))))
2461 * to_2geom(parent_transform.inverse()) ),
2462 parent_transform * move);
2464 // restore compensation setting
2465 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2467 if (apply) {
2468 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2469 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2471 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2472 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2474 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2475 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2476 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2477 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2479 // restore parent and position
2480 SP_OBJECT_REPR(parent)->appendChild(rect);
2481 rect->setPosition(pos > 0 ? pos : 0);
2482 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2484 Inkscape::GC::release(rect);
2486 selection->clear();
2487 selection->set(rectangle);
2488 }
2490 g_slist_free(items);
2492 DocumentUndo::done(doc, SP_VERB_EDIT_TILE,
2493 _("Objects to pattern"));
2494 }
2496 void sp_selection_untile(SPDesktop *desktop)
2497 {
2498 if (desktop == NULL) {
2499 return;
2500 }
2502 SPDocument *doc = sp_desktop_document(desktop);
2503 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
2505 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2507 // check if something is selected
2508 if (selection->isEmpty()) {
2509 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2510 return;
2511 }
2513 GSList *new_select = NULL;
2515 bool did = false;
2517 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2518 items != NULL;
2519 items = items->next) {
2521 SPItem *item = (SPItem *) items->data;
2523 SPStyle *style = item->style;
2525 if (!style || !style->fill.isPaintserver())
2526 continue;
2528 SPPaintServer *server = item->style->getFillPaintServer();
2530 if (!SP_IS_PATTERN(server))
2531 continue;
2533 did = true;
2535 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2537 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2538 pat_transform *= item->transform;
2540 for (SPObject *child = pattern->firstChild() ; child != NULL; child = child->next ) {
2541 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2542 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2544 // FIXME: relink clones to the new canvas objects
2545 // use SPObject::setid when mental finishes it to steal ids of
2547 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2548 doc->ensureUpToDate();
2550 Geom::Matrix transform( i->transform * pat_transform );
2551 i->doWriteTransform(SP_OBJECT_REPR(i), transform);
2553 new_select = g_slist_prepend(new_select, i);
2554 }
2556 SPCSSAttr *css = sp_repr_css_attr_new();
2557 sp_repr_css_set_property(css, "fill", "none");
2558 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2559 }
2561 if (!did) {
2562 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2563 } else {
2564 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2565 _("Pattern to objects"));
2566 selection->setList(new_select);
2567 }
2568 }
2570 void
2571 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2572 {
2573 if (selection->isEmpty()) {
2574 return;
2575 }
2577 GSList const *reprlst = selection->reprList();
2578 bool filename_search = TRUE;
2579 bool xdpi_search = TRUE;
2580 bool ydpi_search = TRUE;
2582 for (; reprlst != NULL &&
2583 filename_search &&
2584 xdpi_search &&
2585 ydpi_search;
2586 reprlst = reprlst->next) {
2587 gchar const *dpi_string;
2588 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2590 if (filename_search) {
2591 *filename = repr->attribute("inkscape:export-filename");
2592 if (*filename != NULL)
2593 filename_search = FALSE;
2594 }
2596 if (xdpi_search) {
2597 dpi_string = NULL;
2598 dpi_string = repr->attribute("inkscape:export-xdpi");
2599 if (dpi_string != NULL) {
2600 *xdpi = atof(dpi_string);
2601 xdpi_search = FALSE;
2602 }
2603 }
2605 if (ydpi_search) {
2606 dpi_string = NULL;
2607 dpi_string = repr->attribute("inkscape:export-ydpi");
2608 if (dpi_string != NULL) {
2609 *ydpi = atof(dpi_string);
2610 ydpi_search = FALSE;
2611 }
2612 }
2613 }
2614 }
2616 void sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2617 {
2618 Inkscape::XML::Node * repr = doc->getReprRoot();
2620 *filename = repr->attribute("inkscape:export-filename");
2622 gchar const *dpi_string = repr->attribute("inkscape:export-xdpi");
2623 if (dpi_string != NULL) {
2624 *xdpi = atof(dpi_string);
2625 }
2627 dpi_string = NULL;
2628 dpi_string = repr->attribute("inkscape:export-ydpi");
2629 if (dpi_string != NULL) {
2630 *ydpi = atof(dpi_string);
2631 }
2632 }
2634 void sp_selection_create_bitmap_copy(SPDesktop *desktop)
2635 {
2636 if (desktop == NULL) {
2637 return;
2638 }
2640 SPDocument *document = sp_desktop_document(desktop);
2641 Inkscape::XML::Document *xml_doc = document->getReprDoc();
2643 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2645 // check if something is selected
2646 if (selection->isEmpty()) {
2647 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2648 return;
2649 }
2651 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2652 // set "busy" cursor
2653 desktop->setWaitingCursor();
2655 // Get the bounding box of the selection
2656 NRRect bbox;
2657 document->ensureUpToDate();
2658 selection->bounds(&bbox);
2659 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2660 desktop->clearWaitingCursor();
2661 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2662 }
2664 // List of the items to show; all others will be hidden
2665 GSList *items = g_slist_copy((GSList *) selection->itemList());
2667 // Sort items so that the topmost comes last
2668 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2670 // Generate a random value from the current time (you may create bitmap from the same object(s)
2671 // multiple times, and this is done so that they don't clash)
2672 GTimeVal cu;
2673 g_get_current_time(&cu);
2674 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2676 // Create the filename.
2677 gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2678 document->getName(),
2679 SP_OBJECT_REPR(items->data)->attribute("id"),
2680 current);
2681 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2682 // digits, and a few other chars, with "_"
2683 g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2685 // Build the complete path by adding document base dir, if set, otherwise home dir
2686 gchar * directory = NULL;
2687 if ( document->getURI() ) {
2688 directory = g_dirname( document->getURI() );
2689 }
2690 if (directory == NULL) {
2691 directory = homedir_path(NULL);
2692 }
2693 gchar *filepath = g_build_filename(directory, basename, NULL);
2695 //g_print("%s\n", filepath);
2697 // Remember parent and z-order of the topmost one
2698 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2699 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2700 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2702 // Calculate resolution
2703 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2704 double res;
2705 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2706 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2707 if (0 < prefs_res) {
2708 // If it's given explicitly in prefs, take it
2709 res = prefs_res;
2710 } else if (0 < prefs_min) {
2711 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2712 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2713 } else {
2714 float hint_xdpi = 0, hint_ydpi = 0;
2715 char const *hint_filename;
2716 // take resolution hint from the selected objects
2717 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2718 if (hint_xdpi != 0) {
2719 res = hint_xdpi;
2720 } else {
2721 // take resolution hint from the document
2722 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2723 if (hint_xdpi != 0) {
2724 res = hint_xdpi;
2725 } else {
2726 // if all else fails, take the default 90 dpi
2727 res = PX_PER_IN;
2728 }
2729 }
2730 }
2732 // The width and height of the bitmap in pixels
2733 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2734 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2736 // Find out if we have to run an external filter
2737 gchar const *run = NULL;
2738 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2739 if (!filter.empty()) {
2740 // filter command is given;
2741 // see if we have a parameter to pass to it
2742 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2743 if (!param1.empty()) {
2744 if (param1[param1.length() - 1] == '%') {
2745 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2746 gchar p1[256];
2747 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2748 // the first param is always the image filename, the second is param1
2749 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2750 } else {
2751 // otherwise pass the param1 unchanged
2752 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2753 }
2754 } else {
2755 // run without extra parameter
2756 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2757 }
2758 }
2760 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2761 Geom::Matrix eek(SP_ITEM(parent_object)->i2d_affine());
2762 Geom::Matrix t;
2764 double shift_x = bbox.x0;
2765 double shift_y = bbox.y1;
2766 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2767 shift_x = round(shift_x);
2768 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2769 }
2770 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2772 // Do the export
2773 sp_export_png_file(document, filepath,
2774 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2775 width, height, res, res,
2776 (guint32) 0xffffff00,
2777 NULL, NULL,
2778 true, /*bool force_overwrite,*/
2779 items);
2781 g_slist_free(items);
2783 // Run filter, if any
2784 if (run) {
2785 g_print("Running external filter: %s\n", run);
2786 int retval;
2787 retval = system(run);
2788 }
2790 // Import the image back
2791 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2792 if (pb) {
2793 // Create the repr for the image
2794 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2795 sp_embed_image(repr, pb, "image/png");
2796 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2797 sp_repr_set_svg_double(repr, "width", width);
2798 sp_repr_set_svg_double(repr, "height", height);
2799 } else {
2800 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2801 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2802 }
2804 // Write transform
2805 gchar *c=sp_svg_transform_write(t);
2806 repr->setAttribute("transform", c);
2807 g_free(c);
2809 // add the new repr to the parent
2810 parent->appendChild(repr);
2812 // move to the saved position
2813 repr->setPosition(pos > 0 ? pos + 1 : 1);
2815 // Set selection to the new image
2816 selection->clear();
2817 selection->add(repr);
2819 // Clean up
2820 Inkscape::GC::release(repr);
2821 gdk_pixbuf_unref(pb);
2823 // Complete undoable transaction
2824 DocumentUndo::done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2825 _("Create bitmap"));
2826 }
2828 desktop->clearWaitingCursor();
2830 g_free(basename);
2831 g_free(filepath);
2832 }
2834 /**
2835 * \brief Creates a mask or clipPath from selection
2836 * Two different modes:
2837 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2838 * and is applied to current layer
2839 * otherwise, topmost object is used as mask for other objects
2840 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2841 *
2842 */
2843 void sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2844 {
2845 if (desktop == NULL) {
2846 return;
2847 }
2849 SPDocument *doc = sp_desktop_document(desktop);
2850 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
2852 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2854 // check if something is selected
2855 bool is_empty = selection->isEmpty();
2856 if ( apply_to_layer && is_empty) {
2857 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2858 return;
2859 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2860 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2861 return;
2862 }
2864 // FIXME: temporary patch to prevent crash!
2865 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2866 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2867 if (clone_with_original) {
2868 return; // in this version, you cannot clip/mask an object with its own clone
2869 }
2870 // /END FIXME
2872 doc->ensureUpToDate();
2874 GSList *items = g_slist_copy((GSList *) selection->itemList());
2876 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2878 // See lp bug #542004
2879 selection->clear();
2881 // create a list of duplicates
2882 GSList *mask_items = NULL;
2883 GSList *apply_to_items = NULL;
2884 GSList *items_to_delete = NULL;
2885 GSList *items_to_select = NULL;
2887 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2888 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2889 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2890 int grouping = prefs->getInt("/options/maskobject/grouping", PREFS_MASKOBJECT_GROUPING_NONE);
2892 if (apply_to_layer) {
2893 // all selected items are used for mask, which is applied to a layer
2894 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2896 for (GSList *i = items; i != NULL; i = i->next) {
2897 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2898 mask_items = g_slist_prepend(mask_items, dup);
2900 SPObject *item = reinterpret_cast<SPObject*>(i->data);
2901 if (remove_original) {
2902 items_to_delete = g_slist_prepend(items_to_delete, item);
2903 }
2904 else {
2905 items_to_select = g_slist_prepend(items_to_select, item);
2906 }
2907 }
2908 } else if (!topmost) {
2909 // topmost item is used as a mask, which is applied to other items in a selection
2910 GSList *i = items;
2911 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2912 mask_items = g_slist_prepend(mask_items, dup);
2914 if (remove_original) {
2915 SPObject *item = reinterpret_cast<SPObject*>(i->data);
2916 items_to_delete = g_slist_prepend(items_to_delete, item);
2917 }
2919 for (i = i->next; i != NULL; i = i->next) {
2920 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2921 items_to_select = g_slist_prepend(items_to_select, i->data);
2922 }
2923 } else {
2924 GSList *i = NULL;
2925 for (i = items; NULL != i->next; i = i->next) {
2926 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2927 items_to_select = g_slist_prepend(items_to_select, i->data);
2928 }
2930 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2931 mask_items = g_slist_prepend(mask_items, dup);
2933 if (remove_original) {
2934 SPObject *item = reinterpret_cast<SPObject*>(i->data);
2935 items_to_delete = g_slist_prepend(items_to_delete, item);
2936 }
2937 }
2939 g_slist_free(items);
2940 items = NULL;
2942 if (apply_to_items && grouping == PREFS_MASKOBJECT_GROUPING_ALL) {
2943 // group all those objects into one group
2944 // and apply mask to that
2945 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
2947 // make a note we should ungroup this when unsetting mask
2948 group->setAttribute("inkscape:groupmode", "maskhelper");
2950 GSList *reprs_to_group = NULL;
2952 for (GSList *i = apply_to_items ; NULL != i ; i = i->next) {
2953 reprs_to_group = g_slist_prepend(reprs_to_group, SP_OBJECT_REPR(i->data));
2954 items_to_select = g_slist_remove(items_to_select, i->data);
2955 }
2956 reprs_to_group = g_slist_reverse(reprs_to_group);
2958 sp_selection_group_impl(reprs_to_group, group, xml_doc, doc);
2960 reprs_to_group = NULL;
2962 // apply clip/mask only to newly created group
2963 g_slist_free(apply_to_items);
2964 apply_to_items = NULL;
2965 apply_to_items = g_slist_prepend(apply_to_items, doc->getObjectByRepr(group));
2967 items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
2969 Inkscape::GC::release(group);
2970 }
2972 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2973 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2974 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2975 // inverted object transform should be applied to a mask object,
2976 // as mask is calculated in user space (after applying transform)
2977 Geom::Matrix maskTransform(item->transform.inverse());
2979 GSList *mask_items_dup = NULL;
2980 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2981 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2982 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2983 }
2985 gchar const *mask_id = NULL;
2986 if (apply_clip_path) {
2987 mask_id = SPClipPath::create(mask_items_dup, doc, &maskTransform);
2988 } else {
2989 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2990 }
2992 g_slist_free(mask_items_dup);
2993 mask_items_dup = NULL;
2995 Inkscape::XML::Node *current = SP_OBJECT_REPR(i->data);
2996 // Node to apply mask to
2997 Inkscape::XML::Node *apply_mask_to = current;
2999 if (grouping == PREFS_MASKOBJECT_GROUPING_SEPARATE) {
3000 // enclose current node in group, and apply crop/mask on that
3001 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
3002 // make a note we should ungroup this when unsetting mask
3003 group->setAttribute("inkscape:groupmode", "maskhelper");
3005 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
3006 gint position = current->position();
3007 items_to_select = g_slist_remove(items_to_select, item);
3008 current->parent()->appendChild(group);
3009 sp_repr_unparent(current);
3010 group->appendChild(spnew);
3011 group->setPosition(position);
3013 // Apply clip/mask to group instead
3014 apply_mask_to = group;
3016 items_to_select = g_slist_prepend(items_to_select, doc->getObjectByRepr(group));
3017 Inkscape::GC::release(spnew);
3018 Inkscape::GC::release(group);
3019 }
3021 apply_mask_to->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
3023 }
3025 g_slist_free(mask_items);
3026 g_slist_free(apply_to_items);
3028 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
3029 SPObject *item = reinterpret_cast<SPObject*>(i->data);
3030 item->deleteObject(false);
3031 items_to_select = g_slist_remove(items_to_select, item);
3032 }
3033 g_slist_free(items_to_delete);
3035 items_to_select = g_slist_reverse(items_to_select);
3037 selection->addList(items_to_select);
3038 g_slist_free(items_to_select);
3040 if (apply_clip_path) {
3041 DocumentUndo::done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
3042 } else {
3043 DocumentUndo::done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
3044 }
3045 }
3047 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
3048 if (desktop == NULL) {
3049 return;
3050 }
3052 SPDocument *doc = sp_desktop_document(desktop);
3053 Inkscape::XML::Document *xml_doc = doc->getReprDoc();
3054 Inkscape::Selection *selection = sp_desktop_selection(desktop);
3056 // check if something is selected
3057 if (selection->isEmpty()) {
3058 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
3059 return;
3060 }
3062 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
3063 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
3064 bool ungroup_masked = prefs->getBool("/options/maskobject/ungrouping", true);
3065 doc->ensureUpToDate();
3067 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
3068 std::map<SPObject*,SPItem*> referenced_objects;
3070 GSList *items = g_slist_copy((GSList *) selection->itemList());
3071 selection->clear();
3073 GSList *items_to_ungroup = NULL;
3074 GSList *items_to_select = g_slist_copy(items);
3075 items_to_select = g_slist_reverse(items_to_select);
3078 // SPObject* refers to a group containing the clipped path or mask itself,
3079 // whereas SPItem* refers to the item being clipped or masked
3080 for (GSList const *i = items; NULL != i; i = i->next) {
3081 if (remove_original) {
3082 // remember referenced mask/clippath, so orphaned masks can be moved back to document
3083 SPItem *item = reinterpret_cast<SPItem *>(i->data);
3084 Inkscape::URIReference *uri_ref = NULL;
3086 if (apply_clip_path) {
3087 uri_ref = item->clip_ref;
3088 } else {
3089 uri_ref = item->mask_ref;
3090 }
3092 // collect distinct mask object (and associate with item to apply transform)
3093 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
3094 referenced_objects[uri_ref->getObject()] = item;
3095 }
3096 }
3098 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
3100 if (ungroup_masked && SP_IS_GROUP(i->data)) {
3101 // if we had previously enclosed masked object in group,
3102 // add it to list so we can ungroup it later
3103 SPGroup *item = SP_GROUP(i->data);
3105 // ungroup only groups we created when setting clip/mask
3106 if (item->layerMode() == SPGroup::MASK_HELPER) {
3107 items_to_ungroup = g_slist_prepend(items_to_ungroup, item);
3108 }
3110 }
3111 }
3112 g_slist_free(items);
3114 // restore mask objects into a document
3115 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
3116 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
3117 GSList *items_to_move = NULL;
3118 for ( SPObject *child = obj->firstChild() ; child; child = child->getNext() ) {
3119 // Collect all clipped paths and masks within a single group
3120 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
3121 items_to_move = g_slist_prepend(items_to_move, copy);
3122 }
3124 if (!obj->isReferenced()) {
3125 // delete from defs if no other object references this mask
3126 obj->deleteObject(false);
3127 }
3129 // remember parent and position of the item to which the clippath/mask was applied
3130 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3131 gint pos = SP_OBJECT_REPR((*it).second)->position();
3133 // Iterate through all clipped paths / masks
3134 for (GSList *i = items_to_move; NULL != i; i = i->next) {
3135 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3137 // insert into parent, restore pos
3138 parent->appendChild(repr);
3139 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3141 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3142 items_to_select = g_slist_prepend(items_to_select, mask_item);
3144 // transform mask, so it is moved the same spot where mask was applied
3145 Geom::Matrix transform(mask_item->transform);
3146 transform *= (*it).second->transform;
3147 mask_item->doWriteTransform(SP_OBJECT_REPR(mask_item), transform);
3148 }
3150 g_slist_free(items_to_move);
3151 }
3153 // ungroup marked groups added when setting mask
3154 for (GSList *i = items_to_ungroup ; NULL != i ; i = i->next) {
3155 items_to_select = g_slist_remove(items_to_select, SP_GROUP(i->data));
3156 GSList *children = NULL;
3157 sp_item_group_ungroup(SP_GROUP(i->data), &children, false);
3158 items_to_select = g_slist_concat(children, items_to_select);
3159 }
3161 g_slist_free(items_to_ungroup);
3163 // rebuild selection
3164 items_to_select = g_slist_reverse(items_to_select);
3165 selection->addList(items_to_select);
3166 g_slist_free(items_to_select);
3168 if (apply_clip_path) {
3169 DocumentUndo::done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3170 } else {
3171 DocumentUndo::done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3172 }
3173 }
3175 /**
3176 * \param with_margins margins defined in the xml under <sodipodi:namedview>
3177 * "fit-margin-..." attributes. See SPDocument::fitToRect.
3178 * \return true if an undoable change should be recorded.
3179 */
3180 bool
3181 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3182 {
3183 g_return_val_if_fail(desktop != NULL, false);
3184 SPDocument *doc = sp_desktop_document(desktop);
3186 g_return_val_if_fail(doc != NULL, false);
3187 g_return_val_if_fail(desktop->selection != NULL, false);
3189 if (desktop->selection->isEmpty()) {
3190 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3191 return false;
3192 }
3193 Geom::OptRect const bbox(desktop->selection->bounds(SPItem::RENDERING_BBOX));
3194 if (bbox) {
3195 doc->fitToRect(*bbox, with_margins);
3196 return true;
3197 } else {
3198 return false;
3199 }
3200 }
3202 /**
3203 * Fit canvas to the bounding box of the selection, as an undoable action.
3204 */
3205 void
3206 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3207 {
3208 if (fit_canvas_to_selection(desktop)) {
3209 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3210 _("Fit Page to Selection"));
3211 }
3212 }
3214 /**
3215 * \param with_margins margins defined in the xml under <sodipodi:namedview>
3216 * "fit-margin-..." attributes. See SPDocument::fitToRect.
3217 */
3218 bool
3219 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3220 {
3221 g_return_val_if_fail(doc != NULL, false);
3223 doc->ensureUpToDate();
3224 SPItem const *const root = SP_ITEM(doc->root);
3225 Geom::OptRect const bbox(root->getBounds(root->i2d_affine()));
3226 if (bbox) {
3227 doc->fitToRect(*bbox, with_margins);
3228 return true;
3229 } else {
3230 return false;
3231 }
3232 }
3234 void
3235 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3236 {
3237 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3238 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3239 _("Fit Page to Drawing"));
3240 }
3241 }
3243 /**
3244 * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3245 * "fit-margin-..." attributes. See SPDocument::fitToRect and
3246 * ui/dialog/page-sizer.
3247 */
3248 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3249 g_return_if_fail(desktop != NULL);
3250 SPDocument *doc = sp_desktop_document(desktop);
3252 g_return_if_fail(doc != NULL);
3253 g_return_if_fail(desktop->selection != NULL);
3255 bool const changed = ( desktop->selection->isEmpty()
3256 ? fit_canvas_to_drawing(doc, true)
3257 : fit_canvas_to_selection(desktop, true) );
3258 if (changed) {
3259 DocumentUndo::done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3260 _("Fit Page to Selection or Drawing"));
3261 }
3262 };
3264 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3265 // don't operate on layers
3266 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3267 f(SP_ITEM(root), desktop);
3268 }
3269 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3270 //don't recurse into locked layers
3271 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3272 itemtree_map(f, iter, desktop);
3273 }
3274 }
3275 }
3277 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3278 if (item->isLocked()) {
3279 item->setLocked(FALSE);
3280 }
3281 }
3283 static void unhide(SPItem *item, SPDesktop *desktop) {
3284 if (desktop->itemIsHidden(item)) {
3285 item->setExplicitlyHidden(FALSE);
3286 }
3287 }
3289 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3290 if (!dt) return;
3292 SPObject *root;
3293 if (layer_only) {
3294 root = dt->currentLayer();
3295 } else {
3296 root = dt->currentRoot();
3297 }
3299 itemtree_map(f, root, dt);
3300 }
3302 void unlock_all(SPDesktop *dt) {
3303 process_all(&unlock, dt, true);
3304 }
3306 void unlock_all_in_all_layers(SPDesktop *dt) {
3307 process_all(&unlock, dt, false);
3308 }
3310 void unhide_all(SPDesktop *dt) {
3311 process_all(&unhide, dt, true);
3312 }
3314 void unhide_all_in_all_layers(SPDesktop *dt) {
3315 process_all(&unhide, dt, false);
3316 }
3319 /*
3320 Local Variables:
3321 mode:c++
3322 c-file-style:"stroustrup"
3323 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3324 indent-tabs-mode:nil
3325 fill-column:99
3326 End:
3327 */
3328 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :