Code

Cherry pick node duplication from 0.48 stable
[inkscape.git] / src / ui / tool / multi-path-manipulator.cpp
1 /** @file
2  * Multi path manipulator - implementation
3  */
4 /* Authors:
5  *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
6  *
7  * Copyright (C) 2009 Authors
8  * Released under GNU GPL, read the file 'COPYING' for more information
9  */
11 #include <boost/shared_ptr.hpp>
12 #include <glib.h>
13 #include <glibmm/i18n.h>
14 #include "desktop.h"
15 #include "desktop-handles.h"
16 #include "document.h"
17 #include "live_effects/lpeobject.h"
18 #include "message-stack.h"
19 #include "preferences.h"
20 #include "sp-path.h"
21 #include "ui/tool/control-point-selection.h"
22 #include "ui/tool/event-utils.h"
23 #include "ui/tool/node.h"
24 #include "ui/tool/multi-path-manipulator.h"
25 #include "ui/tool/path-manipulator.h"
26 #include "util/unordered-containers.h"
28 #ifdef USE_GNU_HASHES
29 namespace __gnu_cxx {
30 template<>
31 struct hash<Inkscape::UI::NodeList::iterator> {
32     size_t operator()(Inkscape::UI::NodeList::iterator const &n) const {
33         return reinterpret_cast<size_t>(n.ptr());
34     }
35 };
36 } // namespace __gnu_cxx
37 #endif // USE_GNU_HASHES
39 namespace Inkscape {
40 namespace UI {
42 namespace {
44 struct hash_nodelist_iterator
45     : public std::unary_function<NodeList::iterator, std::size_t>
46 {
47     std::size_t operator()(NodeList::iterator i) const {
48         return INK_HASH<NodeList::iterator::pointer>()(&*i);
49     }
50 };
52 typedef std::pair<NodeList::iterator, NodeList::iterator> IterPair;
53 typedef std::vector<IterPair> IterPairList;
54 typedef INK_UNORDERED_SET<NodeList::iterator, hash_nodelist_iterator> IterSet;
55 typedef std::multimap<double, IterPair> DistanceMap;
56 typedef std::pair<double, IterPair> DistanceMapItem;
58 /** Find pairs of selected endnodes suitable for joining. */
59 void find_join_iterators(ControlPointSelection &sel, IterPairList &pairs)
60 {
61     IterSet join_iters;
62     DistanceMap dists;
64     // find all endnodes in selection
65     for (ControlPointSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
66         Node *node = dynamic_cast<Node*>(*i);
67         if (!node) continue;
68         NodeList::iterator iter = NodeList::get_iterator(node);
69         if (!iter.next() || !iter.prev()) join_iters.insert(iter);
70     }
72     if (join_iters.size() < 2) return;
74     // Below we find the closest pairs. The algorithm is O(N^3).
75     // We can go down to O(N^2 log N) by using O(N^2) memory, by putting all pairs
76     // with their distances in a multimap (not worth it IMO).
77     while (join_iters.size() >= 2) {
78         double closest = DBL_MAX;
79         IterPair closest_pair;
80         for (IterSet::iterator i = join_iters.begin(); i != join_iters.end(); ++i) {
81             for (IterSet::iterator j = join_iters.begin(); j != i; ++j) {
82                 double dist = Geom::distance(**i, **j);
83                 if (dist < closest) {
84                     closest = dist;
85                     closest_pair = std::make_pair(*i, *j);
86                 }
87             }
88         }
89         pairs.push_back(closest_pair);
90         join_iters.erase(closest_pair.first);
91         join_iters.erase(closest_pair.second);
92     }
93 }
95 /** After this function, first should be at the end of path and second at the beginnning.
96  * @returns True if the nodes are in the same subpath */
97 bool prepare_join(IterPair &join_iters)
98 {
99     if (&NodeList::get(join_iters.first) == &NodeList::get(join_iters.second)) {
100         if (join_iters.first.next()) // if first is begin, swap the iterators
101             std::swap(join_iters.first, join_iters.second);
102         return true;
103     }
105     NodeList &sp_first = NodeList::get(join_iters.first);
106     NodeList &sp_second = NodeList::get(join_iters.second);
107     if (join_iters.first.next()) { // first is begin
108         if (join_iters.second.next()) { // second is begin
109             sp_first.reverse();
110         } else { // second is end
111             std::swap(join_iters.first, join_iters.second);
112         }
113     } else { // first is end
114         if (join_iters.second.next()) { // second is begin
115             // do nothing
116         } else { // second is end
117             sp_second.reverse();
118         }
119     }
120     return false;
122 } // anonymous namespace
125 MultiPathManipulator::MultiPathManipulator(PathSharedData &data, sigc::connection &chg)
126     : PointManipulator(data.node_data.desktop, *data.node_data.selection)
127     , _path_data(data)
128     , _changed(chg)
130     _selection.signal_commit.connect(
131         sigc::mem_fun(*this, &MultiPathManipulator::_commit));
132     _selection.signal_point_changed.connect(
133         sigc::hide( sigc::hide(
134             signal_coords_changed.make_slot())));
137 MultiPathManipulator::~MultiPathManipulator()
139     _mmap.clear();
142 /** Remove empty manipulators. */
143 void MultiPathManipulator::cleanup()
145     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ) {
146         if (i->second->empty()) _mmap.erase(i++);
147         else ++i;
148     }
151 /** @brief Change the set of items to edit.
152  *
153  * This method attempts to preserve as much of the state as possible. */
154 void MultiPathManipulator::setItems(std::set<ShapeRecord> const &s)
156     std::set<ShapeRecord> shapes(s);
158     // iterate over currently edited items, modifying / removing them as necessary
159     for (MapType::iterator i = _mmap.begin(); i != _mmap.end();) {
160         std::set<ShapeRecord>::iterator si = shapes.find(i->first);
161         if (si == shapes.end()) {
162             // This item is no longer supposed to be edited - remove its manipulator
163             _mmap.erase(i++);
164         } else {
165             ShapeRecord const &sr = i->first;
166             ShapeRecord const &sr_new = *si;
167             // if the shape record differs, replace the key only and modify other values
168             if (sr.edit_transform != sr_new.edit_transform ||
169                 sr.role != sr_new.role)
170             {
171                 boost::shared_ptr<PathManipulator> hold(i->second);
172                 if (sr.edit_transform != sr_new.edit_transform)
173                     hold->setControlsTransform(sr_new.edit_transform);
174                 if (sr.role != sr_new.role) {
175                     //hold->setOutlineColor(_getOutlineColor(sr_new.role));
176                 }
177                 _mmap.erase(sr);
178                 _mmap.insert(std::make_pair(sr_new, hold));
179             }
180             shapes.erase(si); // remove the processed record
181             ++i;
182         }
183     }
185     // add newly selected items
186     for (std::set<ShapeRecord>::iterator i = shapes.begin(); i != shapes.end(); ++i) {
187         ShapeRecord const &r = *i;
188         if (!SP_IS_PATH(r.item) && !IS_LIVEPATHEFFECT(r.item)) continue;
189         boost::shared_ptr<PathManipulator> newpm(new PathManipulator(*this, (SPPath*) r.item,
190             r.edit_transform, _getOutlineColor(r.role), r.lpe_key));
191         newpm->showHandles(_show_handles);
192         // always show outlines for clips and masks
193         newpm->showOutline(_show_outline || r.role != SHAPE_ROLE_NORMAL);
194         newpm->showPathDirection(_show_path_direction);
195         newpm->setLiveOutline(_live_outline);
196         newpm->setLiveObjects(_live_objects);
197         _mmap.insert(std::make_pair(r, newpm));
198     }
201 void MultiPathManipulator::selectSubpaths()
203     if (_selection.empty()) {
204         _selection.selectAll();
205     } else {
206         invokeForAll(&PathManipulator::selectSubpaths);
207     }
210 void MultiPathManipulator::shiftSelection(int dir)
212     invokeForAll(&PathManipulator::shiftSelection, dir);
215 void MultiPathManipulator::invertSelectionInSubpaths()
217     invokeForAll(&PathManipulator::invertSelectionInSubpaths);
220 void MultiPathManipulator::setNodeType(NodeType type)
222     if (_selection.empty()) return;
223     for (ControlPointSelection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
224         Node *node = dynamic_cast<Node*>(*i);
225         if (node) node->setType(type);
226     }
227     _done(_("Change node type"));
230 void MultiPathManipulator::setSegmentType(SegmentType type)
232     if (_selection.empty()) return;
233     invokeForAll(&PathManipulator::setSegmentType, type);
234     if (type == SEGMENT_STRAIGHT) {
235         _done(_("Straighten segments"));
236     } else {
237         _done(_("Make segments curves"));
238     }
241 void MultiPathManipulator::insertNodes()
243     invokeForAll(&PathManipulator::insertNodes);
244     _done(_("Add nodes"));
247 void MultiPathManipulator::duplicateNodes()
249     invokeForAll(&PathManipulator::duplicateNodes);
250     _done(_("Duplicate nodes"));
253 void MultiPathManipulator::joinNodes()
255     invokeForAll(&PathManipulator::hideDragPoint);
256     // Node join has two parts. In the first one we join two subpaths by fusing endpoints
257     // into one. In the second we fuse nodes in each subpath.
258     IterPairList joins;
259     NodeList::iterator preserve_pos;
260     Node *mouseover_node = dynamic_cast<Node*>(ControlPoint::mouseovered_point);
261     if (mouseover_node) {
262         preserve_pos = NodeList::get_iterator(mouseover_node);
263     }
264     find_join_iterators(_selection, joins);
266     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
267         bool same_path = prepare_join(*i);
268         NodeList &sp_first = NodeList::get(i->first);
269         NodeList &sp_second = NodeList::get(i->second);
270         i->first->setType(NODE_CUSP, false);
272         Geom::Point joined_pos, pos_handle_front, pos_handle_back;
273         pos_handle_front = *i->second->front();
274         pos_handle_back = *i->first->back();
276         // When we encounter the mouseover node, we unset the iterator - it will be invalidated
277         if (i->first == preserve_pos) {
278             joined_pos = *i->first;
279             preserve_pos = NodeList::iterator();
280         } else if (i->second == preserve_pos) {
281             joined_pos = *i->second;
282             preserve_pos = NodeList::iterator();
283         } else {
284             joined_pos = Geom::middle_point(*i->first, *i->second);
285         }
287         // if the handles aren't degenerate, don't move them
288         i->first->move(joined_pos);
289         Node *joined_node = i->first.ptr();
290         if (!i->second->front()->isDegenerate()) {
291             joined_node->front()->setPosition(pos_handle_front);
292         }
293         if (!i->first->back()->isDegenerate()) {
294             joined_node->back()->setPosition(pos_handle_back);
295         }
296         sp_second.erase(i->second);
298         if (same_path) {
299             sp_first.setClosed(true);
300         } else {
301             sp_first.splice(sp_first.end(), sp_second);
302             sp_second.kill();
303         }
304         _selection.insert(i->first.ptr());
305     }
307     if (joins.empty()) {
308         // Second part replaces contiguous selections of nodes with single nodes
309         invokeForAll(&PathManipulator::weldNodes, preserve_pos);
310     }
312     _doneWithCleanup(_("Join nodes"));
315 void MultiPathManipulator::breakNodes()
317     if (_selection.empty()) return;
318     invokeForAll(&PathManipulator::breakNodes);
319     _done(_("Break nodes"));
322 void MultiPathManipulator::deleteNodes(bool keep_shape)
324     if (_selection.empty()) return;
325     invokeForAll(&PathManipulator::deleteNodes, keep_shape);
326     _doneWithCleanup(_("Delete nodes"));
329 /** Join selected endpoints to create segments. */
330 void MultiPathManipulator::joinSegments()
332     IterPairList joins;
333     find_join_iterators(_selection, joins);
335     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
336         bool same_path = prepare_join(*i);
337         NodeList &sp_first = NodeList::get(i->first);
338         NodeList &sp_second = NodeList::get(i->second);
339         i->first->setType(NODE_CUSP, false);
340         i->second->setType(NODE_CUSP, false);
341         if (same_path) {
342             sp_first.setClosed(true);
343         } else {
344             sp_first.splice(sp_first.end(), sp_second);
345             sp_second.kill();
346         }
347     }
349     if (joins.empty()) {
350         invokeForAll(&PathManipulator::weldSegments);
351     }
352     _doneWithCleanup("Join segments");
355 void MultiPathManipulator::deleteSegments()
357     if (_selection.empty()) return;
358     invokeForAll(&PathManipulator::deleteSegments);
359     _doneWithCleanup("Delete segments");
362 void MultiPathManipulator::alignNodes(Geom::Dim2 d)
364     _selection.align(d);
365     if (d == Geom::X) {
366         _done("Align nodes to a horizontal line");
367     } else {
368         _done("Align nodes to a vertical line");
369     }
372 void MultiPathManipulator::distributeNodes(Geom::Dim2 d)
374     _selection.distribute(d);
375     if (d == Geom::X) {
376         _done("Distrubute nodes horizontally");
377     } else {
378         _done("Distribute nodes vertically");
379     }
382 void MultiPathManipulator::reverseSubpaths()
384     if (_selection.empty()) {
385         invokeForAll(&PathManipulator::reverseSubpaths, false);
386         _done("Reverse subpaths");
387     } else {
388         invokeForAll(&PathManipulator::reverseSubpaths, true);
389         _done("Reverse selected subpaths");
390     }
393 void MultiPathManipulator::move(Geom::Point const &delta)
395     _selection.transform(Geom::Translate(delta));
396     _done("Move nodes");
399 void MultiPathManipulator::showOutline(bool show)
401     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
402         // always show outlines for clipping paths and masks
403         i->second->showOutline(show || i->first.role != SHAPE_ROLE_NORMAL);
404     }
405     _show_outline = show;
408 void MultiPathManipulator::showHandles(bool show)
410     invokeForAll(&PathManipulator::showHandles, show);
411     _show_handles = show;
414 void MultiPathManipulator::showPathDirection(bool show)
416     invokeForAll(&PathManipulator::showPathDirection, show);
417     _show_path_direction = show;
420 /** @brief Set live outline update status
421  * When set to true, outline will be updated continuously when dragging
422  * or transforming nodes. Otherwise it will only update when changes are committed
423  * to XML. */
424 void MultiPathManipulator::setLiveOutline(bool set)
426     invokeForAll(&PathManipulator::setLiveOutline, set);
427     _live_outline = set;
430 /** @brief Set live object update status
431  * When set to true, objects will be updated continuously when dragging
432  * or transforming nodes. Otherwise they will only update when changes are committed
433  * to XML. */
434 void MultiPathManipulator::setLiveObjects(bool set)
436     invokeForAll(&PathManipulator::setLiveObjects, set);
437     _live_objects = set;
440 void MultiPathManipulator::updateOutlineColors()
442     //for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
443     //    i->second->setOutlineColor(_getOutlineColor(i->first.role));
444     //}
447 bool MultiPathManipulator::event(GdkEvent *event)
449     _tracker.event(event);
450     guint key = 0;
451     if (event->type == GDK_KEY_PRESS) {
452         key = shortcut_key(event->key);
453     }
455     // Single handle adjustments go here.
456     if (_selection.size() == 1 && event->type == GDK_KEY_PRESS) {
457         do {
458             Node *n = dynamic_cast<Node *>(*_selection.begin());
459             if (!n) break;
461             PathManipulator &pm = n->nodeList().subpathList().pm();
463             int which = 0;
464             if (_tracker.rightAlt() || _tracker.rightControl()) {
465                 which = 1;
466             }
467             if (_tracker.leftAlt() || _tracker.leftControl()) {
468                 if (which != 0) break; // ambiguous
469                 which = -1;
470             }
471             if (which == 0) break; // no handle chosen
472             bool one_pixel = _tracker.leftAlt() || _tracker.rightAlt();
473             bool handled = true;
475             switch (key) {
476             // single handle functions
477             // rotation
478             case GDK_bracketleft:
479             case GDK_braceleft:
480                 pm.rotateHandle(n, which, 1, one_pixel);
481                 break;
482             case GDK_bracketright:
483             case GDK_braceright:
484                 pm.rotateHandle(n, which, -1, one_pixel);
485                 break;
486             // adjust length
487             case GDK_period:
488             case GDK_greater:
489                 pm.scaleHandle(n, which, 1, one_pixel);
490                 break;
491             case GDK_comma:
492             case GDK_less:
493                 pm.scaleHandle(n, which, -1, one_pixel);
494                 break;
495             default:
496                 handled = false;
497                 break;
498             }
500             if (handled) return true;
501         } while(0);
502     }
505     switch (event->type) {
506     case GDK_KEY_PRESS:
507         switch (key) {
508         case GDK_Insert:
509         case GDK_KP_Insert:
510             // Insert - insert nodes in the middle of selected segments
511             insertNodes();
512             return true;
513         case GDK_i:
514         case GDK_I:
515             if (held_only_shift(event->key)) {
516                 // Shift+I - insert nodes (alternate keybinding for Mac keyboards
517                 //           that don't have the Insert key)
518                 insertNodes();
519                 return true;
520             }
521             break;
522         case GDK_d:
523         case GDK_D:
524             if (held_only_shift(event->key)) {
525                 duplicateNodes();
526                 return true;
527             }
528         case GDK_j:
529         case GDK_J:
530             if (held_only_shift(event->key)) {
531                 // Shift+J - join nodes
532                 joinNodes();
533                 return true;
534             }
535             if (held_only_alt(event->key)) {
536                 // Alt+J - join segments
537                 joinSegments();
538                 return true;
539             }
540             break;
541         case GDK_b:
542         case GDK_B:
543             if (held_only_shift(event->key)) {
544                 // Shift+B - break nodes
545                 breakNodes();
546                 return true;
547             }
548             break;
549         case GDK_Delete:
550         case GDK_KP_Delete:
551         case GDK_BackSpace:
552             if (held_shift(event->key)) break;
553             if (held_alt(event->key)) {
554                 // Alt+Delete - delete segments
555                 deleteSegments();
556             } else {
557                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
558                 bool del_preserves_shape = prefs->getBool("/tools/nodes/delete_preserves_shape", true);
559                 // pass keep_shape = true when:
560                 // a) del preserves shape, and control is not pressed
561                 // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed
562                 // Hence xor
563                 deleteNodes(del_preserves_shape ^ held_control(event->key));
564             }
565             return true;
566         case GDK_c:
567         case GDK_C:
568             if (held_only_shift(event->key)) {
569                 // Shift+C - make nodes cusp
570                 setNodeType(NODE_CUSP);
571                 return true;
572             }
573             break;
574         case GDK_s:
575         case GDK_S:
576             if (held_only_shift(event->key)) {
577                 // Shift+S - make nodes smooth
578                 setNodeType(NODE_SMOOTH);
579                 return true;
580             }
581             break;
582         case GDK_a:
583         case GDK_A:
584             if (held_only_shift(event->key)) {
585                 // Shift+A - make nodes auto-smooth
586                 setNodeType(NODE_AUTO);
587                 return true;
588             }
589             break;
590         case GDK_y:
591         case GDK_Y:
592             if (held_only_shift(event->key)) {
593                 // Shift+Y - make nodes symmetric
594                 setNodeType(NODE_SYMMETRIC);
595                 return true;
596             }
597             break;
598         case GDK_r:
599         case GDK_R:
600             if (held_only_shift(event->key)) {
601                 // Shift+R - reverse subpaths
602                 reverseSubpaths();
603                 return true;
604             }
605             break;
606         default:
607             break;
608         }
609         break;
610     case GDK_MOTION_NOTIFY:
611         combine_motion_events(_desktop->canvas, event->motion, 0);
612         for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
613             if (i->second->event(event)) return true;
614         }
615         break;
616     default: break;
617     }
619     return false;
622 /** Commit changes to XML and add undo stack entry based on the action that was done. Invoked
623  * by sub-manipulators, for example TransformHandleSet and ControlPointSelection. */
624 void MultiPathManipulator::_commit(CommitEvent cps)
626     gchar const *reason = NULL;
627     gchar const *key = NULL;
628     switch(cps) {
629     case COMMIT_MOUSE_MOVE:
630         reason = _("Move nodes");
631         break;
632     case COMMIT_KEYBOARD_MOVE_X:
633         reason = _("Move nodes horizontally");
634         key = "node:move:x";
635         break;
636     case COMMIT_KEYBOARD_MOVE_Y:
637         reason = _("Move nodes vertically");
638         key = "node:move:y";
639         break;
640     case COMMIT_MOUSE_ROTATE:
641         reason = _("Rotate nodes");
642         break;
643     case COMMIT_KEYBOARD_ROTATE:
644         reason = _("Rotate nodes");
645         key = "node:rotate";
646         break;
647     case COMMIT_MOUSE_SCALE_UNIFORM:
648         reason = _("Scale nodes uniformly");
649         break;
650     case COMMIT_MOUSE_SCALE:
651         reason = _("Scale nodes");
652         break;
653     case COMMIT_KEYBOARD_SCALE_UNIFORM:
654         reason = _("Scale nodes uniformly");
655         key = "node:scale:uniform";
656         break;
657     case COMMIT_KEYBOARD_SCALE_X:
658         reason = _("Scale nodes horizontally");
659         key = "node:scale:x";
660         break;
661     case COMMIT_KEYBOARD_SCALE_Y:
662         reason = _("Scale nodes vertically");
663         key = "node:scale:y";
664         break;
665     case COMMIT_FLIP_X:
666         reason = _("Flip nodes horizontally");
667         break;
668     case COMMIT_FLIP_Y:
669         reason = _("Flip nodes vertically");
670         break;
671     default: return;
672     }
673     
674     _selection.signal_update.emit();
675     invokeForAll(&PathManipulator::writeXML);
676     if (key) {
677         sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, reason);
678     } else {
679         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
680     }
681     signal_coords_changed.emit();
684 /** Commits changes to XML and adds undo stack entry. */
685 void MultiPathManipulator::_done(gchar const *reason) {
686     invokeForAll(&PathManipulator::update);
687     invokeForAll(&PathManipulator::writeXML);
688     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
689     signal_coords_changed.emit();
692 /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */
693 void MultiPathManipulator::_doneWithCleanup(gchar const *reason) {
694     _changed.block();
695     _done(reason);
696     cleanup();
697     _changed.unblock();
700 /** Get an outline color based on the shape's role (normal, mask, LPE parameter, etc.). */
701 guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role)
703     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
704     switch(role) {
705     case SHAPE_ROLE_CLIPPING_PATH:
706         return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff);
707     case SHAPE_ROLE_MASK:
708         return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff);
709     case SHAPE_ROLE_LPE_PARAM:
710         return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff);
711     case SHAPE_ROLE_NORMAL:
712     default:
713         return prefs->getColor("/tools/nodes/outline_color", 0xff0000ff);
714     }
717 } // namespace UI
718 } // namespace Inkscape
720 /*
721   Local Variables:
722   mode:c++
723   c-file-style:"stroustrup"
724   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
725   indent-tabs-mode:nil
726   fill-column:99
727   End:
728 */
729 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :