Code

5ae9c4137255c7ab9cc1db66f7cb700045190448
[inkscape.git] / src / ui / tool / path-manipulator.cpp
1 /** @file
2  * Path manipulator - implementation
3  */
4 /* Authors:
5  *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
6  *   Abhishek Sharma
7  *
8  * Copyright (C) 2009 Authors
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  */
12 #include <string>
13 #include <sstream>
14 #include <deque>
15 #include <stdexcept>
16 #include <boost/shared_ptr.hpp>
17 #include <2geom/bezier-curve.h>
18 #include <2geom/bezier-utils.h>
19 #include <2geom/svg-path.h>
20 #include <glibmm.h>
21 #include <glibmm/i18n.h>
22 #include "ui/tool/path-manipulator.h"
23 #include "desktop.h"
24 #include "desktop-handles.h"
25 #include "display/sp-canvas.h"
26 #include "display/sp-canvas-util.h"
27 #include "display/curve.h"
28 #include "display/canvas-bpath.h"
29 #include "document.h"
30 #include "live_effects/effect.h"
31 #include "live_effects/lpeobject.h"
32 #include "live_effects/parameter/path.h"
33 #include "sp-path.h"
34 #include "helper/geom.h"
35 #include "preferences.h"
36 #include "style.h"
37 #include "ui/tool/control-point-selection.h"
38 #include "ui/tool/curve-drag-point.h"
39 #include "ui/tool/event-utils.h"
40 #include "ui/tool/multi-path-manipulator.h"
41 #include "xml/node.h"
42 #include "xml/node-observer.h"
44 namespace Inkscape {
45 namespace UI {
47 namespace {
48 /// Types of path changes that we must react to.
49 enum PathChange {
50     PATH_CHANGE_D,
51     PATH_CHANGE_TRANSFORM
52 };
54 } // anonymous namespace
56 /**
57  * Notifies the path manipulator when something changes the path being edited
58  * (e.g. undo / redo)
59  */
60 class PathManipulatorObserver : public Inkscape::XML::NodeObserver {
61 public:
62     PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node)
63         : _pm(p)
64         , _node(node)
65         , _blocked(false)
66     {
67         Inkscape::GC::anchor(_node);
68         _node->addObserver(*this);
69     }
71     ~PathManipulatorObserver() {
72         _node->removeObserver(*this);
73         Inkscape::GC::release(_node);
74     }
76     virtual void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr,
77         Util::ptr_shared<char>, Util::ptr_shared<char>)
78     {
79         // do nothing if blocked
80         if (_blocked) return;
82         GQuark path_d = g_quark_from_static_string("d");
83         GQuark path_transform = g_quark_from_static_string("transform");
84         GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
86         // only react to "d" (path data) and "transform" attribute changes
87         if (attr == lpe_quark || attr == path_d) {
88             _pm->_externalChange(PATH_CHANGE_D);
89         } else if (attr == path_transform) {
90             _pm->_externalChange(PATH_CHANGE_TRANSFORM);
91         }
92     }
94     void block() { _blocked = true; }
95     void unblock() { _blocked = false; }
96 private:
97     PathManipulator *_pm;
98     Inkscape::XML::Node *_node;
99     bool _blocked;
100 };
102 void build_segment(Geom::PathBuilder &, Node *, Node *);
104 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
105         Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
106     : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
107     , _subpaths(*this)
108     , _multi_path_manipulator(mpm)
109     , _path(path)
110     , _spcurve(new SPCurve())
111     , _dragpoint(new CurveDragPoint(*this))
112     , /* XML Tree being used here directly while it shouldn't be*/_observer(new PathManipulatorObserver(this, SP_OBJECT(path)->getRepr()))
113     , _edit_transform(et)
114     , _num_selected(0)
115     , _show_handles(true)
116     , _show_outline(false)
117     , _show_path_direction(false)
118     , _live_outline(true)
119     , _live_objects(true)
120     , _lpe_key(lpe_key)
122     if (_lpe_key.empty()) {
123         _i2d_transform = SP_ITEM(path)->i2d_affine();
124     } else {
125         _i2d_transform = Geom::identity();
126     }
127     _d2i_transform = _i2d_transform.inverse();
128     _dragpoint->setVisible(false);
130     _getGeometry();
132     _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
133     sp_canvas_item_hide(_outline);
134     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
135         SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
136     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
138     _selection.signal_update.connect(
139         sigc::mem_fun(*this, &PathManipulator::update));
140     _selection.signal_point_changed.connect(
141         sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
142     _desktop->signal_zoom_changed.connect(
143         sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
145     _createControlPointsFromGeometry();
148 PathManipulator::~PathManipulator()
150     delete _dragpoint;
151     delete _observer;
152     gtk_object_destroy(_outline);
153     _spcurve->unref();
154     clear();
157 /** Handle motion events to update the position of the curve drag point. */
158 bool PathManipulator::event(GdkEvent *event)
160     if (empty()) return false;
162     switch (event->type)
163     {
164     case GDK_MOTION_NOTIFY:
165         _updateDragPoint(event_point(event->motion));
166         break;
167     default: break;
168     }
169     return false;
172 /** Check whether the manipulator has any nodes. */
173 bool PathManipulator::empty() {
174     return !_path || _subpaths.empty();
177 /** Update the display and the outline of the path. */
178 void PathManipulator::update()
180     _createGeometryFromControlPoints();
183 /** Store the changes to the path in XML. */
184 void PathManipulator::writeXML()
186     if (!_live_outline)
187         _updateOutline();
188     if (!_live_objects)
189         _setGeometry();
191     if (!_path) return;
192     _observer->block();
193     if (!empty()) {
194         SP_OBJECT(_path)->updateRepr();
195         _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
196     } else {
197         // this manipulator will have to be destroyed right after this call
198         _getXMLNode()->removeObserver(*_observer);
199         sp_object_ref(_path);
200         _path->deleteObject(true, true);
201         sp_object_unref(_path);
202         _path = 0;
203     }
204     _observer->unblock();
207 /** Remove all nodes from the path. */
208 void PathManipulator::clear()
210     // no longer necessary since nodes remove themselves from selection on destruction
211     //_removeNodesFromSelection();
212     _subpaths.clear();
215 /** Select all nodes in subpaths that have something selected. */
216 void PathManipulator::selectSubpaths()
218     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
219         NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
220         for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
221             if (j->selected()) {
222                 // if at least one of the nodes from this subpath is selected,
223                 // select all nodes from this subpath
224                 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
225                     _selection.insert(ins.ptr());
226                 continue;
227             }
228         }
229     }
232 /** Move the selection forward or backward by one node in each subpath, based on the sign
233  * of the parameter. */
234 void PathManipulator::shiftSelection(int dir)
236     if (dir == 0) return;
237     if (_num_selected == 0) {
238         // select the first node of the path.
239         SubpathList::iterator s = _subpaths.begin();
240         if (s == _subpaths.end()) return;
241         NodeList::iterator n = (*s)->begin();
242         if (n != (*s)->end())
243             _selection.insert(n.ptr());
244         return;
245     }
246     // We cannot do any tricks here, like iterating in different directions based on
247     // the sign and only setting the selection of nodes behind us, because it would break
248     // for closed paths.
249     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
250         std::deque<bool> sels; // I hope this is specialized for bools!
251         unsigned num = 0;
252         
253         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
254             sels.push_back(j->selected());
255             _selection.erase(j.ptr());
256             ++num;
257         }
258         if (num == 0) continue; // should never happen! zero-node subpaths are not allowed
260         num = 0;
261         // In closed subpath, shift the selection cyclically. In an open one,
262         // let the selection 'slide into nothing' at ends.
263         if (dir > 0) {
264             if ((*i)->closed()) {
265                 bool last = sels.back();
266                 sels.pop_back();
267                 sels.push_front(last);
268             } else {
269                 sels.push_front(false);
270             }
271         } else {
272             if ((*i)->closed()) {
273                 bool first = sels.front();
274                 sels.pop_front();
275                 sels.push_back(first);
276             } else {
277                 sels.push_back(false);
278                 num = 1;
279             }
280         }
282         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
283             if (sels[num]) _selection.insert(j.ptr());
284             ++num;
285         }
286     }
289 /** Invert selection in the selected subpaths. */
290 void PathManipulator::invertSelectionInSubpaths()
292     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
293         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
294             if (j->selected()) {
295                 // found selected node - invert selection in this subpath
296                 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
297                     if (k->selected()) _selection.erase(k.ptr());
298                     else _selection.insert(k.ptr());
299                 }
300                 // next subpath
301                 break;
302             }
303         }
304     }
307 /** Insert a new node in the middle of each selected segment. */
308 void PathManipulator::insertNodes()
310     if (_num_selected < 2) return;
312     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
313         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
314             NodeList::iterator k = j.next();
315             if (k && j->selected() && k->selected()) {
316                 j = subdivideSegment(j, 0.5);
317                 _selection.insert(j.ptr());
318             }
319         }
320     }
323 /** Insert new nodes exactly at the positions of selected nodes while preserving shape.
324  * This is equivalent to breaking, except that it doesn't split into subpaths. */
325 void PathManipulator::duplicateNodes()
327     if (_num_selected == 0) return;
329     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
330         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
331             if (j->selected()) {
332                 NodeList::iterator k = j.next();
333                 Node *n = new Node(_multi_path_manipulator._path_data.node_data, *j);
335                 // Move the new node to the bottom of the Z-order. This way you can drag all
336                 // nodes that were selected before this operation without deselecting
337                 // everything because there is a new node above.
338                 n->sink();
340                 n->front()->setPosition(*j->front());
341                 j->front()->retract();
342                 j->setType(NODE_CUSP, false);
343                 (*i)->insert(k, n);
345                 // We need to manually call the selection change callback to refresh
346                 // the handle display correctly.
347                 // This call changes num_selected, but we call this once for a selected node
348                 // and once for an unselected node, so in the end the number stays correct.
349                 _selectionChanged(j.ptr(), true);
350                 _selectionChanged(n, false);
351             }
352         }
353     }
356 /** Replace contiguous selections of nodes in each subpath with one node. */
357 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
359     if (_num_selected < 2) return;
360     hideDragPoint();
362     bool pos_valid = preserve_pos;
363     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
364         SubpathPtr sp = *i;
365         unsigned num_selected = 0, num_unselected = 0;
366         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
367             if (j->selected()) ++num_selected;
368             else ++num_unselected;
369         }
370         if (num_selected < 2) continue;
371         if (num_unselected == 0) {
372             // if all nodes in a subpath are selected, the operation doesn't make much sense
373             continue;
374         }
376         // Start from unselected node in closed paths, so that we don't start in the middle
377         // of a selection
378         NodeList::iterator sel_beg = sp->begin(), sel_end;
379         if (sp->closed()) {
380             while (sel_beg->selected()) ++sel_beg;
381         }
383         // Work loop
384         while (num_selected > 0) {
385             // Find selected node
386             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
387             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
388                 "but there are still nodes to process!");
390             // note: this is initialized to zero, because the loop below counts sel_beg as well
391             // the loop conditions are simpler that way
392             unsigned num_points = 0;
393             bool use_pos = false;
394             Geom::Point back_pos, front_pos;
395             back_pos = *sel_beg->back();
397             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
398                 ++num_points;
399                 front_pos = *sel_end->front();
400                 if (pos_valid && sel_end == preserve_pos) use_pos = true;
401             }
402             if (num_points > 1) {
403                 Geom::Point joined_pos;
404                 if (use_pos) {
405                     joined_pos = preserve_pos->position();
406                     pos_valid = false;
407                 } else {
408                     joined_pos = Geom::middle_point(back_pos, front_pos);
409                 }
410                 sel_beg->setType(NODE_CUSP, false);
411                 sel_beg->move(joined_pos);
412                 // do not move handles if they aren't degenerate
413                 if (!sel_beg->back()->isDegenerate()) {
414                     sel_beg->back()->setPosition(back_pos);
415                 }
416                 if (!sel_end.prev()->front()->isDegenerate()) {
417                     sel_beg->front()->setPosition(front_pos);
418                 }
419                 sel_beg = sel_beg.next();
420                 while (sel_beg != sel_end) {
421                     NodeList::iterator next = sel_beg.next();
422                     sp->erase(sel_beg);
423                     sel_beg = next;
424                     --num_selected;
425                 }
426             }
427             --num_selected; // for the joined node or single selected node
428         }
429     }
432 /** Remove nodes in the middle of selected segments. */
433 void PathManipulator::weldSegments()
435     if (_num_selected < 2) return;
436     hideDragPoint();
438     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
439         SubpathPtr sp = *i;
440         unsigned num_selected = 0, num_unselected = 0;
441         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
442             if (j->selected()) ++num_selected;
443             else ++num_unselected;
444         }
445         if (num_selected < 3) continue;
446         if (num_unselected == 0 && sp->closed()) {
447             // if all nodes in a closed subpath are selected, the operation doesn't make much sense
448             continue;
449         }
451         // Start from unselected node in closed paths, so that we don't start in the middle
452         // of a selection
453         NodeList::iterator sel_beg = sp->begin(), sel_end;
454         if (sp->closed()) {
455             while (sel_beg->selected()) ++sel_beg;
456         }
458         // Work loop
459         while (num_selected > 0) {
460             // Find selected node
461             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
462             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
463                 "but there are still nodes to process!");
465             // note: this is initialized to zero, because the loop below counts sel_beg as well
466             // the loop conditions are simpler that way
467             unsigned num_points = 0;
469             // find the end of selected segment
470             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
471                 ++num_points;
472             }
473             if (num_points > 2) {
474                 // remove nodes in the middle
475                 sel_beg = sel_beg.next();
476                 while (sel_beg != sel_end.prev()) {
477                     NodeList::iterator next = sel_beg.next();
478                     sp->erase(sel_beg);
479                     sel_beg = next;
480                 }
481                 sel_beg = sel_end;
482             }
483             num_selected -= num_points;
484         }
485     }
488 /** Break the subpath at selected nodes. It also works for single node closed paths. */
489 void PathManipulator::breakNodes()
491     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
492         SubpathPtr sp = *i;
493         NodeList::iterator cur = sp->begin(), end = sp->end();
494         if (!sp->closed()) {
495             // Each open path must have at least two nodes so no checks are required.
496             // For 2-node open paths, cur == end
497             ++cur;
498             --end;
499         }
500         for (; cur != end; ++cur) {
501             if (!cur->selected()) continue;
502             SubpathPtr ins;
503             bool becomes_open = false;
505             if (sp->closed()) {
506                 // Move the node to break at to the beginning of path
507                 if (cur != sp->begin())
508                     sp->splice(sp->begin(), *sp, cur, sp->end());
509                 sp->setClosed(false);
510                 ins = sp;
511                 becomes_open = true;
512             } else {
513                 SubpathPtr new_sp(new NodeList(_subpaths));
514                 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
515                 _subpaths.insert(i, new_sp);
516                 ins = new_sp;
517             }
519             Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
520             ins->insert(ins->end(), n);
521             cur->setType(NODE_CUSP, false);
522             n->back()->setRelativePos(cur->back()->relativePos());
523             cur->back()->retract();
524             n->sink();
526             if (becomes_open) {
527                 cur = sp->begin(); // this will be increased to ++sp->begin()
528                 end = --sp->end();
529             }
530         }
531     }
534 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
535  * in a way that attempts to preserve the original shape of the curve. */
536 void PathManipulator::deleteNodes(bool keep_shape)
538     if (_num_selected == 0) return;
539     hideDragPoint();
541     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
542         SubpathPtr sp = *i;
544         // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
545         // in a closed one, delete entire subpath.
546         unsigned num_unselected = 0, num_selected = 0;
547         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
548             if (j->selected()) ++num_selected;
549             else ++num_unselected;
550         }
551         if (num_selected == 0) {
552             ++i;
553             continue;
554         }
555         if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
556             _subpaths.erase(i++);
557             continue;
558         }
560         // In closed paths, start from an unselected node - otherwise we might start in the middle
561         // of a selected stretch and the resulting bezier fit would be suboptimal
562         NodeList::iterator sel_beg = sp->begin(), sel_end;
563         if (sp->closed()) {
564             while (sel_beg->selected()) ++sel_beg;
565         }
566         sel_end = sel_beg;
567         
568         while (num_selected > 0) {
569             while (sel_beg && !sel_beg->selected()) {
570                 sel_beg = sel_beg.next();
571             }
572             sel_end = sel_beg;
574             while (sel_end && sel_end->selected()) {
575                 sel_end = sel_end.next();
576             }
577             
578             num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
579             sel_beg = sel_end;
580         }
581         ++i;
582     }
585 /** @brief Delete nodes between the two iterators.
586  * The given range can cross the beginning of the subpath in closed subpaths.
587  * @param start      Beginning of the range to delete
588  * @param end        End of the range
589  * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
590  *                   the shape before deletion
591  * @return Number of deleted nodes */
592 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
594     unsigned const samples_per_segment = 10;
595     double const t_step = 1.0 / samples_per_segment;
597     unsigned del_len = 0;
598     for (NodeList::iterator i = start; i != end; i = i.next()) {
599         ++del_len;
600     }
601     if (del_len == 0) return 0;
603     // set surrounding node types to cusp if:
604     // 1. keep_shape is on, or
605     // 2. we are deleting at the end or beginning of an open path
606     if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
607     if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
609     if (keep_shape && start.prev() && end) {
610         unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
611         Geom::Point *bezier_data = new Geom::Point[num_samples];
612         Geom::Point result[4];
613         unsigned seg = 0;
615         for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
616             Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
617             for (unsigned s = 0; s < samples_per_segment; ++s) {
618                 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
619             }
620             ++seg;
621         }
622         // Fill last point
623         bezier_data[num_samples - 1] = end->position();
624         // Compute replacement bezier curve
625         // TODO the fitting algorithm sucks - rewrite it to be awesome
626         bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
627         delete[] bezier_data;
629         start.prev()->front()->setPosition(result[1]);
630         end->back()->setPosition(result[2]);
631     }
633     // We can't use nl->erase(start, end), because it would break when the stretch
634     // crosses the beginning of a closed subpath
635     NodeList &nl = start->nodeList();
636     while (start != end) {
637         NodeList::iterator next = start.next();
638         nl.erase(start);
639         start = next;
640     }
642     return del_len;
645 /** Removes selected segments */
646 void PathManipulator::deleteSegments()
648     if (_num_selected == 0) return;
649     hideDragPoint();
651     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
652         SubpathPtr sp = *i;
653         bool has_unselected = false;
654         unsigned num_selected = 0;
655         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
656             if (j->selected()) {
657                 ++num_selected;
658             } else {
659                 has_unselected = true;
660             }
661         }
662         if (!has_unselected) {
663             _subpaths.erase(i++);
664             continue;
665         }
667         NodeList::iterator sel_beg = sp->begin();
668         if (sp->closed()) {
669             while (sel_beg && sel_beg->selected()) ++sel_beg;
670         }
671         while (num_selected > 0) {
672             if (!sel_beg->selected()) {
673                 sel_beg = sel_beg.next();
674                 continue;
675             }
676             NodeList::iterator sel_end = sel_beg;
677             unsigned num_points = 0;
678             while (sel_end && sel_end->selected()) {
679                 sel_end = sel_end.next();
680                 ++num_points;
681             }
682             if (num_points >= 2) {
683                 // Retract end handles
684                 sel_end.prev()->setType(NODE_CUSP, false);
685                 sel_end.prev()->back()->retract();
686                 sel_beg->setType(NODE_CUSP, false);
687                 sel_beg->front()->retract();
688                 if (sp->closed()) {
689                     // In closed paths, relocate the beginning of the path to the last selected
690                     // node and then unclose it. Remove the nodes from the first selected node
691                     // to the new end of path.
692                     if (sel_end.prev() != sp->begin())
693                         sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
694                     sp->setClosed(false);
695                     sp->erase(sel_beg.next(), sp->end());
696                 } else {
697                     // for open paths:
698                     // 1. At end or beginning, delete including the node on the end or beginning
699                     // 2. In the middle, delete only inner nodes
700                     if (sel_beg == sp->begin()) {
701                         sp->erase(sp->begin(), sel_end.prev());
702                     } else if (sel_end == sp->end()) {
703                         sp->erase(sel_beg.next(), sp->end());
704                     } else {
705                         SubpathPtr new_sp(new NodeList(_subpaths));
706                         new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
707                         _subpaths.insert(i, new_sp);
708                         if (sel_end.prev())
709                             sp->erase(sp->begin(), sel_end.prev());
710                     }
711                 }
712             }
713             sel_beg = sel_end;
714             num_selected -= num_points;
715         }
716         ++i;
717     }
720 /** Reverse subpaths of the path.
721  * @param selected_only If true, only paths that have at least one selected node
722  *                      will be reversed. Otherwise all subpaths will be reversed. */
723 void PathManipulator::reverseSubpaths(bool selected_only)
725     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
726         if (selected_only) {
727             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
728                 if (j->selected()) {
729                     (*i)->reverse();
730                     break; // continue with the next subpath
731                 }
732             }
733         } else {
734             (*i)->reverse();
735         }
736     }
739 /** Make selected segments curves / lines. */
740 void PathManipulator::setSegmentType(SegmentType type)
742     if (_num_selected == 0) return;
743     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
744         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
745             NodeList::iterator k = j.next();
746             if (!(k && j->selected() && k->selected())) continue;
747             switch (type) {
748             case SEGMENT_STRAIGHT:
749                 if (j->front()->isDegenerate() && k->back()->isDegenerate())
750                     break;
751                 j->front()->move(*j);
752                 k->back()->move(*k);
753                 break;
754             case SEGMENT_CUBIC_BEZIER:
755                 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
756                     break;
757                 // move both handles to 1/3 of the line
758                 j->front()->move(j->position() + (k->position() - j->position()) / 3);
759                 k->back()->move(k->position() + (j->position() - k->position()) / 3);
760                 break;
761             }
762         }
763     }
766 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
768     if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
769         n->setType(NODE_SMOOTH);
770     }
771     Handle *h = _chooseHandle(n, which);
772     double length_change;
774     if (pixel) {
775         length_change = 1.0 / _desktop->current_zoom() * dir;
776     } else {
777         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
778         length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
779         length_change *= dir;
780     }
782     Geom::Point relpos;
783     if (h->isDegenerate()) {
784         if (dir < 0) return;
785         Node *nh = n->nodeToward(h);
786         if (!nh) return;
787         relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
788     } else {
789         relpos = h->relativePos();
790         double rellen = relpos.length();
791         relpos *= ((rellen + length_change) / rellen);
792     }
793     h->setRelativePos(relpos);
794     update();
796     gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
797     _commit(_("Scale handle"), key);
800 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
802     if (n->type() != NODE_CUSP) {
803         n->setType(NODE_CUSP);
804     }
805     Handle *h = _chooseHandle(n, which);
806     if (h->isDegenerate()) return;
808     double angle;
809     if (pixel) {
810         // Rotate by "one pixel"
811         angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
812     } else {
813         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
814         int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
815         angle = M_PI * dir / snaps;
816     }
818     h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
819     update();
820     gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
821     _commit(_("Rotate handle"), key);
824 Handle *PathManipulator::_chooseHandle(Node *n, int which)
826     NodeList::iterator i = NodeList::get_iterator(n);
827     Node *prev = i.prev().ptr();
828     Node *next = i.next().ptr();
830     // on an endnode, the remaining handle automatically wins
831     if (!next) return n->back();
832     if (!prev) return n->front();
834     // compare X coord ofline segments
835     Geom::Point npos = next->position();
836     Geom::Point ppos = prev->position();
837     if (which < 0) {
838         // pick left handle.
839         // we just swap the handles and pick the right handle below.
840         std::swap(npos, ppos);
841     }
843     if (npos[Geom::X] >= ppos[Geom::X]) {
844         return n->front();
845     } else {
846         return n->back();
847     }
850 /** Set the visibility of handles. */
851 void PathManipulator::showHandles(bool show)
853     if (show == _show_handles) return;
854     if (show) {
855         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
856             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
857                 if (!j->selected()) continue;
858                 j->showHandles(true);
859                 if (j.prev()) j.prev()->showHandles(true);
860                 if (j.next()) j.next()->showHandles(true);
861             }
862         }
863     } else {
864         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
865             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
866                 j->showHandles(false);
867             }
868         }
869     }
870     _show_handles = show;
873 /** Set the visibility of outline. */
874 void PathManipulator::showOutline(bool show)
876     if (show == _show_outline) return;
877     _show_outline = show;
878     _updateOutline();
881 void PathManipulator::showPathDirection(bool show)
883     if (show == _show_path_direction) return;
884     _show_path_direction = show;
885     _updateOutline();
888 void PathManipulator::setLiveOutline(bool set)
890     _live_outline = set;
893 void PathManipulator::setLiveObjects(bool set)
895     _live_objects = set;
898 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
900     Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
901     _edit_transform = tnew;
902     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
903         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
904             j->transform(delta);
905         }
906     }
907     _createGeometryFromControlPoints();
910 /** Hide the curve drag point until the next motion event.
911  * This should be called at the beginning of every method that can delete nodes.
912  * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
913 void PathManipulator::hideDragPoint()
915     _dragpoint->setVisible(false);
916     _dragpoint->setIterator(NodeList::iterator());
919 /** Insert a node in the segment beginning with the supplied iterator,
920  * at the given time value */
921 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
923     if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
924     NodeList &list = NodeList::get(first);
925     NodeList::iterator second = first.next();
926     if (!second) throw std::invalid_argument("Subdivide after last node in open path");
928     // We need to insert the segment after 'first'. We can't simply use 'second'
929     // as the point of insertion, because when 'first' is the last node of closed path,
930     // the new node will be inserted as the first node instead.
931     NodeList::iterator insert_at = first;
932     ++insert_at;
934     NodeList::iterator inserted;
935     if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
936         // for a line segment, insert a cusp node
937         Node *n = new Node(_multi_path_manipulator._path_data.node_data,
938             Geom::lerp(t, first->position(), second->position()));
939         n->setType(NODE_CUSP, false);
940         inserted = list.insert(insert_at, n);
941     } else {
942         // build bezier curve and subdivide
943         Geom::CubicBezier temp(first->position(), first->front()->position(),
944             second->back()->position(), second->position());
945         std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
946         std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
948         // set new handle positions
949         Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
950         n->back()->setPosition(seg1[2]);
951         n->front()->setPosition(seg2[1]);
952         n->setType(NODE_SMOOTH, false);
953         inserted = list.insert(insert_at, n);
955         first->front()->move(seg1[1]);
956         second->back()->move(seg2[2]);
957     }
958     return inserted;
961 /** Find the node that is closest/farthest from the origin
962  * @param origin Point of reference
963  * @param search_selected Consider selected nodes
964  * @param search_unselected Consider unselected nodes
965  * @param closest If true, return closest node, if false, return farthest
966  * @return The matching node, or an empty iterator if none found
967  */
968 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
969     bool search_unselected, bool closest)
971     NodeList::iterator match;
972     double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
973     if (_num_selected == 0 && !search_unselected) return match;
975     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
976         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
977             if(j->selected()) {
978                 if (!search_selected) continue;
979             } else {
980                 if (!search_unselected) continue;
981             }
982             double dist = Geom::distance(*j, *origin);
983             bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
984             if (cond) {
985                 match = j;
986                 extr_dist = dist;
987             }
988         }
989     }
990     return match;
993 /** Called by the XML observer when something else than us modifies the path. */
994 void PathManipulator::_externalChange(unsigned type)
996     hideDragPoint();
998     switch (type) {
999     case PATH_CHANGE_D: {
1000         _getGeometry();
1002         // ugly: stored offsets of selected nodes in a vector
1003         // vector<bool> should be specialized so that it takes only 1 bit per value
1004         std::vector<bool> selpos;
1005         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1006             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1007                 selpos.push_back(j->selected());
1008             }
1009         }
1010         unsigned size = selpos.size(), curpos = 0;
1012         _createControlPointsFromGeometry();
1014         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1015             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1016                 if (curpos >= size) goto end_restore;
1017                 if (selpos[curpos]) _selection.insert(j.ptr());
1018                 ++curpos;
1019             }
1020         }
1021         end_restore:
1023         _updateOutline();
1024         } break;
1025     case PATH_CHANGE_TRANSFORM: {
1026         Geom::Matrix i2d_change = _d2i_transform;
1027         _i2d_transform = SP_ITEM(_path)->i2d_affine();
1028         _d2i_transform = _i2d_transform.inverse();
1029         i2d_change *= _i2d_transform;
1030         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1031             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1032                 j->transform(i2d_change);
1033             }
1034         }
1035         _updateOutline();
1036         } break;
1037     default: break;
1038     }
1041 /** Create nodes and handles based on the XML of the edited path. */
1042 void PathManipulator::_createControlPointsFromGeometry()
1044     clear();
1046     // sanitize pathvector and store it in SPCurve,
1047     // so that _updateDragPoint doesn't crash on paths with naked movetos
1048     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1049     for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1050         // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1051         // When we erase an element, the next one slides into position,
1052         // so we do not increment the iterator even though it is theoretically invalidated.
1053         if (i->empty()) {
1054             pathv.erase(i);
1055         } else {
1056             ++i;
1057         }
1058     }
1059     _spcurve->set_pathvector(pathv);
1061     pathv *= (_edit_transform * _i2d_transform);
1063     // in this loop, we know that there are no zero-segment subpaths
1064     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1065         // prepare new subpath
1066         SubpathPtr subpath(new NodeList(_subpaths));
1067         _subpaths.push_back(subpath);
1069         Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1070         subpath->push_back(previous_node);
1071         Geom::Curve const &cseg = pit->back_closed();
1072         bool fuse_ends = pit->closed()
1073             && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1075         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1076             Geom::Point pos = cit->finalPoint();
1077             Node *current_node;
1078             // if the closing segment is degenerate and the path is closed, we need to move
1079             // the handle of the first node instead of creating a new one
1080             if (fuse_ends && cit == --(pit->end_open())) {
1081                 current_node = subpath->begin().get_pointer();
1082             } else {
1083                 /* regardless of segment type, create a new node at the end
1084                  * of this segment (unless this is the last segment of a closed path
1085                  * with a degenerate closing segment */
1086                 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1087                 subpath->push_back(current_node);
1088             }
1089             // if this is a bezier segment, move handles appropriately
1090             if (Geom::CubicBezier const *cubic_bezier =
1091                 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1092             {
1093                 std::vector<Geom::Point> points = cubic_bezier->points();
1095                 previous_node->front()->setPosition(points[1]);
1096                 current_node ->back() ->setPosition(points[2]);
1097             }
1098             previous_node = current_node;
1099         }
1100         // If the path is closed, make the list cyclic
1101         if (pit->closed()) subpath->setClosed(true);
1102     }
1104     // we need to set the nodetypes after all the handles are in place,
1105     // so that pickBestType works correctly
1106     // TODO maybe migrate to inkscape:node-types?
1107     // TODO move this into SPPath - do not manipulate directly
1109     //XML Tree being used here directly while it shouldn't be.
1110     gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : 0;
1111     std::string nodetype_string = nts_raw ? nts_raw : "";
1112     /* Calculate the needed length of the nodetype string.
1113      * For closed paths, the entry is duplicated for the starting node,
1114      * so we can just use the count of segments including the closing one
1115      * to include the extra end node. */
1116     std::string::size_type nodetype_len = 0;
1117     for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1118         if (i->empty()) continue;
1119         nodetype_len += i->size_closed();
1120     }
1121     /* pad the string to required length with a bogus value.
1122      * 'b' and any other letter not recognized by the parser causes the best fit to be set
1123      * as the node type */
1124     if (nodetype_len > nodetype_string.size()) {
1125         nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1126     }
1127     std::string::iterator tsi = nodetype_string.begin();
1128     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1129         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1130             j->setType(Node::parse_nodetype(*tsi++), false);
1131         }
1132         if ((*i)->closed()) {
1133             // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1134             // the first one to remain backward compatible.
1135             (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1136         }
1137     }
1140 /** Construct the geometric representation of nodes and handles, update the outline
1141  * and display */
1142 void PathManipulator::_createGeometryFromControlPoints()
1144     Geom::PathBuilder builder;
1145     for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1146         SubpathPtr subpath = *spi;
1147         if (subpath->empty()) {
1148             _subpaths.erase(spi++);
1149             continue;
1150         }
1151         NodeList::iterator prev = subpath->begin();
1152         builder.moveTo(prev->position());
1154         for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1155             build_segment(builder, prev.ptr(), i.ptr());
1156             prev = i;
1157         }
1158         if (subpath->closed()) {
1159             // Here we link the last and first node if the path is closed.
1160             // If the last segment is Bezier, we add it.
1161             if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1162                 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1163             }
1164             // if that segment is linear, we just call closePath().
1165             builder.closePath();
1166         }
1167         ++spi;
1168     }
1169     builder.finish();
1170     _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1171     if (_live_outline)
1172         _updateOutline();
1173     if (_live_objects)
1174         _setGeometry();
1177 /** Build one segment of the geometric representation.
1178  * @relates PathManipulator */
1179 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1181     if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1182     {
1183         // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1184         // and trying to display a path using them results in funny artifacts.
1185         builder.lineTo(cur_node->position());
1186     } else {
1187         // this is a bezier segment
1188         builder.curveTo(
1189             prev_node->front()->position(),
1190             cur_node->back()->position(),
1191             cur_node->position());
1192     }
1195 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1196 std::string PathManipulator::_createTypeString()
1198     // precondition: no single-node subpaths
1199     std::stringstream tstr;
1200     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1201         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1202             tstr << j->type();
1203         }
1204         // nodestring format peculiarity: first node is counted twice for closed paths
1205         if ((*i)->closed()) tstr << (*i)->begin()->type();
1206     }
1207     return tstr.str();
1210 /** Update the path outline. */
1211 void PathManipulator::_updateOutline()
1213     if (!_show_outline) {
1214         sp_canvas_item_hide(_outline);
1215         return;
1216     }
1218     Geom::PathVector pv = _spcurve->get_pathvector();
1219     pv *= (_edit_transform * _i2d_transform);
1220     // This SPCurve thing has to be killed with extreme prejudice
1221     SPCurve *_hc = new SPCurve();
1222     if (_show_path_direction) {
1223         // To show the direction, we append additional subpaths which consist of a single
1224         // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1225         // at an angle 150 degrees from the unit tangent. This creates the appearance
1226         // of little 'harpoons' that show the direction of the subpaths.
1227         Geom::PathVector arrows;
1228         for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1229             Geom::Path &path = *i;
1230             for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1231                 Geom::Point at = j->pointAt(0.5);
1232                 Geom::Point ut = j->unitTangentAt(0.5);
1233                 // rotate the point 
1234                 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1235                 Geom::Point arrow_end = _desktop->w2d(
1236                     _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1238                 Geom::Path arrow(at);
1239                 arrow.appendNew<Geom::LineSegment>(arrow_end);
1240                 arrows.push_back(arrow);
1241             }
1242         }
1243         pv.insert(pv.end(), arrows.begin(), arrows.end());
1244     }
1245     _hc->set_pathvector(pv);
1246     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1247     sp_canvas_item_show(_outline);
1248     _hc->unref();
1251 /** Retrieve the geometry of the edited object from the object tree */
1252 void PathManipulator::_getGeometry()
1254     using namespace Inkscape::LivePathEffect;
1255     if (!_lpe_key.empty()) {
1256         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1257         if (lpe) {
1258             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1259             _spcurve->unref();
1260             _spcurve = new SPCurve(pathparam->get_pathvector());
1261         }
1262     } else {
1263         _spcurve->unref();
1264         _spcurve = sp_path_get_curve_for_edit(_path);
1265     }
1268 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1269 void PathManipulator::_setGeometry()
1271     using namespace Inkscape::LivePathEffect;
1272     if (empty()) return;
1274     if (!_lpe_key.empty()) {
1275         // copied from nodepath.cpp
1276         // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1277         // a LivePathEffectObject. (mad laughter)
1278         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1279         if (lpe) {
1280             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1281             pathparam->set_new_value(_spcurve->get_pathvector(), false);
1282             LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1283         }
1284     } else {
1285         //XML Tree being used here directly while it shouldn't be.
1286         if (_path->getRepr()->attribute("inkscape:original-d"))
1287             sp_path_set_original_curve(_path, _spcurve, false, false);
1288         else
1289             SP_SHAPE(_path)->setCurve(_spcurve, false);
1290     }
1293 /** Figure out in what attribute to store the nodetype string. */
1294 Glib::ustring PathManipulator::_nodetypesKey()
1296     if (_lpe_key.empty()) return "sodipodi:nodetypes";
1297     return _lpe_key + "-nodetypes";
1300 /** Return the XML node we are editing.
1301  * This method is wrong but necessary at the moment. */
1302 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1304     //XML Tree being used here directly while it shouldn't be.
1305     if (_lpe_key.empty()) return _path->getRepr();
1306     //XML Tree being used here directly while it shouldn't be.
1307     return LIVEPATHEFFECT(_path)->getRepr();
1310 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1312     if (event->button != 1) return false;
1313     if (held_alt(*event) && held_control(*event)) {
1314         // Ctrl+Alt+click: delete nodes
1315         hideDragPoint();
1316         NodeList::iterator iter = NodeList::get_iterator(n);
1317         NodeList &nl = iter->nodeList();
1319         if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1320             // Removing last node of closed path - delete it
1321             nl.kill();
1322         } else {
1323             // In other cases, delete the node under cursor
1324             _deleteStretch(iter, iter.next(), true);
1325         }
1327         if (!empty()) { 
1328             update();
1329         }
1330         // We need to call MPM's method because it could have been our last node
1331         _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1333         return true;
1334     } else if (held_control(*event)) {
1335         // Ctrl+click: cycle between node types
1336         if (!n->isEndNode()) {
1337             n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1338             update();
1339             _commit(_("Cycle node type"));
1340         }
1341         return true;
1342     }
1343     return false;
1346 void PathManipulator::_handleGrabbed()
1348     _selection.hideTransformHandles();
1351 void PathManipulator::_handleUngrabbed()
1353     _selection.restoreTransformHandles();
1354     _commit(_("Drag handle"));
1357 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1359     // retracting by Ctrl+click
1360     if (event->button == 1 && held_control(*event)) {
1361         h->move(h->parent()->position());
1362         update();
1363         _commit(_("Retract handle"));
1364         return true;
1365     }
1366     return false;
1369 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1371     if (selected) ++_num_selected;
1372     else --_num_selected;
1374     // don't do anything if we do not show handles
1375     if (!_show_handles) return;
1377     // only do something if a node changed selection state
1378     Node *node = dynamic_cast<Node*>(p);
1379     if (!node) return;
1381     // update handle display
1382     NodeList::iterator iters[5];
1383     iters[2] = NodeList::get_iterator(node);
1384     iters[1] = iters[2].prev();
1385     iters[3] = iters[2].next();
1386     if (selected) {
1387         // selection - show handles on this node and adjacent ones
1388         node->showHandles(true);
1389         if (iters[1]) iters[1]->showHandles(true);
1390         if (iters[3]) iters[3]->showHandles(true);
1391     } else {
1392         /* Deselection is more complex.
1393          * The change might affect 3 nodes - this one and two adjacent.
1394          * If the node and both its neighbors are deselected, hide handles.
1395          * Otherwise, leave as is. */
1396         if (iters[1]) iters[0] = iters[1].prev();
1397         if (iters[3]) iters[4] = iters[3].next();
1398         bool nodesel[5];
1399         for (int i = 0; i < 5; ++i) {
1400             nodesel[i] = iters[i] && iters[i]->selected();
1401         }
1402         for (int i = 1; i < 4; ++i) {
1403             if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1404                 iters[i]->showHandles(false);
1405             }
1406         }
1407     }
1410 /** Removes all nodes belonging to this manipulator from the control pont selection */
1411 void PathManipulator::_removeNodesFromSelection()
1413     // remove this manipulator's nodes from selection
1414     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1415         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1416             _selection.erase(j.get_pointer());
1417         }
1418     }
1421 /** Update the XML representation and put the specified annotation on the undo stack */
1422 void PathManipulator::_commit(Glib::ustring const &annotation)
1424     writeXML();
1425     DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1428 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1430     writeXML();
1431     DocumentUndo::maybeDone(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1432                             annotation.data());
1435 /** Update the position of the curve drag point such that it is over the nearest
1436  * point of the path. */
1437 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1439     Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1440     Geom::PathVector pv = _spcurve->get_pathvector();
1441     boost::optional<Geom::PathVectorPosition> pvp
1442         = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1443     if (!pvp) return;
1444     Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1445     
1446     double fracpart;
1447     std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1448     for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1449     NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1450     
1451     double stroke_tolerance = _getStrokeTolerance();
1452     if (first && first.next() &&
1453         fracpart != 0.0 &&
1454         Geom::distance(evp, nearest_point) < stroke_tolerance)
1455     {
1456         _dragpoint->setVisible(true);
1457         _dragpoint->setPosition(_desktop->w2d(nearest_point));
1458         _dragpoint->setSize(2 * stroke_tolerance);
1459         _dragpoint->setTimeValue(fracpart);
1460         _dragpoint->setIterator(first);
1461     } else {
1462         _dragpoint->setVisible(false);
1463     }
1466 /// This is called on zoom change to update the direction arrows
1467 void PathManipulator::_updateOutlineOnZoomChange()
1469     if (_show_path_direction) _updateOutline();
1472 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1473  * or segment selection, in window coordinates. */
1474 double PathManipulator::_getStrokeTolerance()
1476     /* Stroke event tolerance is equal to half the stroke's width plus the global
1477      * drag tolerance setting.  */
1478     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1479     double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1480     if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1481         ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1482             * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1483             * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1484     }
1485     return ret;
1488 } // namespace UI
1489 } // namespace Inkscape
1491 /*
1492   Local Variables:
1493   mode:c++
1494   c-file-style:"stroustrup"
1495   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1496   indent-tabs-mode:nil
1497   fill-column:99
1498   End:
1499 */
1500 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :