Code

Merge GSoC 2009 node tool rewrite
[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::joinSegments()
309     IterPairList joins;
310     find_join_iterators(_selection, joins);
312     for (IterPairList::iterator i = joins.begin(); i != joins.end(); ++i) {
313         bool same_path = prepare_join(*i);
314         NodeList &sp_first = NodeList::get(i->first);
315         NodeList &sp_second = NodeList::get(i->second);
316         i->first->setType(NODE_CUSP, false);
317         i->second->setType(NODE_CUSP, false);
318         if (same_path) {
319             sp_first.setClosed(true);
320         } else {
321             sp_first.splice(sp_first.end(), sp_second);
322             sp_second.kill();
323         }
324     }
326     if (joins.empty()) {
327         invokeForAll(&PathManipulator::weldSegments);
328     }
329     _doneWithCleanup("Join segments");
332 void MultiPathManipulator::deleteSegments()
334     if (_selection.empty()) return;
335     invokeForAll(&PathManipulator::deleteSegments);
336     _doneWithCleanup("Delete segments");
339 void MultiPathManipulator::alignNodes(Geom::Dim2 d)
341     _selection.align(d);
342     if (d == Geom::X) {
343         _done("Align nodes to a horizontal line");
344     } else {
345         _done("Align nodes to a vertical line");
346     }
349 void MultiPathManipulator::distributeNodes(Geom::Dim2 d)
351     _selection.distribute(d);
352     if (d == Geom::X) {
353         _done("Distrubute nodes horizontally");
354     } else {
355         _done("Distribute nodes vertically");
356     }
359 void MultiPathManipulator::reverseSubpaths()
361     invokeForAll(&PathManipulator::reverseSubpaths);
362     _done("Reverse selected subpaths");
365 void MultiPathManipulator::move(Geom::Point const &delta)
367     _selection.transform(Geom::Translate(delta));
368     _done("Move nodes");
371 void MultiPathManipulator::showOutline(bool show)
373     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
374         // always show outlines for clipping paths and masks
375         i->second->showOutline(show || i->first.role != SHAPE_ROLE_NORMAL);
376     }
377     _show_outline = show;
380 void MultiPathManipulator::showHandles(bool show)
382     invokeForAll(&PathManipulator::showHandles, show);
383     _show_handles = show;
386 void MultiPathManipulator::showPathDirection(bool show)
388     invokeForAll(&PathManipulator::showPathDirection, show);
389     _show_path_direction = show;
392 void MultiPathManipulator::updateOutlineColors()
394     //for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
395     //    i->second->setOutlineColor(_getOutlineColor(i->first.role));
396     //}
399 bool MultiPathManipulator::event(GdkEvent *event)
401     switch (event->type) {
402     case GDK_KEY_PRESS:
403         switch (shortcut_key(event->key)) {
404         case GDK_Insert:
405         case GDK_KP_Insert:
406             insertNodes();
407             return true;
408         case GDK_i:
409         case GDK_I:
410             if (held_only_shift(event->key)) {
411                 insertNodes();
412                 return true;
413             }
414             break;
415         case GDK_j:
416         case GDK_J:
417             if (held_only_shift(event->key)) {
418                 joinNodes();
419                 return true;
420             }
421             if (held_only_alt(event->key)) {
422                 joinSegments();
423                 return true;
424             }
425             break;
426         case GDK_b:
427         case GDK_B:
428             if (held_only_shift(event->key)) {
429                 breakNodes();
430                 return true;
431             }
432             break;
433         case GDK_Delete:
434         case GDK_KP_Delete:
435         case GDK_BackSpace:
436             if (held_shift(event->key)) break;
437             if (held_alt(event->key)) {
438                 deleteSegments();
439             } else {
440                 deleteNodes(!held_control(event->key));
441             }
442             return true;
443         case GDK_c:
444         case GDK_C:
445             if (held_only_shift(event->key)) {
446                 setNodeType(NODE_CUSP);
447                 return true;
448             }
449             break;
450         case GDK_s:
451         case GDK_S:
452             if (held_only_shift(event->key)) {
453                 setNodeType(NODE_SMOOTH);
454                 return true;
455             }
456             break;
457         case GDK_a:
458         case GDK_A:
459             if (held_only_shift(event->key)) {
460                 setNodeType(NODE_AUTO);
461                 return true;
462             }
463             break;
464         case GDK_y:
465         case GDK_Y:
466             if (held_only_shift(event->key)) {
467                 setNodeType(NODE_SYMMETRIC);
468                 return true;
469             }
470             break;
471         case GDK_r:
472         case GDK_R:
473             if (held_only_shift(event->key)) {
474                 reverseSubpaths();
475                 break;
476             }
477             break;
478         default:
479             break;
480         }
481         break;
482     default: break;
483     }
485     for (MapType::iterator i = _mmap.begin(); i != _mmap.end(); ++i) {
486         if (i->second->event(event)) return true;
487     }
488     return false;
491 /** Commit changes to XML and add undo stack entry based on the action that was done. Invoked
492  * by sub-manipulators, for example TransformHandleSet and ControlPointSelection. */
493 void MultiPathManipulator::_commit(CommitEvent cps)
495     gchar const *reason = NULL;
496     gchar const *key = NULL;
497     switch(cps) {
498     case COMMIT_MOUSE_MOVE:
499         reason = _("Move nodes");
500         break;
501     case COMMIT_KEYBOARD_MOVE_X:
502         reason = _("Move nodes horizontally");
503         key = "node:move:x";
504         break;
505     case COMMIT_KEYBOARD_MOVE_Y:
506         reason = _("Move nodes vertically");
507         key = "node:move:y";
508         break;
509     case COMMIT_MOUSE_ROTATE:
510         reason = _("Rotate nodes");
511         break;
512     case COMMIT_KEYBOARD_ROTATE:
513         reason = _("Rotate nodes");
514         key = "node:rotate";
515         break;
516     case COMMIT_MOUSE_SCALE_UNIFORM:
517         reason = _("Scale nodes uniformly");
518         break;
519     case COMMIT_MOUSE_SCALE:
520         reason = _("Scale nodes");
521         break;
522     case COMMIT_KEYBOARD_SCALE_UNIFORM:
523         reason = _("Scale nodes uniformly");
524         key = "node:scale:uniform";
525         break;
526     case COMMIT_KEYBOARD_SCALE_X:
527         reason = _("Scale nodes horizontally");
528         key = "node:scale:x";
529         break;
530     case COMMIT_KEYBOARD_SCALE_Y:
531         reason = _("Scale nodes vertically");
532         key = "node:scale:y";
533         break;
534     case COMMIT_FLIP_X:
535         reason = _("Flip nodes horizontally");
536         break;
537     case COMMIT_FLIP_Y:
538         reason = _("Flip nodes vertically");
539         break;
540     default: return;
541     }
542     
543     _selection.signal_update.emit();
544     invokeForAll(&PathManipulator::writeXML);
545     if (key) {
546         sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, reason);
547     } else {
548         sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
549     }
550     signal_coords_changed.emit();
553 /** Commits changes to XML and adds undo stack entry. */
554 void MultiPathManipulator::_done(gchar const *reason) {
555     invokeForAll(&PathManipulator::update);
556     invokeForAll(&PathManipulator::writeXML);
557     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, reason);
558     signal_coords_changed.emit();
561 /** Commits changes to XML, adds undo stack entry and removes empty manipulators. */
562 void MultiPathManipulator::_doneWithCleanup(gchar const *reason) {
563     _changed.block();
564     _done(reason);
565     cleanup();
566     _changed.unblock();
569 /** Get an outline color based on the shape's role (normal, mask, LPE parameter, etc.). */
570 guint32 MultiPathManipulator::_getOutlineColor(ShapeRole role)
572     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
573     switch(role) {
574     case SHAPE_ROLE_CLIPPING_PATH:
575         return prefs->getColor("/tools/nodes/clipping_path_color", 0x00ff00ff);
576     case SHAPE_ROLE_MASK:
577         return prefs->getColor("/tools/nodes/mask_color", 0x0000ffff);
578     case SHAPE_ROLE_LPE_PARAM:
579         return prefs->getColor("/tools/nodes/lpe_param_color", 0x009000ff);
580     case SHAPE_ROLE_NORMAL:
581     default:
582         return prefs->getColor("/tools/nodes/outline_color", 0xff0000ff);
583     }
586 } // namespace UI
587 } // namespace Inkscape
589 /*
590   Local Variables:
591   mode:c++
592   c-file-style:"stroustrup"
593   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
594   indent-tabs-mode:nil
595   fill-column:99
596   End:
597 */
598 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :