Code

2cc9bc97b5cf26b45cf6abab886d20c6e26e5529
[inkscape.git] / src / ui / tool / multi-path-manipulator.cpp
1 /** @file
2  * 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 <tr1/unordered_set>
12 #include <boost/shared_ptr.hpp>
13 #include <glib.h>
14 #include <glibmm/i18n.h>
15 #include "desktop.h"
16 #include "desktop-handles.h"
17 #include "document.h"
18 #include "live_effects/lpeobject.h"
19 #include "message-stack.h"
20 #include "preferences.h"
21 #include "sp-path.h"
22 #include "ui/tool/control-point-selection.h"
23 #include "ui/tool/event-utils.h"
24 #include "ui/tool/node.h"
25 #include "ui/tool/multi-path-manipulator.h"
26 #include "ui/tool/path-manipulator.h"
28 namespace std { using namespace tr1; }
30 namespace Inkscape {
31 namespace UI {
33 namespace {
34 typedef std::pair<NodeList::iterator, NodeList::iterator> IterPair;
35 typedef std::vector<IterPair> IterPairList;
36 typedef std::unordered_set<NodeList::iterator> IterSet;
37 typedef std::multimap<double, IterPair> DistanceMap;
38 typedef std::pair<double, IterPair> DistanceMapItem;
40 /** Find pairs of selected endnodes suitable for joining. */
41 void find_join_iterators(ControlPointSelection &sel, IterPairList &pairs)
42 {
43     IterSet join_iters;
44     DistanceMap dists;
46     // find all endnodes in selection
47     for (ControlPointSelection::iterator i = sel.begin(); i != sel.end(); ++i) {
48         Node *node = dynamic_cast<Node*>(i->first);
49         if (!node) continue;
50         NodeList::iterator iter = NodeList::get_iterator(node);
51         if (!iter.next() || !iter.prev()) join_iters.insert(iter);
52     }
54     if (join_iters.size() < 2) return;
56     // Below we find the closest pairs. The algorithm is O(N^3).
57     // We can go down to O(N^2 log N) by using O(N^2) memory, by putting all pairs
58     // with their distances in a multimap (not worth it IMO).
59     while (join_iters.size() >= 2) {
60         double closest = DBL_MAX;
61         IterPair closest_pair;
62         for (IterSet::iterator i = join_iters.begin(); i != join_iters.end(); ++i) {
63             for (IterSet::iterator j = join_iters.begin(); j != i; ++j) {
64                 double dist = Geom::distance(**i, **j);
65                 if (dist < closest) {
66                     closest = dist;
67                     closest_pair = std::make_pair(*i, *j);
68                 }
69             }
70         }
71         pairs.push_back(closest_pair);
72         join_iters.erase(closest_pair.first);
73         join_iters.erase(closest_pair.second);
74     }
75 }
77 /** After this function, first should be at the end of path and second at the beginnning.
78  * @returns True if the nodes are in the same subpath */
79 bool prepare_join(IterPair &join_iters)
80 {
81     if (&NodeList::get(join_iters.first) == &NodeList::get(join_iters.second)) {
82         if (join_iters.first.next()) // if first is begin, swap the iterators
83             std::swap(join_iters.first, join_iters.second);
84         return true;
85     }
87     NodeList &sp_first = NodeList::get(join_iters.first);
88     NodeList &sp_second = NodeList::get(join_iters.second);
89     if (join_iters.first.next()) { // first is begin
90         if (join_iters.second.next()) { // second is begin
91             sp_first.reverse();
92         } else { // second is end
93             std::swap(join_iters.first, join_iters.second);
94         }
95     } else { // first is end
96         if (join_iters.second.next()) { // second is begin
97             // do nothing
98         } else { // second is end
99             sp_second.reverse();
100         }
101     }
102     return false;
104 } // anonymous namespace
107 MultiPathManipulator::MultiPathManipulator(PathSharedData &data, sigc::connection &chg)
108     : PointManipulator(data.node_data.desktop, *data.node_data.selection)
109     , _path_data(data)
110     , _changed(chg)
112     _selection.signal_commit.connect(
113         sigc::mem_fun(*this, &MultiPathManipulator::_commit));
114     _selection.signal_point_changed.connect(
115         sigc::hide( sigc::hide(
116             signal_coords_changed.make_slot())));
119 MultiPathManipulator::~MultiPathManipulator()
121     _mmap.clear();
124 /** Remove empty manipulators. */
125 void MultiPathManipulator::cleanup()
127     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ) {
128         if (i->second->empty()) _mmap.erase(i++);
129         else ++i;
130     }
133 /** @brief Change the set of items to edit.
134  *
135  * This method attempts to preserve as much of the state as possible. */
136 void MultiPathManipulator::setItems(std::set<ShapeRecord> const &s)
138     std::set<ShapeRecord> shapes(s);
140     // iterate over currently edited items, modifying / removing them as necessary
141     for (MapType::iterator i = _mmap.begin(); i != _mmap.end();) {
142         std::set<ShapeRecord>::iterator si = shapes.find(i->first);
143         if (si == shapes.end()) {
144             // This item is no longer supposed to be edited - remove its manipulator
145             _mmap.erase(i++);
146         } else {
147             ShapeRecord const &sr = i->first;
148             ShapeRecord const &sr_new = *si;
149             // if the shape record differs, replace the key only and modify other values
150             if (sr.edit_transform != sr_new.edit_transform ||
151                 sr.role != sr_new.role)
152             {
153                 boost::shared_ptr<PathManipulator> hold(i->second);
154                 if (sr.edit_transform != sr_new.edit_transform)
155                     hold->setControlsTransform(sr_new.edit_transform);
156                 if (sr.role != sr_new.role) {
157                     //hold->setOutlineColor(_getOutlineColor(sr_new.role));
158                 }
159                 _mmap.erase(sr);
160                 _mmap.insert(std::make_pair(sr_new, hold));
161             }
162             shapes.erase(si); // remove the processed record
163             ++i;
164         }
165     }
167     // add newly selected items
168     for (std::set<ShapeRecord>::iterator i = shapes.begin(); i != shapes.end(); ++i) {
169         ShapeRecord const &r = *i;
170         if (!SP_IS_PATH(r.item) && !IS_LIVEPATHEFFECT(r.item)) continue;
171         boost::shared_ptr<PathManipulator> newpm(new PathManipulator(*this, (SPPath*) r.item,
172             r.edit_transform, _getOutlineColor(r.role), r.lpe_key));
173         newpm->showHandles(_show_handles);
174         // always show outlines for clips and masks
175         newpm->showOutline(_show_outline || r.role != SHAPE_ROLE_NORMAL);
176         newpm->showPathDirection(_show_path_direction);
177         _mmap.insert(std::make_pair(r, newpm));
178     }
181 void MultiPathManipulator::selectSubpaths()
183     if (_selection.empty()) {
184         _selection.selectAll();
185     } else {
186         invokeForAll(&PathManipulator::selectSubpaths);
187     }
190 void MultiPathManipulator::shiftSelection(int dir)
192     invokeForAll(&PathManipulator::shiftSelection, dir);
195 void MultiPathManipulator::invertSelectionInSubpaths()
197     invokeForAll(&PathManipulator::invertSelectionInSubpaths);
200 void MultiPathManipulator::setNodeType(NodeType type)
202     if (_selection.empty()) return;
203     for (ControlPointSelection::iterator i = _selection.begin(); i != _selection.end(); ++i) {
204         Node *node = dynamic_cast<Node*>(i->first);
205         if (node) node->setType(type);
206     }
207     _done(_("Change node type"));
210 void MultiPathManipulator::setSegmentType(SegmentType type)
212     if (_selection.empty()) return;
213     invokeForAll(&PathManipulator::setSegmentType, type);
214     if (type == SEGMENT_STRAIGHT) {
215         _done(_("Straighten segments"));
216     } else {
217         _done(_("Make segments curves"));
218     }
221 void MultiPathManipulator::insertNodes()
223     invokeForAll(&PathManipulator::insertNodes);
224     _done(_("Add nodes"));
227 void MultiPathManipulator::joinNodes()
229     invokeForAll(&PathManipulator::hideDragPoint);
230     // Node join has two parts. In the first one we join two subpaths by fusing endpoints
231     // into one. In the second we fuse nodes in each subpath.
232     IterPairList joins;
233     NodeList::iterator preserve_pos;
234     Node *mouseover_node = dynamic_cast<Node*>(ControlPoint::mouseovered_point);
235     if (mouseover_node) {
236         preserve_pos = NodeList::get_iterator(mouseover_node);
237     }
238     find_join_iterators(_selection, joins);
240     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
241         bool same_path = prepare_join(*i);
242         bool mouseover = true;
243         NodeList &sp_first = NodeList::get(i->first);
244         NodeList &sp_second = NodeList::get(i->second);
245         i->first->setType(NODE_CUSP, false);
247         Geom::Point joined_pos, pos_front, pos_back;
248         pos_front = *i->second->front();
249         pos_back = *i->first->back();
250         if (i->first == preserve_pos) {
251             joined_pos = *i->first;
252         } else if (i->second == preserve_pos) {
253             joined_pos = *i->second;
254         } else {
255             joined_pos = Geom::middle_point(pos_back, pos_front);
256             mouseover = false;
257         }
259         // if the handles aren't degenerate, don't move them
260         i->first->move(joined_pos);
261         Node *joined_node = i->first.ptr();
262         if (!i->second->front()->isDegenerate()) {
263             joined_node->front()->setPosition(pos_front);
264         }
265         if (!i->first->back()->isDegenerate()) {
266             joined_node->back()->setPosition(pos_back);
267         }
268         if (mouseover) {
269             // Second node could be mouseovered, but it will be deleted, so we must change
270             // the preserve_pos iterator to the first node.
271             preserve_pos = i->first;
272         }
273         sp_second.erase(i->second);
275         if (same_path) {
276             sp_first.setClosed(true);
277         } else {
278             sp_first.splice(sp_first.end(), sp_second);
279             sp_second.kill();
280         }
281         _selection.insert(i->first.ptr());
282     }
284     if (joins.empty()) {
285         // Second part replaces contiguous selections of nodes with single nodes
286         invokeForAll(&PathManipulator::weldNodes, preserve_pos);
287     }
289     _doneWithCleanup(_("Join nodes"));
292 void MultiPathManipulator::breakNodes()
294     if (_selection.empty()) return;
295     invokeForAll(&PathManipulator::breakNodes);
296     _done(_("Break nodes"));
299 void MultiPathManipulator::deleteNodes(bool keep_shape)
301     if (_selection.empty()) return;
302     invokeForAll(&PathManipulator::deleteNodes, keep_shape);
303     _doneWithCleanup(_("Delete nodes"));
306 /** Join selected endpoints to create segments. */
307 void MultiPathManipulator::joinSegment()
309     IterPairList joins;
310     find_join_iterators(_selection, joins);
311     if (joins.empty()) {
312         _desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
313             _("There must be at least 2 endnodes in selection"));
314         return;
315     }
317     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
318         bool same_path = prepare_join(*i);
319         NodeList &sp_first = NodeList::get(i->first);
320         NodeList &sp_second = NodeList::get(i->second);
321         i->first->setType(NODE_CUSP, false);
322         i->second->setType(NODE_CUSP, false);
323         if (same_path) {
324             sp_first.setClosed(true);
325         } else {
326             sp_first.splice(sp_first.end(), sp_second);
327             sp_second.kill();
328         }
329     }
331     _doneWithCleanup("Join segments");
334 void MultiPathManipulator::deleteSegments()
336     if (_selection.empty()) return;
337     invokeForAll(&PathManipulator::deleteSegments);
338     _doneWithCleanup("Delete segments");
341 void MultiPathManipulator::alignNodes(Geom::Dim2 d)
343     _selection.align(d);
344     if (d == Geom::X) {
345         _done("Align nodes to a horizontal line");
346     } else {
347         _done("Align nodes to a vertical line");
348     }
351 void MultiPathManipulator::distributeNodes(Geom::Dim2 d)
353     _selection.distribute(d);
354     if (d == Geom::X) {
355         _done("Distrubute nodes horizontally");
356     } else {
357         _done("Distribute nodes vertically");
358     }
361 void MultiPathManipulator::reverseSubpaths()
363     invokeForAll(&PathManipulator::reverseSubpaths);
364     _done("Reverse selected subpaths");
367 void MultiPathManipulator::move(Geom::Point const &delta)
369     _selection.transform(Geom::Translate(delta));
370     _done("Move nodes");
373 void MultiPathManipulator::showOutline(bool show)
375     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
376         // always show outlines for clipping paths and masks
377         i->second->showOutline(show || i->first.role != SHAPE_ROLE_NORMAL);
378     }
379     _show_outline = show;
382 void MultiPathManipulator::showHandles(bool show)
384     invokeForAll(&PathManipulator::showHandles, show);
385     _show_handles = show;
388 void MultiPathManipulator::showPathDirection(bool show)
390     invokeForAll(&PathManipulator::showPathDirection, show);
391     _show_path_direction = show;
394 void MultiPathManipulator::updateOutlineColors()
396     //for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
397     //    i->second->setOutlineColor(_getOutlineColor(i->first.role));
398     //}
401 bool MultiPathManipulator::event(GdkEvent *event)
403     switch (event->type) {
404     case GDK_KEY_PRESS:
405         switch (shortcut_key(event->key)) {
406         case GDK_Insert:
407         case GDK_KP_Insert:
408             insertNodes();
409             return true;
410         case GDK_i:
411         case GDK_I:
412             if (held_only_shift(event->key)) {
413                 insertNodes();
414                 return true;
415             }
416             break;
417         case GDK_j:
418         case GDK_J:
419             if (held_only_shift(event->key)) {
420                 joinNodes();
421                 return true;
422             }
423             if (held_only_alt(event->key)) {
424                 joinSegment();
425                 return true;
426             }
427             break;
428         case GDK_b:
429         case GDK_B:
430             if (held_only_shift(event->key)) {
431                 breakNodes();
432                 return true;
433             }
434             break;
435         case GDK_Delete:
436         case GDK_KP_Delete:
437         case GDK_BackSpace:
438             if (held_shift(event->key)) break;
439             if (held_alt(event->key)) {
440                 deleteSegments();
441             } else {
442                 deleteNodes(!held_control(event->key));
443             }
444             return true;
445         case GDK_c:
446         case GDK_C:
447             if (held_only_shift(event->key)) {
448                 setNodeType(NODE_CUSP);
449                 return true;
450             }
451             break;
452         case GDK_s:
453         case GDK_S:
454             if (held_only_shift(event->key)) {
455                 setNodeType(NODE_SMOOTH);
456                 return true;
457             }
458             break;
459         case GDK_a:
460         case GDK_A:
461             if (held_only_shift(event->key)) {
462                 setNodeType(NODE_AUTO);
463                 return true;
464             }
465             break;
466         case GDK_y:
467         case GDK_Y:
468             if (held_only_shift(event->key)) {
469                 setNodeType(NODE_SYMMETRIC);
470                 return true;
471             }
472             break;
473         case GDK_r:
474         case GDK_R:
475             if (held_only_shift(event->key)) {
476                 reverseSubpaths();
477                 break;
478             }
479             break;
480         default:
481             break;
482         }
483         break;
484     default: break;
485     }
487     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
488         if (i->second->event(event)) return true;
489     }
490     return false;
493 /** Commit changes to XML and add undo stack entry based on the action that was done. Invoked
494  * by sub-manipulators, for example TransformHandleSet and ControlPointSelection. */
495 void MultiPathManipulator::_commit(CommitEvent cps)
497     gchar const *reason = NULL;
498     gchar const *key = NULL;
499     switch(cps) {
500     case COMMIT_MOUSE_MOVE:
501         reason = _("Move nodes");
502         break;
503     case COMMIT_KEYBOARD_MOVE_X:
504         reason = _("Move nodes horizontally");
505         key = "node:move:x";
506         break;
507     case COMMIT_KEYBOARD_MOVE_Y:
508         reason = _("Move nodes vertically");
509         key = "node:move:y";
510         break;
511     case COMMIT_MOUSE_ROTATE:
512         reason = _("Rotate nodes");
513         break;
514     case COMMIT_KEYBOARD_ROTATE:
515         reason = _("Rotate nodes");
516         key = "node:rotate";
517         break;
518     case COMMIT_MOUSE_SCALE_UNIFORM:
519         reason = _("Scale nodes uniformly");
520         break;
521     case COMMIT_MOUSE_SCALE:
522         reason = _("Scale nodes");
523         break;
524     case COMMIT_KEYBOARD_SCALE_UNIFORM:
525         reason = _("Scale nodes uniformly");
526         key = "node:scale:uniform";
527         break;
528     case COMMIT_KEYBOARD_SCALE_X:
529         reason = _("Scale nodes horizontally");
530         key = "node:scale:x";
531         break;
532     case COMMIT_KEYBOARD_SCALE_Y:
533         reason = _("Scale nodes vertically");
534         key = "node:scale:y";
535         break;
536     case COMMIT_FLIP_X:
537         reason = _("Flip nodes horizontally");
538         break;
539     case COMMIT_FLIP_Y:
540         reason = _("Flip nodes vertically");
541         break;
542     default: return;
543     }
544     
545     _selection.signal_update.emit();
546     invokeForAll(&PathManipulator::writeXML);
547     if (key) {
548         sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, reason);
549     } else {
550         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
551     }
552     signal_coords_changed.emit();
555 /** Commits changes to XML and adds undo stack entry. */
556 void MultiPathManipulator::_done(gchar const *reason) {
557     invokeForAll(&PathManipulator::update);
558     invokeForAll(&PathManipulator::writeXML);
559     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
560     signal_coords_changed.emit();
563 /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */
564 void MultiPathManipulator::_doneWithCleanup(gchar const *reason) {
565     _changed.block();
566     _done(reason);
567     cleanup();
568     _changed.unblock();
571 /** Get an outline color based on the shape's role (normal, mask, LPE parameter, etc.). */
572 guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role)
574     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
575     switch(role) {
576     case SHAPE_ROLE_CLIPPING_PATH:
577         return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff);
578     case SHAPE_ROLE_MASK:
579         return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff);
580     case SHAPE_ROLE_LPE_PARAM:
581         return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff);
582     case SHAPE_ROLE_NORMAL:
583     default:
584         return prefs->getColor("/tools/nodes/outline_color", 0xff0000ff);
585     }
588 } // namespace UI
589 } // namespace Inkscape
591 /*
592   Local Variables:
593   mode:c++
594   c-file-style:"stroustrup"
595   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
596   indent-tabs-mode:nil
597   fill-column:99
598   End:
599 */
600 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :