Code

Fix Ctrl-drag in node tool with zero snap delay.
[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::joinNodes()
249     invokeForAll(&PathManipulator::hideDragPoint);
250     // Node join has two parts. In the first one we join two subpaths by fusing endpoints
251     // into one. In the second we fuse nodes in each subpath.
252     IterPairList joins;
253     NodeList::iterator preserve_pos;
254     Node *mouseover_node = dynamic_cast<Node*>(ControlPoint::mouseovered_point);
255     if (mouseover_node) {
256         preserve_pos = NodeList::get_iterator(mouseover_node);
257     }
258     find_join_iterators(_selection, joins);
260     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
261         bool same_path = prepare_join(*i);
262         NodeList &sp_first = NodeList::get(i->first);
263         NodeList &sp_second = NodeList::get(i->second);
264         i->first->setType(NODE_CUSP, false);
266         Geom::Point joined_pos, pos_handle_front, pos_handle_back;
267         pos_handle_front = *i->second->front();
268         pos_handle_back = *i->first->back();
270         // When we encounter the mouseover node, we unset the iterator - it will be invalidated
271         if (i->first == preserve_pos) {
272             joined_pos = *i->first;
273             preserve_pos = NodeList::iterator();
274         } else if (i->second == preserve_pos) {
275             joined_pos = *i->second;
276             preserve_pos = NodeList::iterator();
277         } else {
278             joined_pos = Geom::middle_point(*i->first, *i->second);
279         }
281         // if the handles aren't degenerate, don't move them
282         i->first->move(joined_pos);
283         Node *joined_node = i->first.ptr();
284         if (!i->second->front()->isDegenerate()) {
285             joined_node->front()->setPosition(pos_handle_front);
286         }
287         if (!i->first->back()->isDegenerate()) {
288             joined_node->back()->setPosition(pos_handle_back);
289         }
290         sp_second.erase(i->second);
292         if (same_path) {
293             sp_first.setClosed(true);
294         } else {
295             sp_first.splice(sp_first.end(), sp_second);
296             sp_second.kill();
297         }
298         _selection.insert(i->first.ptr());
299     }
301     if (joins.empty()) {
302         // Second part replaces contiguous selections of nodes with single nodes
303         invokeForAll(&PathManipulator::weldNodes, preserve_pos);
304     }
306     _doneWithCleanup(_("Join nodes"));
309 void MultiPathManipulator::breakNodes()
311     if (_selection.empty()) return;
312     invokeForAll(&PathManipulator::breakNodes);
313     _done(_("Break nodes"));
316 void MultiPathManipulator::deleteNodes(bool keep_shape)
318     if (_selection.empty()) return;
319     invokeForAll(&PathManipulator::deleteNodes, keep_shape);
320     _doneWithCleanup(_("Delete nodes"));
323 /** Join selected endpoints to create segments. */
324 void MultiPathManipulator::joinSegments()
326     IterPairList joins;
327     find_join_iterators(_selection, joins);
329     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
330         bool same_path = prepare_join(*i);
331         NodeList &sp_first = NodeList::get(i->first);
332         NodeList &sp_second = NodeList::get(i->second);
333         i->first->setType(NODE_CUSP, false);
334         i->second->setType(NODE_CUSP, false);
335         if (same_path) {
336             sp_first.setClosed(true);
337         } else {
338             sp_first.splice(sp_first.end(), sp_second);
339             sp_second.kill();
340         }
341     }
343     if (joins.empty()) {
344         invokeForAll(&PathManipulator::weldSegments);
345     }
346     _doneWithCleanup("Join segments");
349 void MultiPathManipulator::deleteSegments()
351     if (_selection.empty()) return;
352     invokeForAll(&PathManipulator::deleteSegments);
353     _doneWithCleanup("Delete segments");
356 void MultiPathManipulator::alignNodes(Geom::Dim2 d)
358     _selection.align(d);
359     if (d == Geom::X) {
360         _done("Align nodes to a horizontal line");
361     } else {
362         _done("Align nodes to a vertical line");
363     }
366 void MultiPathManipulator::distributeNodes(Geom::Dim2 d)
368     _selection.distribute(d);
369     if (d == Geom::X) {
370         _done("Distrubute nodes horizontally");
371     } else {
372         _done("Distribute nodes vertically");
373     }
376 void MultiPathManipulator::reverseSubpaths()
378     if (_selection.empty()) {
379         invokeForAll(&PathManipulator::reverseSubpaths, false);
380         _done("Reverse subpaths");
381     } else {
382         invokeForAll(&PathManipulator::reverseSubpaths, true);
383         _done("Reverse selected subpaths");
384     }
387 void MultiPathManipulator::move(Geom::Point const &delta)
389     _selection.transform(Geom::Translate(delta));
390     _done("Move nodes");
393 void MultiPathManipulator::showOutline(bool show)
395     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
396         // always show outlines for clipping paths and masks
397         i->second->showOutline(show || i->first.role != SHAPE_ROLE_NORMAL);
398     }
399     _show_outline = show;
402 void MultiPathManipulator::showHandles(bool show)
404     invokeForAll(&PathManipulator::showHandles, show);
405     _show_handles = show;
408 void MultiPathManipulator::showPathDirection(bool show)
410     invokeForAll(&PathManipulator::showPathDirection, show);
411     _show_path_direction = show;
414 /** @brief Set live outline update status
415  * When set to true, outline will be updated continuously when dragging
416  * or transforming nodes. Otherwise it will only update when changes are committed
417  * to XML. */
418 void MultiPathManipulator::setLiveOutline(bool set)
420     invokeForAll(&PathManipulator::setLiveOutline, set);
421     _live_outline = set;
424 /** @brief Set live object update status
425  * When set to true, objects will be updated continuously when dragging
426  * or transforming nodes. Otherwise they will only update when changes are committed
427  * to XML. */
428 void MultiPathManipulator::setLiveObjects(bool set)
430     invokeForAll(&PathManipulator::setLiveObjects, set);
431     _live_objects = set;
434 void MultiPathManipulator::updateOutlineColors()
436     //for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
437     //    i->second->setOutlineColor(_getOutlineColor(i->first.role));
438     //}
441 bool MultiPathManipulator::event(GdkEvent *event)
443     _tracker.event(event);
444     guint key = 0;
445     if (event->type == GDK_KEY_PRESS) {
446         key = shortcut_key(event->key);
447     }
449     // Single handle adjustments go here.
450     if (_selection.size() == 1 && event->type == GDK_KEY_PRESS) {
451         do {
452             Node *n = dynamic_cast<Node *>(*_selection.begin());
453             if (!n) break;
455             PathManipulator &pm = n->nodeList().subpathList().pm();
457             int which = 0;
458             if (_tracker.rightAlt() || _tracker.rightControl()) {
459                 which = 1;
460             }
461             if (_tracker.leftAlt() || _tracker.leftControl()) {
462                 if (which != 0) break; // ambiguous
463                 which = -1;
464             }
465             if (which == 0) break; // no handle chosen
466             bool one_pixel = _tracker.leftAlt() || _tracker.rightAlt();
468             switch (key) {
469             // single handle functions
470             // rotation
471             case GDK_bracketleft:
472             case GDK_braceleft:
473                 pm.rotateHandle(n, which, 1, one_pixel);
474                 break;
475             case GDK_bracketright:
476             case GDK_braceright:
477                 pm.rotateHandle(n, which, -1, one_pixel);
478                 break;
479             // adjust length
480             case GDK_period:
481             case GDK_greater:
482                 pm.scaleHandle(n, which, 1, one_pixel);
483                 break;
484             case GDK_comma:
485             case GDK_less:
486                 pm.scaleHandle(n, which, -1, one_pixel);
487                 break;
488             }
489             return true;
490         } while(0);
491     }
494     switch (event->type) {
495     case GDK_KEY_PRESS:
496         switch (key) {
497         case GDK_Insert:
498         case GDK_KP_Insert:
499             // Insert - insert nodes in the middle of selected segments
500             insertNodes();
501             return true;
502         case GDK_i:
503         case GDK_I:
504             if (held_only_shift(event->key)) {
505                 // Shift+I - insert nodes (alternate keybinding for Mac keyboards
506                 //           that don't have the Insert key)
507                 insertNodes();
508                 return true;
509             }
510             break;
511         case GDK_j:
512         case GDK_J:
513             if (held_only_shift(event->key)) {
514                 // Shift+J - join nodes
515                 joinNodes();
516                 return true;
517             }
518             if (held_only_alt(event->key)) {
519                 // Alt+J - join segments
520                 joinSegments();
521                 return true;
522             }
523             break;
524         case GDK_b:
525         case GDK_B:
526             if (held_only_shift(event->key)) {
527                 // Shift+B - break nodes
528                 breakNodes();
529                 return true;
530             }
531             break;
532         case GDK_Delete:
533         case GDK_KP_Delete:
534         case GDK_BackSpace:
535             if (held_shift(event->key)) break;
536             if (held_alt(event->key)) {
537                 // Alt+Delete - delete segments
538                 deleteSegments();
539             } else {
540                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
541                 bool del_preserves_shape = prefs->getBool("/tools/nodes/delete_preserves_shape", true);
542                 // pass keep_shape = true when:
543                 // a) del preserves shape, and control is not pressed
544                 // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed
545                 // Hence xor
546                 deleteNodes(del_preserves_shape ^ held_control(event->key));
547             }
548             return true;
549         case GDK_c:
550         case GDK_C:
551             if (held_only_shift(event->key)) {
552                 // Shift+C - make nodes cusp
553                 setNodeType(NODE_CUSP);
554                 return true;
555             }
556             break;
557         case GDK_s:
558         case GDK_S:
559             if (held_only_shift(event->key)) {
560                 // Shift+S - make nodes smooth
561                 setNodeType(NODE_SMOOTH);
562                 return true;
563             }
564             break;
565         case GDK_a:
566         case GDK_A:
567             if (held_only_shift(event->key)) {
568                 // Shift+A - make nodes auto-smooth
569                 setNodeType(NODE_AUTO);
570                 return true;
571             }
572             break;
573         case GDK_y:
574         case GDK_Y:
575             if (held_only_shift(event->key)) {
576                 // Shift+Y - make nodes symmetric
577                 setNodeType(NODE_SYMMETRIC);
578                 return true;
579             }
580             break;
581         case GDK_r:
582         case GDK_R:
583             if (held_only_shift(event->key)) {
584                 // Shift+R - reverse subpaths
585                 reverseSubpaths();
586                 return true;
587             }
588             break;
589         default:
590             break;
591         }
592         break;
593     case GDK_MOTION_NOTIFY:
594         combine_motion_events(_desktop->canvas, event->motion, 0);
595         for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
596             if (i->second->event(event)) return true;
597         }
598         break;
599     default: break;
600     }
602     return false;
605 /** Commit changes to XML and add undo stack entry based on the action that was done. Invoked
606  * by sub-manipulators, for example TransformHandleSet and ControlPointSelection. */
607 void MultiPathManipulator::_commit(CommitEvent cps)
609     gchar const *reason = NULL;
610     gchar const *key = NULL;
611     switch(cps) {
612     case COMMIT_MOUSE_MOVE:
613         reason = _("Move nodes");
614         break;
615     case COMMIT_KEYBOARD_MOVE_X:
616         reason = _("Move nodes horizontally");
617         key = "node:move:x";
618         break;
619     case COMMIT_KEYBOARD_MOVE_Y:
620         reason = _("Move nodes vertically");
621         key = "node:move:y";
622         break;
623     case COMMIT_MOUSE_ROTATE:
624         reason = _("Rotate nodes");
625         break;
626     case COMMIT_KEYBOARD_ROTATE:
627         reason = _("Rotate nodes");
628         key = "node:rotate";
629         break;
630     case COMMIT_MOUSE_SCALE_UNIFORM:
631         reason = _("Scale nodes uniformly");
632         break;
633     case COMMIT_MOUSE_SCALE:
634         reason = _("Scale nodes");
635         break;
636     case COMMIT_KEYBOARD_SCALE_UNIFORM:
637         reason = _("Scale nodes uniformly");
638         key = "node:scale:uniform";
639         break;
640     case COMMIT_KEYBOARD_SCALE_X:
641         reason = _("Scale nodes horizontally");
642         key = "node:scale:x";
643         break;
644     case COMMIT_KEYBOARD_SCALE_Y:
645         reason = _("Scale nodes vertically");
646         key = "node:scale:y";
647         break;
648     case COMMIT_FLIP_X:
649         reason = _("Flip nodes horizontally");
650         break;
651     case COMMIT_FLIP_Y:
652         reason = _("Flip nodes vertically");
653         break;
654     default: return;
655     }
656     
657     _selection.signal_update.emit();
658     invokeForAll(&PathManipulator::writeXML);
659     if (key) {
660         sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, reason);
661     } else {
662         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
663     }
664     signal_coords_changed.emit();
667 /** Commits changes to XML and adds undo stack entry. */
668 void MultiPathManipulator::_done(gchar const *reason) {
669     invokeForAll(&PathManipulator::update);
670     invokeForAll(&PathManipulator::writeXML);
671     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
672     signal_coords_changed.emit();
675 /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */
676 void MultiPathManipulator::_doneWithCleanup(gchar const *reason) {
677     _changed.block();
678     _done(reason);
679     cleanup();
680     _changed.unblock();
683 /** Get an outline color based on the shape's role (normal, mask, LPE parameter, etc.). */
684 guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role)
686     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
687     switch(role) {
688     case SHAPE_ROLE_CLIPPING_PATH:
689         return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff);
690     case SHAPE_ROLE_MASK:
691         return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff);
692     case SHAPE_ROLE_LPE_PARAM:
693         return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff);
694     case SHAPE_ROLE_NORMAL:
695     default:
696         return prefs->getColor("/tools/nodes/outline_color", 0xff0000ff);
697     }
700 } // namespace UI
701 } // namespace Inkscape
703 /*
704   Local Variables:
705   mode:c++
706   c-file-style:"stroustrup"
707   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
708   indent-tabs-mode:nil
709   fill-column:99
710   End:
711 */
712 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :