Code

A simple layout document as to what, why and how is cppification.
[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();
467             bool handled = true;
469             switch (key) {
470             // single handle functions
471             // rotation
472             case GDK_bracketleft:
473             case GDK_braceleft:
474                 pm.rotateHandle(n, which, 1, one_pixel);
475                 break;
476             case GDK_bracketright:
477             case GDK_braceright:
478                 pm.rotateHandle(n, which, -1, one_pixel);
479                 break;
480             // adjust length
481             case GDK_period:
482             case GDK_greater:
483                 pm.scaleHandle(n, which, 1, one_pixel);
484                 break;
485             case GDK_comma:
486             case GDK_less:
487                 pm.scaleHandle(n, which, -1, one_pixel);
488                 break;
489             default:
490                 handled = false;
491                 break;
492             }
494             if (handled) return true;
495         } while(0);
496     }
499     switch (event->type) {
500     case GDK_KEY_PRESS:
501         switch (key) {
502         case GDK_Insert:
503         case GDK_KP_Insert:
504             // Insert - insert nodes in the middle of selected segments
505             insertNodes();
506             return true;
507         case GDK_i:
508         case GDK_I:
509             if (held_only_shift(event->key)) {
510                 // Shift+I - insert nodes (alternate keybinding for Mac keyboards
511                 //           that don't have the Insert key)
512                 insertNodes();
513                 return true;
514             }
515             break;
516         case GDK_j:
517         case GDK_J:
518             if (held_only_shift(event->key)) {
519                 // Shift+J - join nodes
520                 joinNodes();
521                 return true;
522             }
523             if (held_only_alt(event->key)) {
524                 // Alt+J - join segments
525                 joinSegments();
526                 return true;
527             }
528             break;
529         case GDK_b:
530         case GDK_B:
531             if (held_only_shift(event->key)) {
532                 // Shift+B - break nodes
533                 breakNodes();
534                 return true;
535             }
536             break;
537         case GDK_Delete:
538         case GDK_KP_Delete:
539         case GDK_BackSpace:
540             if (held_shift(event->key)) break;
541             if (held_alt(event->key)) {
542                 // Alt+Delete - delete segments
543                 deleteSegments();
544             } else {
545                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
546                 bool del_preserves_shape = prefs->getBool("/tools/nodes/delete_preserves_shape", true);
547                 // pass keep_shape = true when:
548                 // a) del preserves shape, and control is not pressed
549                 // b) ctrl+del preserves shape (del_preserves_shape is false), and control is pressed
550                 // Hence xor
551                 deleteNodes(del_preserves_shape ^ held_control(event->key));
552             }
553             return true;
554         case GDK_c:
555         case GDK_C:
556             if (held_only_shift(event->key)) {
557                 // Shift+C - make nodes cusp
558                 setNodeType(NODE_CUSP);
559                 return true;
560             }
561             break;
562         case GDK_s:
563         case GDK_S:
564             if (held_only_shift(event->key)) {
565                 // Shift+S - make nodes smooth
566                 setNodeType(NODE_SMOOTH);
567                 return true;
568             }
569             break;
570         case GDK_a:
571         case GDK_A:
572             if (held_only_shift(event->key)) {
573                 // Shift+A - make nodes auto-smooth
574                 setNodeType(NODE_AUTO);
575                 return true;
576             }
577             break;
578         case GDK_y:
579         case GDK_Y:
580             if (held_only_shift(event->key)) {
581                 // Shift+Y - make nodes symmetric
582                 setNodeType(NODE_SYMMETRIC);
583                 return true;
584             }
585             break;
586         case GDK_r:
587         case GDK_R:
588             if (held_only_shift(event->key)) {
589                 // Shift+R - reverse subpaths
590                 reverseSubpaths();
591                 return true;
592             }
593             break;
594         default:
595             break;
596         }
597         break;
598     case GDK_MOTION_NOTIFY:
599         combine_motion_events(_desktop->canvas, event->motion, 0);
600         for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
601             if (i->second->event(event)) return true;
602         }
603         break;
604     default: break;
605     }
607     return false;
610 /** Commit changes to XML and add undo stack entry based on the action that was done. Invoked
611  * by sub-manipulators, for example TransformHandleSet and ControlPointSelection. */
612 void MultiPathManipulator::_commit(CommitEvent cps)
614     gchar const *reason = NULL;
615     gchar const *key = NULL;
616     switch(cps) {
617     case COMMIT_MOUSE_MOVE:
618         reason = _("Move nodes");
619         break;
620     case COMMIT_KEYBOARD_MOVE_X:
621         reason = _("Move nodes horizontally");
622         key = "node:move:x";
623         break;
624     case COMMIT_KEYBOARD_MOVE_Y:
625         reason = _("Move nodes vertically");
626         key = "node:move:y";
627         break;
628     case COMMIT_MOUSE_ROTATE:
629         reason = _("Rotate nodes");
630         break;
631     case COMMIT_KEYBOARD_ROTATE:
632         reason = _("Rotate nodes");
633         key = "node:rotate";
634         break;
635     case COMMIT_MOUSE_SCALE_UNIFORM:
636         reason = _("Scale nodes uniformly");
637         break;
638     case COMMIT_MOUSE_SCALE:
639         reason = _("Scale nodes");
640         break;
641     case COMMIT_KEYBOARD_SCALE_UNIFORM:
642         reason = _("Scale nodes uniformly");
643         key = "node:scale:uniform";
644         break;
645     case COMMIT_KEYBOARD_SCALE_X:
646         reason = _("Scale nodes horizontally");
647         key = "node:scale:x";
648         break;
649     case COMMIT_KEYBOARD_SCALE_Y:
650         reason = _("Scale nodes vertically");
651         key = "node:scale:y";
652         break;
653     case COMMIT_FLIP_X:
654         reason = _("Flip nodes horizontally");
655         break;
656     case COMMIT_FLIP_Y:
657         reason = _("Flip nodes vertically");
658         break;
659     default: return;
660     }
661     
662     _selection.signal_update.emit();
663     invokeForAll(&PathManipulator::writeXML);
664     if (key) {
665         SPDocumentUndo::maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, reason);
666     } else {
667         SPDocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
668     }
669     signal_coords_changed.emit();
672 /** Commits changes to XML and adds undo stack entry. */
673 void MultiPathManipulator::_done(gchar const *reason) {
674     invokeForAll(&PathManipulator::update);
675     invokeForAll(&PathManipulator::writeXML);
676     SPDocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
677     signal_coords_changed.emit();
680 /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */
681 void MultiPathManipulator::_doneWithCleanup(gchar const *reason) {
682     _changed.block();
683     _done(reason);
684     cleanup();
685     _changed.unblock();
688 /** Get an outline color based on the shape's role (normal, mask, LPE parameter, etc.). */
689 guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role)
691     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
692     switch(role) {
693     case SHAPE_ROLE_CLIPPING_PATH:
694         return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff);
695     case SHAPE_ROLE_MASK:
696         return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff);
697     case SHAPE_ROLE_LPE_PARAM:
698         return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff);
699     case SHAPE_ROLE_NORMAL:
700     default:
701         return prefs->getColor("/tools/nodes/outline_color", 0xff0000ff);
702     }
705 } // namespace UI
706 } // namespace Inkscape
708 /*
709   Local Variables:
710   mode:c++
711   c-file-style:"stroustrup"
712   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
713   indent-tabs-mode:nil
714   fill-column:99
715   End:
716 */
717 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :