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 *
12 * Copyright (C) 1999-2010 authors
13 * Copyright (C) 2001-2002 Ximian, Inc.
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
22 #include "selection-chemistry.h"
24 // TOOD fixme: This should be moved into preference repr
25 SPCycleType SP_CYCLING = SP_CYCLE_FOCUS;
28 #include <gtkmm/clipboard.h>
30 #include "svg/svg.h"
31 #include "desktop.h"
32 #include "desktop-style.h"
33 #include "dir-util.h"
34 #include "selection.h"
35 #include "tools-switch.h"
36 #include "desktop-handles.h"
37 #include "message-stack.h"
38 #include "sp-item-transform.h"
39 #include "marker.h"
40 #include "sp-use.h"
41 #include "sp-textpath.h"
42 #include "sp-tspan.h"
43 #include "sp-tref.h"
44 #include "sp-flowtext.h"
45 #include "sp-flowregion.h"
46 #include "text-editing.h"
47 #include "text-context.h"
48 #include "connector-context.h"
49 #include "sp-path.h"
50 #include "sp-conn-end.h"
51 #include "dropper-context.h"
52 #include <glibmm/i18n.h>
53 #include "libnr/nr-matrix-rotate-ops.h"
54 #include "libnr/nr-matrix-translate-ops.h"
55 #include "libnr/nr-scale-ops.h"
56 #include <libnr/nr-matrix-ops.h>
57 #include <2geom/transforms.h>
58 #include "xml/repr.h"
59 #include "xml/rebase-hrefs.h"
60 #include "style.h"
61 #include "document-private.h"
62 #include "sp-gradient.h"
63 #include "sp-gradient-reference.h"
64 #include "sp-linear-gradient-fns.h"
65 #include "sp-pattern.h"
66 #include "sp-radial-gradient-fns.h"
67 #include "gradient-context.h"
68 #include "sp-namedview.h"
69 #include "preferences.h"
70 #include "sp-offset.h"
71 #include "sp-clippath.h"
72 #include "sp-mask.h"
73 #include "file.h"
74 #include "helper/png-write.h"
75 #include "layer-fns.h"
76 #include "context-fns.h"
77 #include <map>
78 #include <cstring>
79 #include <string>
80 #include "helper/units.h"
81 #include "sp-item.h"
82 #include "box3d.h"
83 #include "persp3d.h"
84 #include "unit-constants.h"
85 #include "xml/simple-document.h"
86 #include "sp-filter-reference.h"
87 #include "gradient-drag.h"
88 #include "uri-references.h"
89 #include "libnr/nr-convert2geom.h"
90 #include "display/curve.h"
91 #include "display/canvas-bpath.h"
92 #include "inkscape-private.h"
93 #include "path-chemistry.h"
94 #include "ui/tool/control-point-selection.h"
95 #include "ui/tool/multi-path-manipulator.h"
97 // For clippath editing
98 #include "tools-switch.h"
99 #include "ui/tool/node-tool.h"
101 #include "ui/clipboard.h"
103 using Geom::X;
104 using Geom::Y;
106 /* The clipboard handling is in ui/clipboard.cpp now. There are some legacy functions left here,
107 because the layer manipulation code uses them. It should be rewritten specifically
108 for that purpose. */
112 namespace Inkscape {
114 void SelectionHelper::selectAll(SPDesktop *dt)
115 {
116 if (tools_isactive(dt, TOOLS_NODES)) {
117 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
118 nt->_multipath->selectSubpaths();
119 } else {
120 sp_edit_select_all(dt);
121 }
122 }
124 void SelectionHelper::selectAllInAll(SPDesktop *dt)
125 {
126 if (tools_isactive(dt, TOOLS_NODES)) {
127 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
128 nt->_selected_nodes->selectAll();
129 } else {
130 sp_edit_select_all_in_all_layers(dt);
131 }
132 }
134 void SelectionHelper::selectNone(SPDesktop *dt)
135 {
136 if (tools_isactive(dt, TOOLS_NODES)) {
137 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
138 nt->_selected_nodes->clear();
139 } else {
140 sp_desktop_selection(dt)->clear();
141 }
142 }
144 void SelectionHelper::invert(SPDesktop *dt)
145 {
146 if (tools_isactive(dt, TOOLS_NODES)) {
147 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
148 nt->_multipath->invertSelectionInSubpaths();
149 } else {
150 sp_edit_invert(dt);
151 }
152 }
154 void SelectionHelper::invertAllInAll(SPDesktop *dt)
155 {
156 if (tools_isactive(dt, TOOLS_NODES)) {
157 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
158 nt->_selected_nodes->invertSelection();
159 } else {
160 sp_edit_invert_in_all_layers(dt);
161 }
162 }
164 void SelectionHelper::reverse(SPDesktop *dt)
165 {
166 // TODO make this a virtual method of event context!
167 if (tools_isactive(dt, TOOLS_NODES)) {
168 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
169 nt->_multipath->reverseSubpaths();
170 } else {
171 sp_selected_path_reverse(dt);
172 }
173 }
175 void SelectionHelper::selectNext(SPDesktop *dt)
176 {
177 SPEventContext *ec = dt->event_context;
178 if (tools_isactive(dt, TOOLS_NODES)) {
179 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
180 nt->_multipath->shiftSelection(1);
181 } else if (tools_isactive(dt, TOOLS_GRADIENT)
182 && ec->_grdrag->isNonEmpty()) {
183 sp_gradient_context_select_next(ec);
184 } else {
185 sp_selection_item_next(dt);
186 }
187 }
189 void SelectionHelper::selectPrev(SPDesktop *dt)
190 {
191 SPEventContext *ec = dt->event_context;
192 if (tools_isactive(dt, TOOLS_NODES)) {
193 InkNodeTool *nt = static_cast<InkNodeTool*>(dt->event_context);
194 nt->_multipath->shiftSelection(-1);
195 } else if (tools_isactive(dt, TOOLS_GRADIENT)
196 && ec->_grdrag->isNonEmpty()) {
197 sp_gradient_context_select_prev(ec);
198 } else {
199 sp_selection_item_prev(dt);
200 }
201 }
203 } // namespace Inkscape
206 /**
207 * Copies repr and its inherited css style elements, along with the accumulated transform 'full_t',
208 * then prepends the copy to 'clip'.
209 */
210 void sp_selection_copy_one(Inkscape::XML::Node *repr, Geom::Matrix full_t, GSList **clip, Inkscape::XML::Document* xml_doc)
211 {
212 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
214 // copy complete inherited style
215 SPCSSAttr *css = sp_repr_css_attr_inherited(repr, "style");
216 sp_repr_css_set(copy, css, "style");
217 sp_repr_css_attr_unref(css);
219 // write the complete accumulated transform passed to us
220 // (we're dealing with unattached repr, so we write to its attr
221 // instead of using sp_item_set_transform)
222 gchar *affinestr=sp_svg_transform_write(full_t);
223 copy->setAttribute("transform", affinestr);
224 g_free(affinestr);
226 *clip = g_slist_prepend(*clip, copy);
227 }
229 void sp_selection_copy_impl(GSList const *items, GSList **clip, Inkscape::XML::Document* xml_doc)
230 {
231 // Sort items:
232 GSList *sorted_items = g_slist_copy((GSList *) items);
233 sorted_items = g_slist_sort((GSList *) sorted_items, (GCompareFunc) sp_object_compare_position);
235 // Copy item reprs:
236 for (GSList *i = (GSList *) sorted_items; i != NULL; i = i->next) {
237 sp_selection_copy_one(SP_OBJECT_REPR(i->data), sp_item_i2doc_affine(SP_ITEM(i->data)), clip, xml_doc);
238 }
240 *clip = g_slist_reverse(*clip);
241 g_slist_free((GSList *) sorted_items);
242 }
244 GSList *sp_selection_paste_impl(SPDocument *doc, SPObject *parent, GSList **clip)
245 {
246 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
248 GSList *copied = NULL;
249 // add objects to document
250 for (GSList *l = *clip; l != NULL; l = l->next) {
251 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
252 Inkscape::XML::Node *copy = repr->duplicate(xml_doc);
254 // premultiply the item transform by the accumulated parent transform in the paste layer
255 Geom::Matrix local(sp_item_i2doc_affine(SP_ITEM(parent)));
256 if (!local.isIdentity()) {
257 gchar const *t_str = copy->attribute("transform");
258 Geom::Matrix item_t(Geom::identity());
259 if (t_str)
260 sp_svg_transform_read(t_str, &item_t);
261 item_t *= local.inverse();
262 // (we're dealing with unattached repr, so we write to its attr instead of using sp_item_set_transform)
263 gchar *affinestr=sp_svg_transform_write(item_t);
264 copy->setAttribute("transform", affinestr);
265 g_free(affinestr);
266 }
268 parent->appendChildRepr(copy);
269 copied = g_slist_prepend(copied, copy);
270 Inkscape::GC::release(copy);
271 }
272 return copied;
273 }
275 void sp_selection_delete_impl(GSList const *items, bool propagate = true, bool propagate_descendants = true)
276 {
277 for (GSList const *i = items ; i ; i = i->next ) {
278 sp_object_ref((SPObject *)i->data, NULL);
279 }
280 for (GSList const *i = items; i != NULL; i = i->next) {
281 SPItem *item = (SPItem *) i->data;
282 SP_OBJECT(item)->deleteObject(propagate, propagate_descendants);
283 sp_object_unref((SPObject *)item, NULL);
284 }
285 }
288 void sp_selection_delete(SPDesktop *desktop)
289 {
290 if (desktop == NULL) {
291 return;
292 }
294 if (tools_isactive(desktop, TOOLS_TEXT))
295 if (sp_text_delete_selection(desktop->event_context)) {
296 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_TEXT,
297 _("Delete text"));
298 return;
299 }
301 Inkscape::Selection *selection = sp_desktop_selection(desktop);
303 // check if something is selected
304 if (selection->isEmpty()) {
305 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("<b>Nothing</b> was deleted."));
306 return;
307 }
309 GSList const *selected = g_slist_copy(const_cast<GSList *>(selection->itemList()));
310 selection->clear();
311 sp_selection_delete_impl(selected);
312 g_slist_free((GSList *) selected);
314 /* a tool may have set up private information in it's selection context
315 * that depends on desktop items. I think the only sane way to deal with
316 * this currently is to reset the current tool, which will reset it's
317 * associated selection context. For example: deleting an object
318 * while moving it around the canvas.
319 */
320 tools_switch( desktop, tools_active( desktop ) );
322 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DELETE,
323 _("Delete"));
324 }
326 void add_ids_recursive(std::vector<const gchar *> &ids, SPObject *obj)
327 {
328 if (!obj)
329 return;
331 ids.push_back(SP_OBJECT_ID(obj));
333 if (SP_IS_GROUP(obj)) {
334 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
335 add_ids_recursive(ids, child);
336 }
337 }
338 }
340 void sp_selection_duplicate(SPDesktop *desktop, bool suppressDone)
341 {
342 if (desktop == NULL)
343 return;
345 SPDocument *doc = desktop->doc();
346 Inkscape::XML::Document* xml_doc = sp_document_repr_doc(doc);
347 Inkscape::Selection *selection = sp_desktop_selection(desktop);
349 // check if something is selected
350 if (selection->isEmpty()) {
351 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to duplicate."));
352 return;
353 }
355 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
357 selection->clear();
359 // sorting items from different parents sorts each parent's subset without possibly mixing
360 // them, just what we need
361 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
363 GSList *newsel = NULL;
365 std::vector<const gchar *> old_ids;
366 std::vector<const gchar *> new_ids;
367 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
368 bool relink_clones = prefs->getBool("/options/relinkclonesonduplicate/value");
370 while (reprs) {
371 Inkscape::XML::Node *old_repr = (Inkscape::XML::Node *) reprs->data;
372 Inkscape::XML::Node *parent = old_repr->parent();
373 Inkscape::XML::Node *copy = old_repr->duplicate(xml_doc);
375 parent->appendChild(copy);
377 if (relink_clones) {
378 SPObject *old_obj = doc->getObjectByRepr(old_repr);
379 SPObject *new_obj = doc->getObjectByRepr(copy);
380 add_ids_recursive(old_ids, old_obj);
381 add_ids_recursive(new_ids, new_obj);
382 }
384 newsel = g_slist_prepend(newsel, copy);
385 reprs = g_slist_remove(reprs, reprs->data);
386 Inkscape::GC::release(copy);
387 }
389 if (relink_clones) {
391 g_assert(old_ids.size() == new_ids.size());
393 for (unsigned int i = 0; i < old_ids.size(); i++) {
394 const gchar *id = old_ids[i];
395 SPObject *old_clone = doc->getObjectById(id);
396 if (SP_IS_USE(old_clone)) {
397 SPItem *orig = sp_use_get_original(SP_USE(old_clone));
398 if (!orig) // orphaned
399 continue;
400 for (unsigned int j = 0; j < old_ids.size(); j++) {
401 if (!strcmp(SP_OBJECT_ID(orig), old_ids[j])) {
402 // we have both orig and clone in selection, relink
403 // std::cout << id << " old, its ori: " << SP_OBJECT_ID(orig) << "; will relink:" << new_ids[i] << " to " << new_ids[j] << "\n";
404 gchar *newref = g_strdup_printf("#%s", new_ids[j]);
405 SPObject *new_clone = doc->getObjectById(new_ids[i]);
406 SP_OBJECT_REPR(new_clone)->setAttribute("xlink:href", newref);
407 new_clone->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
408 g_free(newref);
409 }
410 }
411 }
412 }
413 }
416 if ( !suppressDone ) {
417 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_DUPLICATE,
418 _("Duplicate"));
419 }
421 selection->setReprList(newsel);
423 g_slist_free(newsel);
424 }
426 void sp_edit_clear_all(SPDesktop *dt)
427 {
428 if (!dt)
429 return;
431 SPDocument *doc = sp_desktop_document(dt);
432 sp_desktop_selection(dt)->clear();
434 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
435 GSList *items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
437 while (items) {
438 SP_OBJECT(items->data)->deleteObject();
439 items = g_slist_remove(items, items->data);
440 }
442 sp_document_done(doc, SP_VERB_EDIT_CLEAR_ALL,
443 _("Delete all"));
444 }
446 GSList *
447 get_all_items(GSList *list, SPObject *from, SPDesktop *desktop, bool onlyvisible, bool onlysensitive, GSList const *exclude)
448 {
449 for (SPObject *child = sp_object_first_child(SP_OBJECT(from)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
450 if (SP_IS_ITEM(child) &&
451 !desktop->isLayer(SP_ITEM(child)) &&
452 (!onlysensitive || !SP_ITEM(child)->isLocked()) &&
453 (!onlyvisible || !desktop->itemIsHidden(SP_ITEM(child))) &&
454 (!exclude || !g_slist_find((GSList *) exclude, child))
455 )
456 {
457 list = g_slist_prepend(list, SP_ITEM(child));
458 }
460 if (SP_IS_ITEM(child) && desktop->isLayer(SP_ITEM(child))) {
461 list = get_all_items(list, child, desktop, onlyvisible, onlysensitive, exclude);
462 }
463 }
465 return list;
466 }
468 void sp_edit_select_all_full(SPDesktop *dt, bool force_all_layers, bool invert)
469 {
470 if (!dt)
471 return;
473 Inkscape::Selection *selection = sp_desktop_selection(dt);
475 g_return_if_fail(SP_IS_GROUP(dt->currentLayer()));
477 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
478 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
479 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
480 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
482 GSList *items = NULL;
484 GSList const *exclude = NULL;
485 if (invert) {
486 exclude = selection->itemList();
487 }
489 if (force_all_layers)
490 inlayer = PREFS_SELECTION_ALL;
492 switch (inlayer) {
493 case PREFS_SELECTION_LAYER: {
494 if ( (onlysensitive && SP_ITEM(dt->currentLayer())->isLocked()) ||
495 (onlyvisible && dt->itemIsHidden(SP_ITEM(dt->currentLayer()))) )
496 return;
498 GSList *all_items = sp_item_group_item_list(SP_GROUP(dt->currentLayer()));
500 for (GSList *i = all_items; i; i = i->next) {
501 SPItem *item = SP_ITEM(i->data);
503 if (item && (!onlysensitive || !item->isLocked())) {
504 if (!onlyvisible || !dt->itemIsHidden(item)) {
505 if (!dt->isLayer(item)) {
506 if (!invert || !g_slist_find((GSList *) exclude, item)) {
507 items = g_slist_prepend(items, item); // leave it in the list
508 }
509 }
510 }
511 }
512 }
514 g_slist_free(all_items);
515 break;
516 }
517 case PREFS_SELECTION_LAYER_RECURSIVE: {
518 items = get_all_items(NULL, dt->currentLayer(), dt, onlyvisible, onlysensitive, exclude);
519 break;
520 }
521 default: {
522 items = get_all_items(NULL, dt->currentRoot(), dt, onlyvisible, onlysensitive, exclude);
523 break;
524 }
525 }
527 selection->setList(items);
529 if (items) {
530 g_slist_free(items);
531 }
532 }
534 void sp_edit_select_all(SPDesktop *desktop)
535 {
536 sp_edit_select_all_full(desktop, false, false);
537 }
539 void sp_edit_select_all_in_all_layers(SPDesktop *desktop)
540 {
541 sp_edit_select_all_full(desktop, true, false);
542 }
544 void sp_edit_invert(SPDesktop *desktop)
545 {
546 sp_edit_select_all_full(desktop, false, true);
547 }
549 void sp_edit_invert_in_all_layers(SPDesktop *desktop)
550 {
551 sp_edit_select_all_full(desktop, true, true);
552 }
554 void sp_selection_group(SPDesktop *desktop)
555 {
556 if (desktop == NULL)
557 return;
559 SPDocument *doc = sp_desktop_document(desktop);
560 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
562 Inkscape::Selection *selection = sp_desktop_selection(desktop);
564 // Check if something is selected.
565 if (selection->isEmpty()) {
566 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>some objects</b> to group."));
567 return;
568 }
570 GSList const *l = (GSList *) selection->reprList();
572 GSList *p = g_slist_copy((GSList *) l);
574 selection->clear();
576 p = g_slist_sort(p, (GCompareFunc) sp_repr_compare_position);
578 // Remember the position and parent of the topmost object.
579 gint topmost = ((Inkscape::XML::Node *) g_slist_last(p)->data)->position();
580 Inkscape::XML::Node *topmost_parent = ((Inkscape::XML::Node *) g_slist_last(p)->data)->parent();
582 Inkscape::XML::Node *group = xml_doc->createElement("svg:g");
584 while (p) {
585 Inkscape::XML::Node *current = (Inkscape::XML::Node *) p->data;
587 if (current->parent() == topmost_parent) {
588 Inkscape::XML::Node *spnew = current->duplicate(xml_doc);
589 sp_repr_unparent(current);
590 group->appendChild(spnew);
591 Inkscape::GC::release(spnew);
592 topmost --; // only reduce count for those items deleted from topmost_parent
593 } else { // move it to topmost_parent first
594 GSList *temp_clip = NULL;
596 // At this point, current may already have no item, due to its being a clone whose original is already moved away
597 // So we copy it artificially calculating the transform from its repr->attr("transform") and the parent transform
598 gchar const *t_str = current->attribute("transform");
599 Geom::Matrix item_t(Geom::identity());
600 if (t_str)
601 sp_svg_transform_read(t_str, &item_t);
602 item_t *= sp_item_i2doc_affine(SP_ITEM(doc->getObjectByRepr(current->parent())));
603 // FIXME: when moving both clone and original from a transformed group (either by
604 // grouping into another parent, or by cut/paste) the transform from the original's
605 // parent becomes embedded into original itself, and this affects its clones. Fix
606 // this by remembering the transform diffs we write to each item into an array and
607 // then, if this is clone, looking up its original in that array and pre-multiplying
608 // it by the inverse of that original's transform diff.
610 sp_selection_copy_one(current, item_t, &temp_clip, xml_doc);
611 sp_repr_unparent(current);
613 // paste into topmost_parent (temporarily)
614 GSList *copied = sp_selection_paste_impl(doc, doc->getObjectByRepr(topmost_parent), &temp_clip);
615 if (temp_clip) g_slist_free(temp_clip);
616 if (copied) { // if success,
617 // take pasted object (now in topmost_parent)
618 Inkscape::XML::Node *in_topmost = (Inkscape::XML::Node *) copied->data;
619 // make a copy
620 Inkscape::XML::Node *spnew = in_topmost->duplicate(xml_doc);
621 // remove pasted
622 sp_repr_unparent(in_topmost);
623 // put its copy into group
624 group->appendChild(spnew);
625 Inkscape::GC::release(spnew);
626 g_slist_free(copied);
627 }
628 }
629 p = g_slist_remove(p, current);
630 }
632 // Add the new group to the topmost members' parent
633 topmost_parent->appendChild(group);
635 // Move to the position of the topmost, reduced by the number of items deleted from topmost_parent
636 group->setPosition(topmost + 1);
638 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_GROUP,
639 _("Group"));
641 selection->set(group);
642 Inkscape::GC::release(group);
643 }
645 void sp_selection_ungroup(SPDesktop *desktop)
646 {
647 if (desktop == NULL)
648 return;
650 Inkscape::Selection *selection = sp_desktop_selection(desktop);
652 if (selection->isEmpty()) {
653 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select a <b>group</b> to ungroup."));
654 return;
655 }
657 GSList *items = g_slist_copy((GSList *) selection->itemList());
658 selection->clear();
660 // Get a copy of current selection.
661 GSList *new_select = NULL;
662 bool ungrouped = false;
663 for (GSList *i = items;
664 i != NULL;
665 i = i->next)
666 {
667 SPItem *group = (SPItem *) i->data;
669 // when ungrouping cloned groups with their originals, some objects that were selected may no more exist due to unlinking
670 if (!SP_IS_OBJECT(group)) {
671 continue;
672 }
674 /* We do not allow ungrouping <svg> etc. (lauris) */
675 if (strcmp(SP_OBJECT_REPR(group)->name(), "svg:g") && strcmp(SP_OBJECT_REPR(group)->name(), "svg:switch")) {
676 // keep the non-group item in the new selection
677 selection->add(group);
678 continue;
679 }
681 GSList *children = NULL;
682 /* This is not strictly required, but is nicer to rely on group ::destroy (lauris) */
683 sp_item_group_ungroup(SP_GROUP(group), &children, false);
684 ungrouped = true;
685 // Add ungrouped items to the new selection.
686 new_select = g_slist_concat(new_select, children);
687 }
689 if (new_select) { // Set new selection.
690 selection->addList(new_select);
691 g_slist_free(new_select);
692 }
693 if (!ungrouped) {
694 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No groups</b> to ungroup in the selection."));
695 }
697 g_slist_free(items);
699 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_UNGROUP,
700 _("Ungroup"));
701 }
703 /** Replace all groups in the list with their member objects, recursively; returns a new list, frees old */
704 GSList *
705 sp_degroup_list(GSList *items)
706 {
707 GSList *out = NULL;
708 bool has_groups = false;
709 for (GSList *item = items; item; item = item->next) {
710 if (!SP_IS_GROUP(item->data)) {
711 out = g_slist_prepend(out, item->data);
712 } else {
713 has_groups = true;
714 GSList *members = sp_item_group_item_list(SP_GROUP(item->data));
715 for (GSList *member = members; member; member = member->next) {
716 out = g_slist_prepend(out, member->data);
717 }
718 g_slist_free(members);
719 }
720 }
721 out = g_slist_reverse(out);
722 g_slist_free(items);
724 if (has_groups) { // recurse if we unwrapped a group - it may have contained others
725 out = sp_degroup_list(out);
726 }
728 return out;
729 }
732 /** If items in the list have a common parent, return it, otherwise return NULL */
733 static SPGroup *
734 sp_item_list_common_parent_group(GSList const *items)
735 {
736 if (!items) {
737 return NULL;
738 }
739 SPObject *parent = SP_OBJECT_PARENT(items->data);
740 /* Strictly speaking this CAN happen, if user selects <svg> from Inkscape::XML editor */
741 if (!SP_IS_GROUP(parent)) {
742 return NULL;
743 }
744 for (items = items->next; items; items = items->next) {
745 if (SP_OBJECT_PARENT(items->data) != parent) {
746 return NULL;
747 }
748 }
750 return SP_GROUP(parent);
751 }
753 /** Finds out the minimum common bbox of the selected items. */
754 static Geom::OptRect
755 enclose_items(GSList const *items)
756 {
757 g_assert(items != NULL);
759 Geom::OptRect r;
760 for (GSList const *i = items; i; i = i->next) {
761 r = Geom::unify(r, sp_item_bbox_desktop((SPItem *) i->data));
762 }
763 return r;
764 }
766 SPObject *
767 prev_sibling(SPObject *child)
768 {
769 SPObject *parent = SP_OBJECT_PARENT(child);
770 if (!SP_IS_GROUP(parent)) {
771 return NULL;
772 }
773 for ( SPObject *i = sp_object_first_child(parent) ; i; i = SP_OBJECT_NEXT(i) ) {
774 if (i->next == child)
775 return i;
776 }
777 return NULL;
778 }
780 void
781 sp_selection_raise(SPDesktop *desktop)
782 {
783 if (!desktop)
784 return;
786 Inkscape::Selection *selection = sp_desktop_selection(desktop);
788 GSList const *items = (GSList *) selection->itemList();
789 if (!items) {
790 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise."));
791 return;
792 }
794 SPGroup const *group = sp_item_list_common_parent_group(items);
795 if (!group) {
796 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
797 return;
798 }
800 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
802 /* Construct reverse-ordered list of selected children. */
803 GSList *rev = g_slist_copy((GSList *) items);
804 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
806 // Determine the common bbox of the selected items.
807 Geom::OptRect selected = enclose_items(items);
809 // Iterate over all objects in the selection (starting from top).
810 if (selected) {
811 while (rev) {
812 SPObject *child = SP_OBJECT(rev->data);
813 // for each selected object, find the next sibling
814 for (SPObject *newref = child->next; newref; newref = newref->next) {
815 // if the sibling is an item AND overlaps our selection,
816 if (SP_IS_ITEM(newref)) {
817 Geom::OptRect newref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
818 if ( newref_bbox && selected->intersects(*newref_bbox) ) {
819 // AND if it's not one of our selected objects,
820 if (!g_slist_find((GSList *) items, newref)) {
821 // move the selected object after that sibling
822 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(newref));
823 }
824 break;
825 }
826 }
827 }
828 rev = g_slist_remove(rev, child);
829 }
830 } else {
831 g_slist_free(rev);
832 }
834 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_RAISE,
835 //TRANSLATORS: only translate "string" in "context|string".
836 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
837 // "Raise" means "to raise an object" in the undo history
838 Q_("undo_action|Raise"));
839 }
841 void sp_selection_raise_to_top(SPDesktop *desktop)
842 {
843 if (desktop == NULL)
844 return;
846 SPDocument *document = sp_desktop_document(desktop);
847 Inkscape::Selection *selection = sp_desktop_selection(desktop);
849 if (selection->isEmpty()) {
850 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to raise to top."));
851 return;
852 }
854 GSList const *items = (GSList *) selection->itemList();
856 SPGroup const *group = sp_item_list_common_parent_group(items);
857 if (!group) {
858 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
859 return;
860 }
862 GSList *rl = g_slist_copy((GSList *) selection->reprList());
863 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
865 for (GSList *l = rl; l != NULL; l = l->next) {
866 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
867 repr->setPosition(-1);
868 }
870 g_slist_free(rl);
872 sp_document_done(document, SP_VERB_SELECTION_TO_FRONT,
873 _("Raise to top"));
874 }
876 void
877 sp_selection_lower(SPDesktop *desktop)
878 {
879 if (desktop == NULL)
880 return;
882 Inkscape::Selection *selection = sp_desktop_selection(desktop);
884 GSList const *items = (GSList *) selection->itemList();
885 if (!items) {
886 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower."));
887 return;
888 }
890 SPGroup const *group = sp_item_list_common_parent_group(items);
891 if (!group) {
892 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
893 return;
894 }
896 Inkscape::XML::Node *grepr = SP_OBJECT_REPR(group);
898 // Determine the common bbox of the selected items.
899 Geom::OptRect selected = enclose_items(items);
901 /* Construct direct-ordered list of selected children. */
902 GSList *rev = g_slist_copy((GSList *) items);
903 rev = g_slist_sort(rev, (GCompareFunc) sp_item_repr_compare_position);
904 rev = g_slist_reverse(rev);
906 // Iterate over all objects in the selection (starting from top).
907 if (selected) {
908 while (rev) {
909 SPObject *child = SP_OBJECT(rev->data);
910 // for each selected object, find the prev sibling
911 for (SPObject *newref = prev_sibling(child); newref; newref = prev_sibling(newref)) {
912 // if the sibling is an item AND overlaps our selection,
913 if (SP_IS_ITEM(newref)) {
914 Geom::OptRect ref_bbox = sp_item_bbox_desktop(SP_ITEM(newref));
915 if ( ref_bbox && selected->intersects(*ref_bbox) ) {
916 // AND if it's not one of our selected objects,
917 if (!g_slist_find((GSList *) items, newref)) {
918 // move the selected object before that sibling
919 SPObject *put_after = prev_sibling(newref);
920 if (put_after)
921 grepr->changeOrder(SP_OBJECT_REPR(child), SP_OBJECT_REPR(put_after));
922 else
923 SP_OBJECT_REPR(child)->setPosition(0);
924 }
925 break;
926 }
927 }
928 }
929 rev = g_slist_remove(rev, child);
930 }
931 } else {
932 g_slist_free(rev);
933 }
935 sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_LOWER,
936 _("Lower"));
937 }
939 void sp_selection_lower_to_bottom(SPDesktop *desktop)
940 {
941 if (desktop == NULL)
942 return;
944 SPDocument *document = sp_desktop_document(desktop);
945 Inkscape::Selection *selection = sp_desktop_selection(desktop);
947 if (selection->isEmpty()) {
948 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to lower to bottom."));
949 return;
950 }
952 GSList const *items = (GSList *) selection->itemList();
954 SPGroup const *group = sp_item_list_common_parent_group(items);
955 if (!group) {
956 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("You cannot raise/lower objects from <b>different groups</b> or <b>layers</b>."));
957 return;
958 }
960 GSList *rl;
961 rl = g_slist_copy((GSList *) selection->reprList());
962 rl = g_slist_sort(rl, (GCompareFunc) sp_repr_compare_position);
963 rl = g_slist_reverse(rl);
965 for (GSList *l = rl; l != NULL; l = l->next) {
966 gint minpos;
967 SPObject *pp, *pc;
968 Inkscape::XML::Node *repr = (Inkscape::XML::Node *) l->data;
969 pp = document->getObjectByRepr(sp_repr_parent(repr));
970 minpos = 0;
971 g_assert(SP_IS_GROUP(pp));
972 pc = sp_object_first_child(pp);
973 while (!SP_IS_ITEM(pc)) {
974 minpos += 1;
975 pc = pc->next;
976 }
977 repr->setPosition(minpos);
978 }
980 g_slist_free(rl);
982 sp_document_done(document, SP_VERB_SELECTION_TO_BACK,
983 _("Lower to bottom"));
984 }
986 void
987 sp_undo(SPDesktop *desktop, SPDocument *)
988 {
989 if (!sp_document_undo(sp_desktop_document(desktop)))
990 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to undo."));
991 }
993 void
994 sp_redo(SPDesktop *desktop, SPDocument *)
995 {
996 if (!sp_document_redo(sp_desktop_document(desktop)))
997 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Nothing to redo."));
998 }
1000 void sp_selection_cut(SPDesktop *desktop)
1001 {
1002 sp_selection_copy();
1003 sp_selection_delete(desktop);
1004 }
1006 /**
1007 * \pre item != NULL
1008 */
1009 SPCSSAttr *
1010 take_style_from_item(SPItem *item)
1011 {
1012 // write the complete cascaded style, context-free
1013 SPCSSAttr *css = sp_css_attr_from_object(SP_OBJECT(item), SP_STYLE_FLAG_ALWAYS);
1014 if (css == NULL)
1015 return NULL;
1017 if ((SP_IS_GROUP(item) && SP_OBJECT(item)->children) ||
1018 (SP_IS_TEXT(item) && SP_OBJECT(item)->children && SP_OBJECT(item)->children->next == NULL)) {
1019 // if this is a text with exactly one tspan child, merge the style of that tspan as well
1020 // If this is a group, merge the style of its topmost (last) child with style
1021 for (SPObject *last_element = item->lastChild(); last_element != NULL; last_element = SP_OBJECT_PREV(last_element)) {
1022 if (SP_OBJECT_STYLE(last_element) != NULL) {
1023 SPCSSAttr *temp = sp_css_attr_from_object(last_element, SP_STYLE_FLAG_IFSET);
1024 if (temp) {
1025 sp_repr_css_merge(css, temp);
1026 sp_repr_css_attr_unref(temp);
1027 }
1028 break;
1029 }
1030 }
1031 }
1032 if (!(SP_IS_TEXT(item) || SP_IS_TSPAN(item) || SP_IS_TREF(item) || SP_IS_STRING(item))) {
1033 // do not copy text properties from non-text objects, it's confusing
1034 css = sp_css_attr_unset_text(css);
1035 }
1037 // FIXME: also transform gradient/pattern fills, by forking? NO, this must be nondestructive
1038 double ex = to_2geom(sp_item_i2doc_affine(item)).descrim();
1039 if (ex != 1.0) {
1040 css = sp_css_attr_scale(css, ex);
1041 }
1043 return css;
1044 }
1047 void sp_selection_copy()
1048 {
1049 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1050 cm->copy();
1051 }
1053 void sp_selection_paste(SPDesktop *desktop, bool in_place)
1054 {
1055 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1056 if (cm->paste(in_place))
1057 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE, _("Paste"));
1058 }
1060 void sp_selection_paste_style(SPDesktop *desktop)
1061 {
1062 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1063 if (cm->pasteStyle())
1064 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_STYLE, _("Paste style"));
1065 }
1068 void sp_selection_paste_livepatheffect(SPDesktop *desktop)
1069 {
1070 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1071 if (cm->pastePathEffect())
1072 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_LIVEPATHEFFECT,
1073 _("Paste live path effect"));
1074 }
1077 void sp_selection_remove_livepatheffect_impl(SPItem *item)
1078 {
1079 if ( item && SP_IS_LPE_ITEM(item) &&
1080 sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1081 sp_lpe_item_remove_all_path_effects(SP_LPE_ITEM(item), false);
1082 }
1083 }
1085 void sp_selection_remove_livepatheffect(SPDesktop *desktop)
1086 {
1087 if (desktop == NULL) return;
1089 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1091 // check if something is selected
1092 if (selection->isEmpty()) {
1093 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove live path effects from."));
1094 return;
1095 }
1097 for ( GSList const *itemlist = selection->itemList(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
1098 SPItem *item = reinterpret_cast<SPItem*>(itemlist->data);
1100 sp_selection_remove_livepatheffect_impl(item);
1102 }
1104 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_LIVEPATHEFFECT,
1105 _("Remove live path effect"));
1106 }
1108 void sp_selection_remove_filter(SPDesktop *desktop)
1109 {
1110 if (desktop == NULL) return;
1112 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1114 // check if something is selected
1115 if (selection->isEmpty()) {
1116 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove filters from."));
1117 return;
1118 }
1120 SPCSSAttr *css = sp_repr_css_attr_new();
1121 sp_repr_css_unset_property(css, "filter");
1122 sp_desktop_set_style(desktop, css);
1123 sp_repr_css_attr_unref(css);
1125 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_REMOVE_FILTER,
1126 _("Remove filter"));
1127 }
1130 void sp_selection_paste_size(SPDesktop *desktop, bool apply_x, bool apply_y)
1131 {
1132 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1133 if (cm->pasteSize(false, apply_x, apply_y))
1134 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE,
1135 _("Paste size"));
1136 }
1138 void sp_selection_paste_size_separately(SPDesktop *desktop, bool apply_x, bool apply_y)
1139 {
1140 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
1141 if (cm->pasteSize(true, apply_x, apply_y))
1142 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_PASTE_SIZE_SEPARATELY,
1143 _("Paste size separately"));
1144 }
1146 void sp_selection_to_next_layer(SPDesktop *dt, bool suppressDone)
1147 {
1148 Inkscape::Selection *selection = sp_desktop_selection(dt);
1150 // check if something is selected
1151 if (selection->isEmpty()) {
1152 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer above."));
1153 return;
1154 }
1156 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1158 bool no_more = false; // Set to true, if no more layers above
1159 SPObject *next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer());
1160 if (next) {
1161 GSList *temp_clip = NULL;
1162 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc()));
1163 sp_selection_delete_impl(items, false, false);
1164 next=Inkscape::next_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1165 GSList *copied;
1166 if (next) {
1167 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1168 } else {
1169 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1170 no_more = true;
1171 }
1172 selection->setReprList((GSList const *) copied);
1173 g_slist_free(copied);
1174 if (temp_clip) g_slist_free(temp_clip);
1175 if (next) dt->setCurrentLayer(next);
1176 if ( !suppressDone ) {
1177 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_NEXT,
1178 _("Raise to next layer"));
1179 }
1180 } else {
1181 no_more = true;
1182 }
1184 if (no_more) {
1185 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers above."));
1186 }
1188 g_slist_free((GSList *) items);
1189 }
1191 void sp_selection_to_prev_layer(SPDesktop *dt, bool suppressDone)
1192 {
1193 Inkscape::Selection *selection = sp_desktop_selection(dt);
1195 // check if something is selected
1196 if (selection->isEmpty()) {
1197 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to move to the layer below."));
1198 return;
1199 }
1201 GSList const *items = g_slist_copy((GSList *) selection->itemList());
1203 bool no_more = false; // Set to true, if no more layers below
1204 SPObject *next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer());
1205 if (next) {
1206 GSList *temp_clip = NULL;
1207 sp_selection_copy_impl(items, &temp_clip, sp_document_repr_doc(dt->doc())); // we're in the same doc, so no need to copy defs
1208 sp_selection_delete_impl(items, false, false);
1209 next=Inkscape::previous_layer(dt->currentRoot(), dt->currentLayer()); // Fixes bug 1482973: crash while moving layers
1210 GSList *copied;
1211 if (next) {
1212 copied = sp_selection_paste_impl(sp_desktop_document(dt), next, &temp_clip);
1213 } else {
1214 copied = sp_selection_paste_impl(sp_desktop_document(dt), dt->currentLayer(), &temp_clip);
1215 no_more = true;
1216 }
1217 selection->setReprList((GSList const *) copied);
1218 g_slist_free(copied);
1219 if (temp_clip) g_slist_free(temp_clip);
1220 if (next) dt->setCurrentLayer(next);
1221 if ( !suppressDone ) {
1222 sp_document_done(sp_desktop_document(dt), SP_VERB_LAYER_MOVE_TO_PREV,
1223 _("Lower to previous layer"));
1224 }
1225 } else {
1226 no_more = true;
1227 }
1229 if (no_more) {
1230 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("No more layers below."));
1231 }
1233 g_slist_free((GSList *) items);
1234 }
1236 bool
1237 selection_contains_original(SPItem *item, Inkscape::Selection *selection)
1238 {
1239 bool contains_original = false;
1241 bool is_use = SP_IS_USE(item);
1242 SPItem *item_use = item;
1243 SPItem *item_use_first = item;
1244 while (is_use && item_use && !contains_original)
1245 {
1246 item_use = sp_use_get_original(SP_USE(item_use));
1247 contains_original |= selection->includes(item_use);
1248 if (item_use == item_use_first)
1249 break;
1250 is_use = SP_IS_USE(item_use);
1251 }
1253 // If it's a tref, check whether the object containing the character
1254 // data is part of the selection
1255 if (!contains_original && SP_IS_TREF(item)) {
1256 contains_original = selection->includes(SP_TREF(item)->getObjectReferredTo());
1257 }
1259 return contains_original;
1260 }
1263 bool
1264 selection_contains_both_clone_and_original(Inkscape::Selection *selection)
1265 {
1266 bool clone_with_original = false;
1267 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1268 SPItem *item = SP_ITEM(l->data);
1269 clone_with_original |= selection_contains_original(item, selection);
1270 if (clone_with_original)
1271 break;
1272 }
1273 return clone_with_original;
1274 }
1276 /** Apply matrix to the selection. \a set_i2d is normally true, which means objects are in the
1277 original transform, synced with their reprs, and need to jump to the new transform in one go. A
1278 value of set_i2d==false is only used by seltrans when it's dragging objects live (not outlines); in
1279 that case, items are already in the new position, but the repr is in the old, and this function
1280 then simply updates the repr from item->transform.
1281 */
1282 void sp_selection_apply_affine(Inkscape::Selection *selection, Geom::Matrix const &affine, bool set_i2d, bool compensate)
1283 {
1284 if (selection->isEmpty())
1285 return;
1287 // For each perspective with a box in selection, check whether all boxes are selected and
1288 // unlink all non-selected boxes.
1289 Persp3D *persp;
1290 Persp3D *transf_persp;
1291 std::list<Persp3D *> plist = selection->perspList();
1292 for (std::list<Persp3D *>::iterator i = plist.begin(); i != plist.end(); ++i) {
1293 persp = (Persp3D *) (*i);
1295 if (!persp3d_has_all_boxes_in_selection (persp, selection)) {
1296 std::list<SPBox3D *> selboxes = selection->box3DList(persp);
1298 // create a new perspective as a copy of the current one and link the selected boxes to it
1299 transf_persp = persp3d_create_xml_element (SP_OBJECT_DOCUMENT(persp), persp->perspective_impl);
1301 for (std::list<SPBox3D *>::iterator b = selboxes.begin(); b != selboxes.end(); ++b)
1302 box3d_switch_perspectives(*b, persp, transf_persp);
1303 } else {
1304 transf_persp = persp;
1305 }
1307 persp3d_apply_affine_transformation(transf_persp, affine);
1308 }
1310 for (GSList const *l = selection->itemList(); l != NULL; l = l->next) {
1311 SPItem *item = SP_ITEM(l->data);
1313 Geom::Point old_center(0,0);
1314 if (set_i2d && item->isCenterSet())
1315 old_center = item->getCenter();
1317 #if 0 /* Re-enable this once persistent guides have a graphical indication.
1318 At the time of writing, this is the only place to re-enable. */
1319 sp_item_update_cns(*item, selection->desktop());
1320 #endif
1322 // we're moving both a clone and its original or any ancestor in clone chain?
1323 bool transform_clone_with_original = selection_contains_original(item, selection);
1324 // ...both a text-on-path and its path?
1325 bool transform_textpath_with_path = (SP_IS_TEXT_TEXTPATH(item) && selection->includes( sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item)))) ));
1326 // ...both a flowtext and its frame?
1327 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)
1328 // ...both an offset and its source?
1329 bool transform_offset_with_source = (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) && selection->includes( sp_offset_get_source(SP_OFFSET(item)) );
1331 // If we're moving a connector, we want to detach it
1332 // from shapes that aren't part of the selection, but
1333 // leave it attached if they are
1334 if (cc_item_is_connector(item)) {
1335 SPItem *attItem[2];
1336 SP_PATH(item)->connEndPair.getAttachedItems(attItem);
1338 for (int n = 0; n < 2; ++n) {
1339 if (!selection->includes(attItem[n])) {
1340 sp_conn_end_detach(item, n);
1341 }
1342 }
1343 }
1345 // "clones are unmoved when original is moved" preference
1346 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1347 int compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
1348 bool prefs_unmoved = (compensation == SP_CLONE_COMPENSATION_UNMOVED);
1349 bool prefs_parallel = (compensation == SP_CLONE_COMPENSATION_PARALLEL);
1351 /* If this is a clone and it's selected along with its original, do not move it;
1352 * it will feel the transform of its original and respond to it itself.
1353 * Without this, a clone is doubly transformed, very unintuitive.
1354 *
1355 * Same for textpath if we are also doing ANY transform to its path: do not touch textpath,
1356 * letters cannot be squeezed or rotated anyway, they only refill the changed path.
1357 * Same for linked offset if we are also moving its source: do not move it. */
1358 if (transform_textpath_with_path || transform_offset_with_source) {
1359 // Restore item->transform field from the repr, in case it was changed by seltrans.
1360 sp_object_read_attr(SP_OBJECT(item), "transform");
1361 } else if (transform_flowtext_with_frame) {
1362 // apply the inverse of the region's transform to the <use> so that the flow remains
1363 // the same (even though the output itself gets transformed)
1364 for (SPObject *region = item->firstChild() ; region ; region = SP_OBJECT_NEXT(region)) {
1365 if (!SP_IS_FLOWREGION(region) && !SP_IS_FLOWREGIONEXCLUDE(region))
1366 continue;
1367 for (SPObject *use = region->firstChild() ; use ; use = SP_OBJECT_NEXT(use)) {
1368 if (!SP_IS_USE(use)) continue;
1369 sp_item_write_transform(SP_USE(use), SP_OBJECT_REPR(use), item->transform.inverse(), NULL, compensate);
1370 }
1371 }
1372 } else if (transform_clone_with_original) {
1373 // We are transforming a clone along with its original. The below matrix juggling is
1374 // necessary to ensure that they transform as a whole, i.e. the clone's induced
1375 // transform and its move compensation are both cancelled out.
1377 // restore item->transform field from the repr, in case it was changed by seltrans
1378 sp_object_read_attr(SP_OBJECT(item), "transform");
1380 // calculate the matrix we need to apply to the clone to cancel its induced transform from its original
1381 Geom::Matrix parent2dt = sp_item_i2d_affine(SP_ITEM(SP_OBJECT_PARENT(item)));
1382 Geom::Matrix t = parent2dt * affine * parent2dt.inverse();
1383 Geom::Matrix t_inv = t.inverse();
1384 Geom::Matrix result = t_inv * item->transform * t;
1386 if ((prefs_parallel || prefs_unmoved) && affine.isTranslation()) {
1387 // we need to cancel out the move compensation, too
1389 // find out the clone move, same as in sp_use_move_compensate
1390 Geom::Matrix parent = sp_use_get_parent_transform(SP_USE(item));
1391 Geom::Matrix clone_move = parent.inverse() * t * parent;
1393 if (prefs_parallel) {
1394 Geom::Matrix move = result * clone_move * t_inv;
1395 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &move, compensate);
1397 } else if (prefs_unmoved) {
1398 //if (SP_IS_USE(sp_use_get_original(SP_USE(item))))
1399 // clone_move = Geom::identity();
1400 Geom::Matrix move = result * clone_move;
1401 sp_item_write_transform(item, SP_OBJECT_REPR(item), move, &t, compensate);
1402 }
1404 } else {
1405 // just apply the result
1406 sp_item_write_transform(item, SP_OBJECT_REPR(item), result, &t, compensate);
1407 }
1409 } else {
1410 if (set_i2d) {
1411 sp_item_set_i2d_affine(item, sp_item_i2d_affine(item) * (Geom::Matrix)affine);
1412 }
1413 sp_item_write_transform(item, SP_OBJECT_REPR(item), item->transform, NULL, compensate);
1414 }
1416 // if we're moving the actual object, not just updating the repr, we can transform the
1417 // center by the same matrix (only necessary for non-translations)
1418 if (set_i2d && item->isCenterSet() && !(affine.isTranslation() || affine.isIdentity())) {
1419 item->setCenter(old_center * affine);
1420 SP_OBJECT(item)->updateRepr();
1421 }
1422 }
1423 }
1425 void sp_selection_remove_transform(SPDesktop *desktop)
1426 {
1427 if (desktop == NULL)
1428 return;
1430 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1432 GSList const *l = (GSList *) selection->reprList();
1433 while (l != NULL) {
1434 ((Inkscape::XML::Node*)l->data)->setAttribute("transform", NULL, false);
1435 l = l->next;
1436 }
1438 sp_document_done(sp_desktop_document(desktop), SP_VERB_OBJECT_FLATTEN,
1439 _("Remove transform"));
1440 }
1442 void
1443 sp_selection_scale_absolute(Inkscape::Selection *selection,
1444 double const x0, double const x1,
1445 double const y0, double const y1)
1446 {
1447 if (selection->isEmpty())
1448 return;
1450 Geom::OptRect const bbox(selection->bounds());
1451 if ( !bbox ) {
1452 return;
1453 }
1455 Geom::Translate const p2o(-bbox->min());
1457 Geom::Scale const newSize(x1 - x0,
1458 y1 - y0);
1459 Geom::Scale const scale( newSize * Geom::Scale(bbox->dimensions()).inverse() );
1460 Geom::Translate const o2n(x0, y0);
1461 Geom::Matrix const final( p2o * scale * o2n );
1463 sp_selection_apply_affine(selection, final);
1464 }
1467 void sp_selection_scale_relative(Inkscape::Selection *selection, Geom::Point const &align, Geom::Scale const &scale)
1468 {
1469 if (selection->isEmpty())
1470 return;
1472 Geom::OptRect const bbox(selection->bounds());
1474 if ( !bbox ) {
1475 return;
1476 }
1478 // FIXME: ARBITRARY LIMIT: don't try to scale above 1 Mpx, it won't display properly and will crash sooner or later anyway
1479 if ( bbox->dimensions()[Geom::X] * scale[Geom::X] > 1e6 ||
1480 bbox->dimensions()[Geom::Y] * scale[Geom::Y] > 1e6 )
1481 {
1482 return;
1483 }
1485 Geom::Translate const n2d(-align);
1486 Geom::Translate const d2n(align);
1487 Geom::Matrix const final( n2d * scale * d2n );
1488 sp_selection_apply_affine(selection, final);
1489 }
1491 void
1492 sp_selection_rotate_relative(Inkscape::Selection *selection, Geom::Point const ¢er, gdouble const angle_degrees)
1493 {
1494 Geom::Translate const d2n(center);
1495 Geom::Translate const n2d(-center);
1496 Geom::Rotate const rotate(Geom::Rotate::from_degrees(angle_degrees));
1497 Geom::Matrix const final( Geom::Matrix(n2d) * rotate * d2n );
1498 sp_selection_apply_affine(selection, final);
1499 }
1501 void
1502 sp_selection_skew_relative(Inkscape::Selection *selection, Geom::Point const &align, double dx, double dy)
1503 {
1504 Geom::Translate const d2n(align);
1505 Geom::Translate const n2d(-align);
1506 Geom::Matrix const skew(1, dy,
1507 dx, 1,
1508 0, 0);
1509 Geom::Matrix const final( n2d * skew * d2n );
1510 sp_selection_apply_affine(selection, final);
1511 }
1513 void sp_selection_move_relative(Inkscape::Selection *selection, Geom::Point const &move, bool compensate)
1514 {
1515 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(move)), true, compensate);
1516 }
1518 void sp_selection_move_relative(Inkscape::Selection *selection, double dx, double dy)
1519 {
1520 sp_selection_apply_affine(selection, Geom::Matrix(Geom::Translate(dx, dy)));
1521 }
1523 /**
1524 * @brief Rotates selected objects 90 degrees, either clock-wise or counter-clockwise, depending on the value of ccw
1525 */
1526 void sp_selection_rotate_90(SPDesktop *desktop, bool ccw)
1527 {
1528 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1530 if (selection->isEmpty())
1531 return;
1533 GSList const *l = selection->itemList();
1534 Geom::Rotate const rot_90(Geom::Point(0, ccw ? 1 : -1)); // pos. or neg. rotation, depending on the value of ccw
1535 for (GSList const *l2 = l ; l2 != NULL ; l2 = l2->next) {
1536 SPItem *item = SP_ITEM(l2->data);
1537 sp_item_rotate_rel(item, rot_90);
1538 }
1540 sp_document_done(sp_desktop_document(desktop),
1541 ccw ? SP_VERB_OBJECT_ROTATE_90_CCW : SP_VERB_OBJECT_ROTATE_90_CW,
1542 ccw ? _("Rotate 90° CCW") : _("Rotate 90° CW"));
1543 }
1545 void
1546 sp_selection_rotate(Inkscape::Selection *selection, gdouble const angle_degrees)
1547 {
1548 if (selection->isEmpty())
1549 return;
1551 boost::optional<Geom::Point> center = selection->center();
1552 if (!center) {
1553 return;
1554 }
1556 sp_selection_rotate_relative(selection, *center, angle_degrees);
1558 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1559 ( ( angle_degrees > 0 )
1560 ? "selector:rotate:ccw"
1561 : "selector:rotate:cw" ),
1562 SP_VERB_CONTEXT_SELECT,
1563 _("Rotate"));
1564 }
1566 // helper function:
1567 static
1568 Geom::Point
1569 cornerFarthestFrom(Geom::Rect const &r, Geom::Point const &p){
1570 Geom::Point m = r.midpoint();
1571 unsigned i = 0;
1572 if (p[X] < m[X]) {
1573 i = 1;
1574 }
1575 if (p[Y] < m[Y]) {
1576 i = 3 - i;
1577 }
1578 return r.corner(i);
1579 }
1581 /**
1582 \param angle the angle in "angular pixels", i.e. how many visible pixels must move the outermost point of the rotated object
1583 */
1584 void
1585 sp_selection_rotate_screen(Inkscape::Selection *selection, gdouble angle)
1586 {
1587 if (selection->isEmpty())
1588 return;
1590 Geom::OptRect const bbox(selection->bounds());
1591 boost::optional<Geom::Point> center = selection->center();
1593 if ( !bbox || !center ) {
1594 return;
1595 }
1597 gdouble const zoom = selection->desktop()->current_zoom();
1598 gdouble const zmove = angle / zoom;
1599 gdouble const r = Geom::L2(cornerFarthestFrom(*bbox, *center) - *center);
1601 gdouble const zangle = 180 * atan2(zmove, r) / M_PI;
1603 sp_selection_rotate_relative(selection, *center, zangle);
1605 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1606 ( (angle > 0)
1607 ? "selector:rotate:ccw"
1608 : "selector:rotate:cw" ),
1609 SP_VERB_CONTEXT_SELECT,
1610 _("Rotate by pixels"));
1611 }
1613 void
1614 sp_selection_scale(Inkscape::Selection *selection, gdouble grow)
1615 {
1616 if (selection->isEmpty())
1617 return;
1619 Geom::OptRect const bbox(selection->bounds());
1620 if (!bbox) {
1621 return;
1622 }
1624 Geom::Point const center(bbox->midpoint());
1626 // you can't scale "do nizhe pola" (below zero)
1627 double const max_len = bbox->maxExtent();
1628 if ( max_len + grow <= 1e-3 ) {
1629 return;
1630 }
1632 double const times = 1.0 + grow / max_len;
1633 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1635 sp_document_maybe_done(sp_desktop_document(selection->desktop()),
1636 ( (grow > 0)
1637 ? "selector:scale:larger"
1638 : "selector:scale:smaller" ),
1639 SP_VERB_CONTEXT_SELECT,
1640 _("Scale"));
1641 }
1643 void
1644 sp_selection_scale_screen(Inkscape::Selection *selection, gdouble grow_pixels)
1645 {
1646 sp_selection_scale(selection,
1647 grow_pixels / selection->desktop()->current_zoom());
1648 }
1650 void
1651 sp_selection_scale_times(Inkscape::Selection *selection, gdouble times)
1652 {
1653 if (selection->isEmpty())
1654 return;
1656 Geom::OptRect sel_bbox = selection->bounds();
1658 if (!sel_bbox) {
1659 return;
1660 }
1662 Geom::Point const center(sel_bbox->midpoint());
1663 sp_selection_scale_relative(selection, center, Geom::Scale(times, times));
1664 sp_document_done(sp_desktop_document(selection->desktop()), SP_VERB_CONTEXT_SELECT,
1665 _("Scale by whole factor"));
1666 }
1668 void
1669 sp_selection_move(SPDesktop *desktop, gdouble dx, gdouble dy)
1670 {
1671 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1672 if (selection->isEmpty()) {
1673 return;
1674 }
1676 sp_selection_move_relative(selection, dx, dy);
1678 if (dx == 0) {
1679 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1680 _("Move vertically"));
1681 } else if (dy == 0) {
1682 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1683 _("Move horizontally"));
1684 } else {
1685 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1686 _("Move"));
1687 }
1688 }
1690 void
1691 sp_selection_move_screen(SPDesktop *desktop, gdouble dx, gdouble dy)
1692 {
1693 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1694 if (selection->isEmpty()) {
1695 return;
1696 }
1698 // same as sp_selection_move but divide deltas by zoom factor
1699 gdouble const zoom = desktop->current_zoom();
1700 gdouble const zdx = dx / zoom;
1701 gdouble const zdy = dy / zoom;
1702 sp_selection_move_relative(selection, zdx, zdy);
1704 if (dx == 0) {
1705 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:vertical", SP_VERB_CONTEXT_SELECT,
1706 _("Move vertically by pixels"));
1707 } else if (dy == 0) {
1708 sp_document_maybe_done(sp_desktop_document(desktop), "selector:move:horizontal", SP_VERB_CONTEXT_SELECT,
1709 _("Move horizontally by pixels"));
1710 } else {
1711 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_SELECT,
1712 _("Move"));
1713 }
1714 }
1716 namespace {
1718 template <typename D>
1719 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1720 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1722 template <typename D>
1723 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items, SPObject *root,
1724 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive);
1726 struct Forward {
1727 typedef SPObject *Iterator;
1729 static Iterator children(SPObject *o) { return sp_object_first_child(o); }
1730 static Iterator siblings_after(SPObject *o) { return SP_OBJECT_NEXT(o); }
1731 static void dispose(Iterator /*i*/) {}
1733 static SPObject *object(Iterator i) { return i; }
1734 static Iterator next(Iterator i) { return SP_OBJECT_NEXT(i); }
1735 };
1737 struct Reverse {
1738 typedef GSList *Iterator;
1740 static Iterator children(SPObject *o) {
1741 return make_list(o->firstChild(), NULL);
1742 }
1743 static Iterator siblings_after(SPObject *o) {
1744 return make_list(SP_OBJECT_PARENT(o)->firstChild(), o);
1745 }
1746 static void dispose(Iterator i) {
1747 g_slist_free(i);
1748 }
1750 static SPObject *object(Iterator i) {
1751 return reinterpret_cast<SPObject *>(i->data);
1752 }
1753 static Iterator next(Iterator i) { return i->next; }
1755 private:
1756 static GSList *make_list(SPObject *object, SPObject *limit) {
1757 GSList *list=NULL;
1758 while ( object != limit ) {
1759 list = g_slist_prepend(list, object);
1760 object = SP_OBJECT_NEXT(object);
1761 }
1762 return list;
1763 }
1764 };
1766 }
1768 void
1769 sp_selection_item_next(SPDesktop *desktop)
1770 {
1771 g_return_if_fail(desktop != NULL);
1772 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1774 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1775 PrefsSelectionContext inlayer = (PrefsSelectionContext)prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1776 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1777 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1779 SPObject *root;
1780 if (PREFS_SELECTION_ALL != inlayer) {
1781 root = selection->activeContext();
1782 } else {
1783 root = desktop->currentRoot();
1784 }
1786 SPItem *item=next_item_from_list<Forward>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1788 if (item) {
1789 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1790 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1791 scroll_to_show_item(desktop, item);
1792 }
1793 }
1794 }
1796 void
1797 sp_selection_item_prev(SPDesktop *desktop)
1798 {
1799 SPDocument *document = sp_desktop_document(desktop);
1800 g_return_if_fail(document != NULL);
1801 g_return_if_fail(desktop != NULL);
1802 Inkscape::Selection *selection = sp_desktop_selection(desktop);
1804 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1805 PrefsSelectionContext inlayer = (PrefsSelectionContext) prefs->getInt("/options/kbselection/inlayer", PREFS_SELECTION_LAYER);
1806 bool onlyvisible = prefs->getBool("/options/kbselection/onlyvisible", true);
1807 bool onlysensitive = prefs->getBool("/options/kbselection/onlysensitive", true);
1809 SPObject *root;
1810 if (PREFS_SELECTION_ALL != inlayer) {
1811 root = selection->activeContext();
1812 } else {
1813 root = desktop->currentRoot();
1814 }
1816 SPItem *item=next_item_from_list<Reverse>(desktop, selection->itemList(), root, SP_CYCLING == SP_CYCLE_VISIBLE, inlayer, onlyvisible, onlysensitive);
1818 if (item) {
1819 selection->set(item, PREFS_SELECTION_LAYER_RECURSIVE == inlayer);
1820 if ( SP_CYCLING == SP_CYCLE_FOCUS ) {
1821 scroll_to_show_item(desktop, item);
1822 }
1823 }
1824 }
1826 void sp_selection_next_patheffect_param(SPDesktop * dt)
1827 {
1828 if (!dt) return;
1830 Inkscape::Selection *selection = sp_desktop_selection(dt);
1831 if ( selection && !selection->isEmpty() ) {
1832 SPItem *item = selection->singleItem();
1833 if ( item && SP_IS_SHAPE(item)) {
1834 if (sp_lpe_item_has_path_effect(SP_LPE_ITEM(item))) {
1835 sp_lpe_item_edit_next_param_oncanvas(SP_LPE_ITEM(item), dt);
1836 } else {
1837 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("The selection has no applied path effect."));
1838 }
1839 }
1840 }
1841 }
1843 /*bool has_path_recursive(SPObject *obj)
1844 {
1845 if (!obj) return false;
1846 if (SP_IS_PATH(obj)) {
1847 return true;
1848 }
1849 if (SP_IS_GROUP(obj) || SP_IS_OBJECTGROUP(obj)) {
1850 for (SPObject *c = obj->children; c; c = c->next) {
1851 if (has_path_recursive(c)) return true;
1852 }
1853 }
1854 return false;
1855 }*/
1857 void sp_selection_edit_clip_or_mask(SPDesktop * /*dt*/, bool /*clip*/)
1858 {
1859 return;
1860 /*if (!dt) return;
1861 using namespace Inkscape::UI;
1863 Inkscape::Selection *selection = sp_desktop_selection(dt);
1864 if (!selection || selection->isEmpty()) return;
1866 GSList const *items = selection->itemList();
1867 bool has_path = false;
1868 for (GSList *i = const_cast<GSList*>(items); i; i= i->next) {
1869 SPItem *item = SP_ITEM(i->data);
1870 SPObject *search = clip
1871 ? SP_OBJECT(item->clip_ref ? item->clip_ref->getObject() : NULL)
1872 : SP_OBJECT(item->mask_ref ? item->mask_ref->getObject() : NULL);
1873 has_path |= has_path_recursive(search);
1874 if (has_path) break;
1875 }
1876 if (has_path) {
1877 if (!tools_isactive(dt, TOOLS_NODES)) {
1878 tools_switch(dt, TOOLS_NODES);
1879 }
1880 ink_node_tool_set_mode(INK_NODE_TOOL(dt->event_context),
1881 clip ? NODE_TOOL_EDIT_CLIPPING_PATHS : NODE_TOOL_EDIT_MASKS);
1882 } else if (clip) {
1883 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1884 _("The selection has no applied clip path."));
1885 } else {
1886 dt->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1887 _("The selection has no applied mask."));
1888 }*/
1889 }
1892 namespace {
1894 template <typename D>
1895 SPItem *next_item_from_list(SPDesktop *desktop, GSList const *items,
1896 SPObject *root, bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1897 {
1898 SPObject *current=root;
1899 while (items) {
1900 SPItem *item=SP_ITEM(items->data);
1901 if ( root->isAncestorOf(item) &&
1902 ( !only_in_viewport || desktop->isWithinViewport(item) ) )
1903 {
1904 current = item;
1905 break;
1906 }
1907 items = items->next;
1908 }
1910 GSList *path=NULL;
1911 while ( current != root ) {
1912 path = g_slist_prepend(path, current);
1913 current = SP_OBJECT_PARENT(current);
1914 }
1916 SPItem *next;
1917 // first, try from the current object
1918 next = next_item<D>(desktop, path, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1919 g_slist_free(path);
1921 if (!next) { // if we ran out of objects, start over at the root
1922 next = next_item<D>(desktop, NULL, root, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1923 }
1925 return next;
1926 }
1928 template <typename D>
1929 SPItem *next_item(SPDesktop *desktop, GSList *path, SPObject *root,
1930 bool only_in_viewport, PrefsSelectionContext inlayer, bool onlyvisible, bool onlysensitive)
1931 {
1932 typename D::Iterator children;
1933 typename D::Iterator iter;
1935 SPItem *found=NULL;
1937 if (path) {
1938 SPObject *object=reinterpret_cast<SPObject *>(path->data);
1939 g_assert(SP_OBJECT_PARENT(object) == root);
1940 if (desktop->isLayer(object)) {
1941 found = next_item<D>(desktop, path->next, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1942 }
1943 iter = children = D::siblings_after(object);
1944 } else {
1945 iter = children = D::children(root);
1946 }
1948 while ( iter && !found ) {
1949 SPObject *object=D::object(iter);
1950 if (desktop->isLayer(object)) {
1951 if (PREFS_SELECTION_LAYER != inlayer) { // recurse into sublayers
1952 found = next_item<D>(desktop, NULL, object, only_in_viewport, inlayer, onlyvisible, onlysensitive);
1953 }
1954 } else if ( SP_IS_ITEM(object) &&
1955 ( !only_in_viewport || desktop->isWithinViewport(SP_ITEM(object)) ) &&
1956 ( !onlyvisible || !desktop->itemIsHidden(SP_ITEM(object))) &&
1957 ( !onlysensitive || !SP_ITEM(object)->isLocked()) &&
1958 !desktop->isLayer(SP_ITEM(object)) )
1959 {
1960 found = SP_ITEM(object);
1961 }
1962 iter = D::next(iter);
1963 }
1965 D::dispose(children);
1967 return found;
1968 }
1970 }
1972 /**
1973 * If \a item is not entirely visible then adjust visible area to centre on the centre on of
1974 * \a item.
1975 */
1976 void scroll_to_show_item(SPDesktop *desktop, SPItem *item)
1977 {
1978 Geom::Rect dbox = desktop->get_display_area();
1979 Geom::OptRect sbox = sp_item_bbox_desktop(item);
1981 if ( sbox && dbox.contains(*sbox) == false ) {
1982 Geom::Point const s_dt = sbox->midpoint();
1983 Geom::Point const s_w = desktop->d2w(s_dt);
1984 Geom::Point const d_dt = dbox.midpoint();
1985 Geom::Point const d_w = desktop->d2w(d_dt);
1986 Geom::Point const moved_w( d_w - s_w );
1987 gint const dx = (gint) moved_w[X];
1988 gint const dy = (gint) moved_w[Y];
1989 desktop->scroll_world(dx, dy);
1990 }
1991 }
1994 void
1995 sp_selection_clone(SPDesktop *desktop)
1996 {
1997 if (desktop == NULL)
1998 return;
2000 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2002 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
2004 // check if something is selected
2005 if (selection->isEmpty()) {
2006 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object</b> to clone."));
2007 return;
2008 }
2010 GSList *reprs = g_slist_copy((GSList *) selection->reprList());
2012 selection->clear();
2014 // sorting items from different parents sorts each parent's subset without possibly mixing them, just what we need
2015 reprs = g_slist_sort(reprs, (GCompareFunc) sp_repr_compare_position);
2017 GSList *newsel = NULL;
2019 while (reprs) {
2020 Inkscape::XML::Node *sel_repr = (Inkscape::XML::Node *) reprs->data;
2021 Inkscape::XML::Node *parent = sp_repr_parent(sel_repr);
2023 Inkscape::XML::Node *clone = xml_doc->createElement("svg:use");
2024 clone->setAttribute("x", "0", false);
2025 clone->setAttribute("y", "0", false);
2026 clone->setAttribute("xlink:href", g_strdup_printf("#%s", sel_repr->attribute("id")), false);
2028 clone->setAttribute("inkscape:transform-center-x", sel_repr->attribute("inkscape:transform-center-x"), false);
2029 clone->setAttribute("inkscape:transform-center-y", sel_repr->attribute("inkscape:transform-center-y"), false);
2031 // add the new clone to the top of the original's parent
2032 parent->appendChild(clone);
2034 newsel = g_slist_prepend(newsel, clone);
2035 reprs = g_slist_remove(reprs, sel_repr);
2036 Inkscape::GC::release(clone);
2037 }
2039 // TRANSLATORS: only translate "string" in "context|string".
2040 // For more details, see http://developer.gnome.org/doc/API/2.0/glib/glib-I18N.html#Q-:CAPS
2041 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_CLONE,
2042 Q_("action|Clone"));
2044 selection->setReprList(newsel);
2046 g_slist_free(newsel);
2047 }
2049 void
2050 sp_selection_relink(SPDesktop *desktop)
2051 {
2052 if (!desktop)
2053 return;
2055 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2057 if (selection->isEmpty()) {
2058 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to relink."));
2059 return;
2060 }
2062 Inkscape::UI::ClipboardManager *cm = Inkscape::UI::ClipboardManager::get();
2063 const gchar *newid = cm->getFirstObjectID();
2064 if (!newid) {
2065 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Copy an <b>object</b> to clipboard to relink clones to."));
2066 return;
2067 }
2068 gchar *newref = g_strdup_printf("#%s", newid);
2070 // Get a copy of current selection.
2071 bool relinked = false;
2072 for (GSList *items = (GSList *) selection->itemList();
2073 items != NULL;
2074 items = items->next)
2075 {
2076 SPItem *item = (SPItem *) items->data;
2078 if (!SP_IS_USE(item))
2079 continue;
2081 SP_OBJECT_REPR(item)->setAttribute("xlink:href", newref);
2082 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2083 relinked = true;
2084 }
2086 g_free(newref);
2088 if (!relinked) {
2089 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to relink</b> in the selection."));
2090 } else {
2091 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2092 _("Relink clone"));
2093 }
2094 }
2097 void
2098 sp_selection_unlink(SPDesktop *desktop)
2099 {
2100 if (!desktop)
2101 return;
2103 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2105 if (selection->isEmpty()) {
2106 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>clones</b> to unlink."));
2107 return;
2108 }
2110 // Get a copy of current selection.
2111 GSList *new_select = NULL;
2112 bool unlinked = false;
2113 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2114 items != NULL;
2115 items = items->next)
2116 {
2117 SPItem *item = (SPItem *) items->data;
2119 if (SP_IS_TEXT(item)) {
2120 SPObject *tspan = sp_tref_convert_to_tspan(SP_OBJECT(item));
2122 if (tspan) {
2123 SP_OBJECT(item)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
2124 }
2126 // Set unlink to true, and fall into the next if which
2127 // will include this text item in the new selection
2128 unlinked = true;
2129 }
2131 if (!(SP_IS_USE(item) || SP_IS_TREF(item))) {
2132 // keep the non-use item in the new selection
2133 new_select = g_slist_prepend(new_select, item);
2134 continue;
2135 }
2137 SPItem *unlink;
2138 if (SP_IS_USE(item)) {
2139 unlink = sp_use_unlink(SP_USE(item));
2140 } else /*if (SP_IS_TREF(use))*/ {
2141 unlink = SP_ITEM(sp_tref_convert_to_tspan(SP_OBJECT(item)));
2142 }
2144 unlinked = true;
2145 // Add ungrouped items to the new selection.
2146 new_select = g_slist_prepend(new_select, unlink);
2147 }
2149 if (new_select) { // set new selection
2150 selection->clear();
2151 selection->setList(new_select);
2152 g_slist_free(new_select);
2153 }
2154 if (!unlinked) {
2155 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No clones to unlink</b> in the selection."));
2156 }
2158 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNLINK_CLONE,
2159 _("Unlink clone"));
2160 }
2162 void
2163 sp_select_clone_original(SPDesktop *desktop)
2164 {
2165 if (desktop == NULL)
2166 return;
2168 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2170 SPItem *item = selection->singleItem();
2172 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.");
2174 // Check if other than two objects are selected
2175 if (g_slist_length((GSList *) selection->itemList()) != 1 || !item) {
2176 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2177 return;
2178 }
2180 SPItem *original = NULL;
2181 if (SP_IS_USE(item)) {
2182 original = sp_use_get_original(SP_USE(item));
2183 } else if (SP_IS_OFFSET(item) && SP_OFFSET(item)->sourceHref) {
2184 original = sp_offset_get_source(SP_OFFSET(item));
2185 } else if (SP_IS_TEXT_TEXTPATH(item)) {
2186 original = sp_textpath_get_path_item(SP_TEXTPATH(sp_object_first_child(SP_OBJECT(item))));
2187 } else if (SP_IS_FLOWTEXT(item)) {
2188 original = SP_FLOWTEXT(item)->get_frame(NULL); // first frame only
2189 } else { // it's an object that we don't know what to do with
2190 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, error);
2191 return;
2192 }
2194 if (!original) {
2195 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>Cannot find</b> the object to select (orphaned clone, offset, textpath, flowed text?)"));
2196 return;
2197 }
2199 for (SPObject *o = original; o && !SP_IS_ROOT(o); o = SP_OBJECT_PARENT(o)) {
2200 if (SP_IS_DEFS(o)) {
2201 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("The object you're trying to select is <b>not visible</b> (it is in <defs>)"));
2202 return;
2203 }
2204 }
2206 if (original) {
2207 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2208 bool highlight = prefs->getBool("/options/highlightoriginal/value");
2209 if (highlight) {
2210 Geom::OptRect a = item->getBounds(sp_item_i2d_affine(item));
2211 Geom::OptRect b = original->getBounds(sp_item_i2d_affine(original));
2212 if ( a && b ) {
2213 // draw a flashing line between the objects
2214 SPCurve *curve = new SPCurve();
2215 curve->moveto(a->midpoint());
2216 curve->lineto(b->midpoint());
2218 SPCanvasItem * canvasitem = sp_canvas_bpath_new(sp_desktop_tempgroup(desktop), curve);
2219 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(canvasitem), 0x0000ddff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 3);
2220 sp_canvas_item_show(canvasitem);
2221 curve->unref();
2222 desktop->add_temporary_canvasitem(canvasitem, 1000);
2223 }
2224 }
2226 selection->clear();
2227 selection->set(original);
2228 if (SP_CYCLING == SP_CYCLE_FOCUS) {
2229 scroll_to_show_item(desktop, original);
2230 }
2231 }
2232 }
2235 void sp_selection_to_marker(SPDesktop *desktop, bool apply)
2236 {
2237 if (desktop == NULL)
2238 return;
2240 SPDocument *doc = sp_desktop_document(desktop);
2241 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2243 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2245 // check if something is selected
2246 if (selection->isEmpty()) {
2247 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to marker."));
2248 return;
2249 }
2251 sp_document_ensure_up_to_date(doc);
2252 Geom::OptRect r = selection->bounds();
2253 boost::optional<Geom::Point> c = selection->center();
2254 if ( !r || !c ) {
2255 return;
2256 }
2258 // calculate the transform to be applied to objects to move them to 0,0
2259 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - *c;
2260 move_p[Geom::Y] = -move_p[Geom::Y];
2261 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2263 GSList *items = g_slist_copy((GSList *) selection->itemList());
2265 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2267 // bottommost object, after sorting
2268 SPObject *parent = SP_OBJECT_PARENT(items->data);
2270 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2272 // remember the position of the first item
2273 gint pos = SP_OBJECT_REPR(items->data)->position();
2274 (void)pos; // TODO check why this was remembered
2276 // create a list of duplicates
2277 GSList *repr_copies = NULL;
2278 for (GSList *i = items; i != NULL; i = i->next) {
2279 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2280 repr_copies = g_slist_prepend(repr_copies, dup);
2281 }
2283 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2285 if (apply) {
2286 // delete objects so that their clones don't get alerted; this object will be restored shortly
2287 for (GSList *i = items; i != NULL; i = i->next) {
2288 SPObject *item = SP_OBJECT(i->data);
2289 item->deleteObject(false);
2290 }
2291 }
2293 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2294 // without disturbing clones.
2295 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2296 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2297 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2298 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2300 gchar const *mark_id = generate_marker(repr_copies, bounds, doc,
2301 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(
2302 Geom::Point(r->min()[Geom::X],
2303 r->max()[Geom::Y]))))
2304 * parent_transform.inverse() ),
2305 parent_transform * move);
2306 (void)mark_id;
2308 // restore compensation setting
2309 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2312 g_slist_free(items);
2314 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_MARKER,
2315 _("Objects to marker"));
2316 }
2318 static void sp_selection_to_guides_recursive(SPItem *item, bool deleteitem, bool wholegroups) {
2319 if (SP_IS_GROUP(item) && !SP_IS_BOX3D(item) && !wholegroups) {
2320 for (GSList *i = sp_item_group_item_list(SP_GROUP(item)); i != NULL; i = i->next) {
2321 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2322 }
2323 } else {
2324 sp_item_convert_item_to_guides(item);
2326 if (deleteitem) {
2327 SP_OBJECT(item)->deleteObject(true);
2328 }
2329 }
2330 }
2332 void sp_selection_to_guides(SPDesktop *desktop)
2333 {
2334 if (desktop == NULL)
2335 return;
2337 SPDocument *doc = sp_desktop_document(desktop);
2338 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2339 // we need to copy the list because it gets reset when objects are deleted
2340 GSList *items = g_slist_copy((GSList *) selection->itemList());
2342 if (!items) {
2343 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to guides."));
2344 return;
2345 }
2347 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2348 bool deleteitem = !prefs->getBool("/tools/cvg_keep_objects", 0);
2349 bool wholegroups = prefs->getBool("/tools/cvg_convert_whole_groups", 0);
2351 for (GSList const *i = items; i != NULL; i = i->next) {
2352 sp_selection_to_guides_recursive(SP_ITEM(i->data), deleteitem, wholegroups);
2353 }
2355 sp_document_done(doc, SP_VERB_EDIT_SELECTION_2_GUIDES, _("Objects to guides"));
2356 }
2358 void
2359 sp_selection_tile(SPDesktop *desktop, bool apply)
2360 {
2361 if (desktop == NULL)
2362 return;
2364 SPDocument *doc = sp_desktop_document(desktop);
2365 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2367 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2369 // check if something is selected
2370 if (selection->isEmpty()) {
2371 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to convert to pattern."));
2372 return;
2373 }
2375 sp_document_ensure_up_to_date(doc);
2376 Geom::OptRect r = selection->bounds();
2377 if ( !r ) {
2378 return;
2379 }
2381 // calculate the transform to be applied to objects to move them to 0,0
2382 Geom::Point move_p = Geom::Point(0, sp_document_height(doc)) - (r->min() + Geom::Point(0, r->dimensions()[Geom::Y]));
2383 move_p[Geom::Y] = -move_p[Geom::Y];
2384 Geom::Matrix move = Geom::Matrix(Geom::Translate(move_p));
2386 GSList *items = g_slist_copy((GSList *) selection->itemList());
2388 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2390 // bottommost object, after sorting
2391 SPObject *parent = SP_OBJECT_PARENT(items->data);
2393 Geom::Matrix parent_transform(sp_item_i2doc_affine(SP_ITEM(parent)));
2395 // remember the position of the first item
2396 gint pos = SP_OBJECT_REPR(items->data)->position();
2398 // create a list of duplicates
2399 GSList *repr_copies = NULL;
2400 for (GSList *i = items; i != NULL; i = i->next) {
2401 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2402 repr_copies = g_slist_prepend(repr_copies, dup);
2403 }
2404 // restore the z-order after prepends
2405 repr_copies = g_slist_reverse(repr_copies);
2407 Geom::Rect bounds(desktop->dt2doc(r->min()), desktop->dt2doc(r->max()));
2409 if (apply) {
2410 // delete objects so that their clones don't get alerted; this object will be restored shortly
2411 for (GSList *i = items; i != NULL; i = i->next) {
2412 SPObject *item = SP_OBJECT(i->data);
2413 item->deleteObject(false);
2414 }
2415 }
2417 // Hack: Temporarily set clone compensation to unmoved, so that we can move clone-originals
2418 // without disturbing clones.
2419 // See ActorAlign::on_button_click() in src/ui/dialog/align-and-distribute.cpp
2420 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2421 int saved_compensation = prefs->getInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2422 prefs->setInt("/options/clonecompensation/value", SP_CLONE_COMPENSATION_UNMOVED);
2424 gchar const *pat_id = pattern_tile(repr_copies, bounds, doc,
2425 ( Geom::Matrix(Geom::Translate(desktop->dt2doc(Geom::Point(r->min()[Geom::X],
2426 r->max()[Geom::Y]))))
2427 * to_2geom(parent_transform.inverse()) ),
2428 parent_transform * move);
2430 // restore compensation setting
2431 prefs->setInt("/options/clonecompensation/value", saved_compensation);
2433 if (apply) {
2434 Inkscape::XML::Node *rect = xml_doc->createElement("svg:rect");
2435 rect->setAttribute("style", g_strdup_printf("stroke:none;fill:url(#%s)", pat_id));
2437 Geom::Point min = bounds.min() * to_2geom(parent_transform.inverse());
2438 Geom::Point max = bounds.max() * to_2geom(parent_transform.inverse());
2440 sp_repr_set_svg_double(rect, "width", max[Geom::X] - min[Geom::X]);
2441 sp_repr_set_svg_double(rect, "height", max[Geom::Y] - min[Geom::Y]);
2442 sp_repr_set_svg_double(rect, "x", min[Geom::X]);
2443 sp_repr_set_svg_double(rect, "y", min[Geom::Y]);
2445 // restore parent and position
2446 SP_OBJECT_REPR(parent)->appendChild(rect);
2447 rect->setPosition(pos > 0 ? pos : 0);
2448 SPItem *rectangle = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(rect);
2450 Inkscape::GC::release(rect);
2452 selection->clear();
2453 selection->set(rectangle);
2454 }
2456 g_slist_free(items);
2458 sp_document_done(doc, SP_VERB_EDIT_TILE,
2459 _("Objects to pattern"));
2460 }
2462 void
2463 sp_selection_untile(SPDesktop *desktop)
2464 {
2465 if (desktop == NULL)
2466 return;
2468 SPDocument *doc = sp_desktop_document(desktop);
2469 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2471 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2473 // check if something is selected
2474 if (selection->isEmpty()) {
2475 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select an <b>object with pattern fill</b> to extract objects from."));
2476 return;
2477 }
2479 GSList *new_select = NULL;
2481 bool did = false;
2483 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
2484 items != NULL;
2485 items = items->next) {
2487 SPItem *item = (SPItem *) items->data;
2489 SPStyle *style = SP_OBJECT_STYLE(item);
2491 if (!style || !style->fill.isPaintserver())
2492 continue;
2494 SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
2496 if (!SP_IS_PATTERN(server))
2497 continue;
2499 did = true;
2501 SPPattern *pattern = pattern_getroot(SP_PATTERN(server));
2503 Geom::Matrix pat_transform = to_2geom(pattern_patternTransform(SP_PATTERN(server)));
2504 pat_transform *= item->transform;
2506 for (SPObject *child = sp_object_first_child(SP_OBJECT(pattern)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2507 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2508 SPItem *i = SP_ITEM(desktop->currentLayer()->appendChildRepr(copy));
2510 // FIXME: relink clones to the new canvas objects
2511 // use SPObject::setid when mental finishes it to steal ids of
2513 // this is needed to make sure the new item has curve (simply requestDisplayUpdate does not work)
2514 sp_document_ensure_up_to_date(doc);
2516 Geom::Matrix transform( i->transform * pat_transform );
2517 sp_item_write_transform(i, SP_OBJECT_REPR(i), transform);
2519 new_select = g_slist_prepend(new_select, i);
2520 }
2522 SPCSSAttr *css = sp_repr_css_attr_new();
2523 sp_repr_css_set_property(css, "fill", "none");
2524 sp_repr_css_change(SP_OBJECT_REPR(item), css, "style");
2525 }
2527 if (!did) {
2528 desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, _("<b>No pattern fills</b> in the selection."));
2529 } else {
2530 sp_document_done(sp_desktop_document(desktop), SP_VERB_EDIT_UNTILE,
2531 _("Pattern to objects"));
2532 selection->setList(new_select);
2533 }
2534 }
2536 void
2537 sp_selection_get_export_hints(Inkscape::Selection *selection, char const **filename, float *xdpi, float *ydpi)
2538 {
2539 if (selection->isEmpty()) {
2540 return;
2541 }
2543 GSList const *reprlst = selection->reprList();
2544 bool filename_search = TRUE;
2545 bool xdpi_search = TRUE;
2546 bool ydpi_search = TRUE;
2548 for (; reprlst != NULL &&
2549 filename_search &&
2550 xdpi_search &&
2551 ydpi_search;
2552 reprlst = reprlst->next) {
2553 gchar const *dpi_string;
2554 Inkscape::XML::Node * repr = (Inkscape::XML::Node *)reprlst->data;
2556 if (filename_search) {
2557 *filename = repr->attribute("inkscape:export-filename");
2558 if (*filename != NULL)
2559 filename_search = FALSE;
2560 }
2562 if (xdpi_search) {
2563 dpi_string = NULL;
2564 dpi_string = repr->attribute("inkscape:export-xdpi");
2565 if (dpi_string != NULL) {
2566 *xdpi = atof(dpi_string);
2567 xdpi_search = FALSE;
2568 }
2569 }
2571 if (ydpi_search) {
2572 dpi_string = NULL;
2573 dpi_string = repr->attribute("inkscape:export-ydpi");
2574 if (dpi_string != NULL) {
2575 *ydpi = atof(dpi_string);
2576 ydpi_search = FALSE;
2577 }
2578 }
2579 }
2580 }
2582 void
2583 sp_document_get_export_hints(SPDocument *doc, char const **filename, float *xdpi, float *ydpi)
2584 {
2585 Inkscape::XML::Node * repr = sp_document_repr_root(doc);
2586 gchar const *dpi_string;
2588 *filename = repr->attribute("inkscape:export-filename");
2590 dpi_string = NULL;
2591 dpi_string = repr->attribute("inkscape:export-xdpi");
2592 if (dpi_string != NULL) {
2593 *xdpi = atof(dpi_string);
2594 }
2596 dpi_string = NULL;
2597 dpi_string = repr->attribute("inkscape:export-ydpi");
2598 if (dpi_string != NULL) {
2599 *ydpi = atof(dpi_string);
2600 }
2601 }
2603 void
2604 sp_selection_create_bitmap_copy(SPDesktop *desktop)
2605 {
2606 if (desktop == NULL)
2607 return;
2609 SPDocument *document = sp_desktop_document(desktop);
2610 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
2612 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2614 // check if something is selected
2615 if (selection->isEmpty()) {
2616 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to make a bitmap copy."));
2617 return;
2618 }
2620 desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Rendering bitmap..."));
2621 // set "busy" cursor
2622 desktop->setWaitingCursor();
2624 // Get the bounding box of the selection
2625 NRRect bbox;
2626 sp_document_ensure_up_to_date(document);
2627 selection->bounds(&bbox);
2628 if (NR_RECT_DFLS_TEST_EMPTY(&bbox)) {
2629 desktop->clearWaitingCursor();
2630 return; // exceptional situation, so not bother with a translatable error message, just quit quietly
2631 }
2633 // List of the items to show; all others will be hidden
2634 GSList *items = g_slist_copy((GSList *) selection->itemList());
2636 // Sort items so that the topmost comes last
2637 items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
2639 // Generate a random value from the current time (you may create bitmap from the same object(s)
2640 // multiple times, and this is done so that they don't clash)
2641 GTimeVal cu;
2642 g_get_current_time(&cu);
2643 guint current = (int) (cu.tv_sec * 1000000 + cu.tv_usec) % 1024;
2645 // Create the filename.
2646 gchar *const basename = g_strdup_printf("%s-%s-%u.png",
2647 document->name,
2648 SP_OBJECT_REPR(items->data)->attribute("id"),
2649 current);
2650 // Imagemagick is known not to handle spaces in filenames, so we replace anything but letters,
2651 // digits, and a few other chars, with "_"
2652 g_strcanon(basename, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.=+~$#@^&!?", '_');
2654 // Build the complete path by adding document base dir, if set, otherwise home dir
2655 gchar * directory = NULL;
2656 if (SP_DOCUMENT_URI(document)) {
2657 directory = g_dirname(SP_DOCUMENT_URI(document));
2658 }
2659 if (directory == NULL) {
2660 directory = homedir_path(NULL);
2661 }
2662 gchar *filepath = g_build_filename(directory, basename, NULL);
2664 //g_print("%s\n", filepath);
2666 // Remember parent and z-order of the topmost one
2667 gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
2668 SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
2669 Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
2671 // Calculate resolution
2672 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2673 double res;
2674 int const prefs_res = prefs->getInt("/options/createbitmap/resolution", 0);
2675 int const prefs_min = prefs->getInt("/options/createbitmap/minsize", 0);
2676 if (0 < prefs_res) {
2677 // If it's given explicitly in prefs, take it
2678 res = prefs_res;
2679 } else if (0 < prefs_min) {
2680 // If minsize is given, look up minimum bitmap size (default 250 pixels) and calculate resolution from it
2681 res = PX_PER_IN * prefs_min / MIN((bbox.x1 - bbox.x0), (bbox.y1 - bbox.y0));
2682 } else {
2683 float hint_xdpi = 0, hint_ydpi = 0;
2684 char const *hint_filename;
2685 // take resolution hint from the selected objects
2686 sp_selection_get_export_hints(selection, &hint_filename, &hint_xdpi, &hint_ydpi);
2687 if (hint_xdpi != 0) {
2688 res = hint_xdpi;
2689 } else {
2690 // take resolution hint from the document
2691 sp_document_get_export_hints(document, &hint_filename, &hint_xdpi, &hint_ydpi);
2692 if (hint_xdpi != 0) {
2693 res = hint_xdpi;
2694 } else {
2695 // if all else fails, take the default 90 dpi
2696 res = PX_PER_IN;
2697 }
2698 }
2699 }
2701 // The width and height of the bitmap in pixels
2702 unsigned width = (unsigned) floor((bbox.x1 - bbox.x0) * res / PX_PER_IN);
2703 unsigned height =(unsigned) floor((bbox.y1 - bbox.y0) * res / PX_PER_IN);
2705 // Find out if we have to run an external filter
2706 gchar const *run = NULL;
2707 Glib::ustring filter = prefs->getString("/options/createbitmap/filter");
2708 if (!filter.empty()) {
2709 // filter command is given;
2710 // see if we have a parameter to pass to it
2711 Glib::ustring param1 = prefs->getString("/options/createbitmap/filter_param1");
2712 if (!param1.empty()) {
2713 if (param1[param1.length() - 1] == '%') {
2714 // if the param string ends with %, interpret it as a percentage of the image's max dimension
2715 gchar p1[256];
2716 g_ascii_dtostr(p1, 256, ceil(g_ascii_strtod(param1.data(), NULL) * MAX(width, height) / 100));
2717 // the first param is always the image filename, the second is param1
2718 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, p1);
2719 } else {
2720 // otherwise pass the param1 unchanged
2721 run = g_strdup_printf("%s \"%s\" %s", filter.data(), filepath, param1.data());
2722 }
2723 } else {
2724 // run without extra parameter
2725 run = g_strdup_printf("%s \"%s\"", filter.data(), filepath);
2726 }
2727 }
2729 // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
2730 Geom::Matrix eek(sp_item_i2d_affine(SP_ITEM(parent_object)));
2731 Geom::Matrix t;
2733 double shift_x = bbox.x0;
2734 double shift_y = bbox.y1;
2735 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2736 shift_x = round(shift_x);
2737 shift_y = -round(-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
2738 }
2739 t = Geom::Scale(1, -1) * Geom::Translate(shift_x, shift_y) * eek.inverse();
2741 // Do the export
2742 sp_export_png_file(document, filepath,
2743 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
2744 width, height, res, res,
2745 (guint32) 0xffffff00,
2746 NULL, NULL,
2747 true, /*bool force_overwrite,*/
2748 items);
2750 g_slist_free(items);
2752 // Run filter, if any
2753 if (run) {
2754 g_print("Running external filter: %s\n", run);
2755 int retval;
2756 retval = system(run);
2757 }
2759 // Import the image back
2760 GdkPixbuf *pb = gdk_pixbuf_new_from_file(filepath, NULL);
2761 if (pb) {
2762 // Create the repr for the image
2763 Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
2764 {
2765 repr->setAttribute("sodipodi:absref", filepath);
2766 gchar *abs_base = Inkscape::XML::calc_abs_doc_base(document->base);
2767 repr->setAttribute("xlink:href", sp_relative_path_from_path(filepath, abs_base));
2768 g_free(abs_base);
2769 }
2770 if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
2771 sp_repr_set_svg_double(repr, "width", width);
2772 sp_repr_set_svg_double(repr, "height", height);
2773 } else {
2774 sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
2775 sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
2776 }
2778 // Write transform
2779 gchar *c=sp_svg_transform_write(t);
2780 repr->setAttribute("transform", c);
2781 g_free(c);
2783 // add the new repr to the parent
2784 parent->appendChild(repr);
2786 // move to the saved position
2787 repr->setPosition(pos > 0 ? pos + 1 : 1);
2789 // Set selection to the new image
2790 selection->clear();
2791 selection->add(repr);
2793 // Clean up
2794 Inkscape::GC::release(repr);
2795 gdk_pixbuf_unref(pb);
2797 // Complete undoable transaction
2798 sp_document_done(document, SP_VERB_SELECTION_CREATE_BITMAP,
2799 _("Create bitmap"));
2800 }
2802 desktop->clearWaitingCursor();
2804 g_free(basename);
2805 g_free(filepath);
2806 }
2808 /**
2809 * \brief Creates a mask or clipPath from selection
2810 * Two different modes:
2811 * if applyToLayer, all selection is moved to DEFS as mask/clippath
2812 * and is applied to current layer
2813 * otherwise, topmost object is used as mask for other objects
2814 * If \a apply_clip_path parameter is true, clipPath is created, otherwise mask
2815 *
2816 */
2817 void
2818 sp_selection_set_mask(SPDesktop *desktop, bool apply_clip_path, bool apply_to_layer)
2819 {
2820 if (desktop == NULL)
2821 return;
2823 SPDocument *doc = sp_desktop_document(desktop);
2824 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2826 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2828 // check if something is selected
2829 bool is_empty = selection->isEmpty();
2830 if ( apply_to_layer && is_empty) {
2831 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to create clippath or mask from."));
2832 return;
2833 } else if (!apply_to_layer && ( is_empty || NULL == selection->itemList()->next )) {
2834 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select mask object and <b>object(s)</b> to apply clippath or mask to."));
2835 return;
2836 }
2838 // FIXME: temporary patch to prevent crash!
2839 // Remove this when bboxes are fixed to not blow up on an item clipped/masked with its own clone
2840 bool clone_with_original = selection_contains_both_clone_and_original(selection);
2841 if (clone_with_original) {
2842 return; // in this version, you cannot clip/mask an object with its own clone
2843 }
2844 // /END FIXME
2846 sp_document_ensure_up_to_date(doc);
2848 GSList *items = g_slist_copy((GSList *) selection->itemList());
2850 items = g_slist_sort(items, (GCompareFunc) sp_object_compare_position);
2852 // create a list of duplicates
2853 GSList *mask_items = NULL;
2854 GSList *apply_to_items = NULL;
2855 GSList *items_to_delete = NULL;
2856 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2857 bool topmost = prefs->getBool("/options/maskobject/topmost", true);
2858 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2860 if (apply_to_layer) {
2861 // all selected items are used for mask, which is applied to a layer
2862 apply_to_items = g_slist_prepend(apply_to_items, desktop->currentLayer());
2864 for (GSList *i = items; i != NULL; i = i->next) {
2865 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2866 mask_items = g_slist_prepend(mask_items, dup);
2868 if (remove_original) {
2869 SPObject *item = SP_OBJECT(i->data);
2870 items_to_delete = g_slist_prepend(items_to_delete, item);
2871 }
2872 }
2873 } else if (!topmost) {
2874 // topmost item is used as a mask, which is applied to other items in a selection
2875 GSList *i = items;
2876 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2877 mask_items = g_slist_prepend(mask_items, dup);
2879 if (remove_original) {
2880 SPObject *item = SP_OBJECT(i->data);
2881 items_to_delete = g_slist_prepend(items_to_delete, item);
2882 }
2884 for (i = i->next; i != NULL; i = i->next) {
2885 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2886 }
2887 } else {
2888 GSList *i = NULL;
2889 for (i = items; NULL != i->next; i = i->next) {
2890 apply_to_items = g_slist_prepend(apply_to_items, i->data);
2891 }
2893 Inkscape::XML::Node *dup = (SP_OBJECT_REPR(i->data))->duplicate(xml_doc);
2894 mask_items = g_slist_prepend(mask_items, dup);
2896 if (remove_original) {
2897 SPObject *item = SP_OBJECT(i->data);
2898 items_to_delete = g_slist_prepend(items_to_delete, item);
2899 }
2900 }
2902 g_slist_free(items);
2903 items = NULL;
2905 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2906 for (GSList *i = apply_to_items; NULL != i; i = i->next) {
2907 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2908 // inverted object transform should be applied to a mask object,
2909 // as mask is calculated in user space (after applying transform)
2910 Geom::Matrix maskTransform(item->transform.inverse());
2912 GSList *mask_items_dup = NULL;
2913 for (GSList *mask_item = mask_items; NULL != mask_item; mask_item = mask_item->next) {
2914 Inkscape::XML::Node *dup = reinterpret_cast<Inkscape::XML::Node *>(mask_item->data)->duplicate(xml_doc);
2915 mask_items_dup = g_slist_prepend(mask_items_dup, dup);
2916 }
2918 gchar const *mask_id = NULL;
2919 if (apply_clip_path) {
2920 mask_id = sp_clippath_create(mask_items_dup, doc, &maskTransform);
2921 } else {
2922 mask_id = sp_mask_create(mask_items_dup, doc, &maskTransform);
2923 }
2925 g_slist_free(mask_items_dup);
2926 mask_items_dup = NULL;
2928 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, g_strdup_printf("url(#%s)", mask_id));
2929 }
2931 g_slist_free(mask_items);
2932 g_slist_free(apply_to_items);
2934 for (GSList *i = items_to_delete; NULL != i; i = i->next) {
2935 SPObject *item = SP_OBJECT(i->data);
2936 item->deleteObject(false);
2937 }
2938 g_slist_free(items_to_delete);
2940 if (apply_clip_path)
2941 sp_document_done(doc, SP_VERB_OBJECT_SET_CLIPPATH, _("Set clipping path"));
2942 else
2943 sp_document_done(doc, SP_VERB_OBJECT_SET_MASK, _("Set mask"));
2944 }
2946 void sp_selection_unset_mask(SPDesktop *desktop, bool apply_clip_path) {
2947 if (desktop == NULL)
2948 return;
2950 SPDocument *doc = sp_desktop_document(desktop);
2951 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
2952 Inkscape::Selection *selection = sp_desktop_selection(desktop);
2954 // check if something is selected
2955 if (selection->isEmpty()) {
2956 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to remove clippath or mask from."));
2957 return;
2958 }
2960 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
2961 bool remove_original = prefs->getBool("/options/maskobject/remove", true);
2962 sp_document_ensure_up_to_date(doc);
2964 gchar const *attributeName = apply_clip_path ? "clip-path" : "mask";
2965 std::map<SPObject*,SPItem*> referenced_objects;
2966 // SPObject* refers to a group containing the clipped path or mask itself,
2967 // whereas SPItem* refers to the item being clipped or masked
2968 for (GSList const *i = selection->itemList(); NULL != i; i = i->next) {
2969 if (remove_original) {
2970 // remember referenced mask/clippath, so orphaned masks can be moved back to document
2971 SPItem *item = reinterpret_cast<SPItem *>(i->data);
2972 Inkscape::URIReference *uri_ref = NULL;
2974 if (apply_clip_path) {
2975 uri_ref = item->clip_ref;
2976 } else {
2977 uri_ref = item->mask_ref;
2978 }
2980 // collect distinct mask object (and associate with item to apply transform)
2981 if (NULL != uri_ref && NULL != uri_ref->getObject()) {
2982 referenced_objects[uri_ref->getObject()] = item;
2983 }
2984 }
2986 SP_OBJECT_REPR(i->data)->setAttribute(attributeName, "none");
2987 }
2989 // restore mask objects into a document
2990 for ( std::map<SPObject*,SPItem*>::iterator it = referenced_objects.begin() ; it != referenced_objects.end() ; ++it) {
2991 SPObject *obj = (*it).first; // Group containing the clipped paths or masks
2992 GSList *items_to_move = NULL;
2993 for (SPObject *child = sp_object_first_child(obj) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
2994 // Collect all clipped paths and masks within a single group
2995 Inkscape::XML::Node *copy = SP_OBJECT_REPR(child)->duplicate(xml_doc);
2996 items_to_move = g_slist_prepend(items_to_move, copy);
2997 }
2999 if (!obj->isReferenced()) {
3000 // delete from defs if no other object references this mask
3001 obj->deleteObject(false);
3002 }
3004 // remember parent and position of the item to which the clippath/mask was applied
3005 Inkscape::XML::Node *parent = SP_OBJECT_REPR((*it).second)->parent();
3006 gint pos = SP_OBJECT_REPR((*it).second)->position();
3008 // Iterate through all clipped paths / masks
3009 for (GSList *i = items_to_move; NULL != i; i = i->next) {
3010 Inkscape::XML::Node *repr = (Inkscape::XML::Node *)i->data;
3012 // insert into parent, restore pos
3013 parent->appendChild(repr);
3014 repr->setPosition((pos + 1) > 0 ? (pos + 1) : 0);
3016 SPItem *mask_item = (SPItem *) sp_desktop_document(desktop)->getObjectByRepr(repr);
3017 selection->add(repr);
3019 // transform mask, so it is moved the same spot where mask was applied
3020 Geom::Matrix transform(mask_item->transform);
3021 transform *= (*it).second->transform;
3022 sp_item_write_transform(mask_item, SP_OBJECT_REPR(mask_item), transform);
3023 }
3025 g_slist_free(items_to_move);
3026 }
3028 if (apply_clip_path)
3029 sp_document_done(doc, SP_VERB_OBJECT_UNSET_CLIPPATH, _("Release clipping path"));
3030 else
3031 sp_document_done(doc, SP_VERB_OBJECT_UNSET_MASK, _("Release mask"));
3032 }
3034 /**
3035 * \param with_margins margins defined in the xml under <sodipodi:namedview>
3036 * "fit-margin-..." attributes. See SPDocument::fitToRect.
3037 * \return true if an undoable change should be recorded.
3038 */
3039 bool
3040 fit_canvas_to_selection(SPDesktop *desktop, bool with_margins)
3041 {
3042 g_return_val_if_fail(desktop != NULL, false);
3043 SPDocument *doc = sp_desktop_document(desktop);
3045 g_return_val_if_fail(doc != NULL, false);
3046 g_return_val_if_fail(desktop->selection != NULL, false);
3048 if (desktop->selection->isEmpty()) {
3049 desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to fit canvas to."));
3050 return false;
3051 }
3052 Geom::OptRect const bbox(desktop->selection->bounds());
3053 if (bbox) {
3054 doc->fitToRect(*bbox, with_margins);
3055 return true;
3056 } else {
3057 return false;
3058 }
3059 }
3061 /**
3062 * Fit canvas to the bounding box of the selection, as an undoable action.
3063 */
3064 void
3065 verb_fit_canvas_to_selection(SPDesktop *const desktop)
3066 {
3067 if (fit_canvas_to_selection(desktop)) {
3068 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION,
3069 _("Fit Page to Selection"));
3070 }
3071 }
3073 /**
3074 * \param with_margins margins defined in the xml under <sodipodi:namedview>
3075 * "fit-margin-..." attributes. See SPDocument::fitToRect.
3076 */
3077 bool
3078 fit_canvas_to_drawing(SPDocument *doc, bool with_margins)
3079 {
3080 g_return_val_if_fail(doc != NULL, false);
3082 sp_document_ensure_up_to_date(doc);
3083 SPItem const *const root = SP_ITEM(doc->root);
3084 Geom::OptRect const bbox(root->getBounds(sp_item_i2d_affine(root)));
3085 if (bbox) {
3086 doc->fitToRect(*bbox, with_margins);
3087 return true;
3088 } else {
3089 return false;
3090 }
3091 }
3093 void
3094 verb_fit_canvas_to_drawing(SPDesktop *desktop)
3095 {
3096 if (fit_canvas_to_drawing(sp_desktop_document(desktop))) {
3097 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_DRAWING,
3098 _("Fit Page to Drawing"));
3099 }
3100 }
3102 /**
3103 * Fits canvas to selection or drawing with margins from <sodipodi:namedview>
3104 * "fit-margin-..." attributes. See SPDocument::fitToRect and
3105 * ui/dialog/page-sizer.
3106 */
3107 void fit_canvas_to_selection_or_drawing(SPDesktop *desktop) {
3108 g_return_if_fail(desktop != NULL);
3109 SPDocument *doc = sp_desktop_document(desktop);
3111 g_return_if_fail(doc != NULL);
3112 g_return_if_fail(desktop->selection != NULL);
3114 bool const changed = ( desktop->selection->isEmpty()
3115 ? fit_canvas_to_drawing(doc, true)
3116 : fit_canvas_to_selection(desktop, true) );
3117 if (changed) {
3118 sp_document_done(sp_desktop_document(desktop), SP_VERB_FIT_CANVAS_TO_SELECTION_OR_DRAWING,
3119 _("Fit Page to Selection or Drawing"));
3120 }
3121 };
3123 static void itemtree_map(void (*f)(SPItem *, SPDesktop *), SPObject *root, SPDesktop *desktop) {
3124 // don't operate on layers
3125 if (SP_IS_ITEM(root) && !desktop->isLayer(SP_ITEM(root))) {
3126 f(SP_ITEM(root), desktop);
3127 }
3128 for ( SPObject::SiblingIterator iter = root->firstChild() ; iter ; ++iter ) {
3129 //don't recurse into locked layers
3130 if (!(SP_IS_ITEM(&*iter) && desktop->isLayer(SP_ITEM(&*iter)) && SP_ITEM(&*iter)->isLocked())) {
3131 itemtree_map(f, iter, desktop);
3132 }
3133 }
3134 }
3136 static void unlock(SPItem *item, SPDesktop */*desktop*/) {
3137 if (item->isLocked()) {
3138 item->setLocked(FALSE);
3139 }
3140 }
3142 static void unhide(SPItem *item, SPDesktop *desktop) {
3143 if (desktop->itemIsHidden(item)) {
3144 item->setExplicitlyHidden(FALSE);
3145 }
3146 }
3148 static void process_all(void (*f)(SPItem *, SPDesktop *), SPDesktop *dt, bool layer_only) {
3149 if (!dt) return;
3151 SPObject *root;
3152 if (layer_only) {
3153 root = dt->currentLayer();
3154 } else {
3155 root = dt->currentRoot();
3156 }
3158 itemtree_map(f, root, dt);
3159 }
3161 void unlock_all(SPDesktop *dt) {
3162 process_all(&unlock, dt, true);
3163 }
3165 void unlock_all_in_all_layers(SPDesktop *dt) {
3166 process_all(&unlock, dt, false);
3167 }
3169 void unhide_all(SPDesktop *dt) {
3170 process_all(&unhide, dt, true);
3171 }
3173 void unhide_all_in_all_layers(SPDesktop *dt) {
3174 process_all(&unhide, dt, false);
3175 }
3178 /*
3179 Local Variables:
3180 mode:c++
3181 c-file-style:"stroustrup"
3182 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
3183 indent-tabs-mode:nil
3184 fill-column:99
3185 End:
3186 */
3187 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :