Code

Node tool: fix Tab and Shift+Tab
[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 (SubpathList::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 /** Invert selection in the selected subpaths. */
233 void PathManipulator::invertSelectionInSubpaths()
235     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
236         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
237             if (j->selected()) {
238                 // found selected node - invert selection in this subpath
239                 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
240                     if (k->selected()) _selection.erase(k.ptr());
241                     else _selection.insert(k.ptr());
242                 }
243                 // next subpath
244                 break;
245             }
246         }
247     }
250 /** Insert a new node in the middle of each selected segment. */
251 void PathManipulator::insertNodes()
253     if (_num_selected < 2) return;
255     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
256         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
257             NodeList::iterator k = j.next();
258             if (k && j->selected() && k->selected()) {
259                 j = subdivideSegment(j, 0.5);
260                 _selection.insert(j.ptr());
261             }
262         }
263     }
266 /** Insert new nodes exactly at the positions of selected nodes while preserving shape.
267  * This is equivalent to breaking, except that it doesn't split into subpaths. */
268 void PathManipulator::duplicateNodes()
270     if (_num_selected == 0) return;
272     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
273         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
274             if (j->selected()) {
275                 NodeList::iterator k = j.next();
276                 Node *n = new Node(_multi_path_manipulator._path_data.node_data, *j);
278                 // Move the new node to the bottom of the Z-order. This way you can drag all
279                 // nodes that were selected before this operation without deselecting
280                 // everything because there is a new node above.
281                 n->sink();
283                 n->front()->setPosition(*j->front());
284                 j->front()->retract();
285                 j->setType(NODE_CUSP, false);
286                 (*i)->insert(k, n);
288                 // We need to manually call the selection change callback to refresh
289                 // the handle display correctly.
290                 // This call changes num_selected, but we call this once for a selected node
291                 // and once for an unselected node, so in the end the number stays correct.
292                 _selectionChanged(j.ptr(), true);
293                 _selectionChanged(n, false);
294             }
295         }
296     }
299 /** Replace contiguous selections of nodes in each subpath with one node. */
300 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
302     if (_num_selected < 2) return;
303     hideDragPoint();
305     bool pos_valid = preserve_pos;
306     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
307         SubpathPtr sp = *i;
308         unsigned num_selected = 0, num_unselected = 0;
309         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
310             if (j->selected()) ++num_selected;
311             else ++num_unselected;
312         }
313         if (num_selected < 2) continue;
314         if (num_unselected == 0) {
315             // if all nodes in a subpath are selected, the operation doesn't make much sense
316             continue;
317         }
319         // Start from unselected node in closed paths, so that we don't start in the middle
320         // of a selection
321         NodeList::iterator sel_beg = sp->begin(), sel_end;
322         if (sp->closed()) {
323             while (sel_beg->selected()) ++sel_beg;
324         }
326         // Work loop
327         while (num_selected > 0) {
328             // Find selected node
329             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
330             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
331                 "but there are still nodes to process!");
333             // note: this is initialized to zero, because the loop below counts sel_beg as well
334             // the loop conditions are simpler that way
335             unsigned num_points = 0;
336             bool use_pos = false;
337             Geom::Point back_pos, front_pos;
338             back_pos = *sel_beg->back();
340             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
341                 ++num_points;
342                 front_pos = *sel_end->front();
343                 if (pos_valid && sel_end == preserve_pos) use_pos = true;
344             }
345             if (num_points > 1) {
346                 Geom::Point joined_pos;
347                 if (use_pos) {
348                     joined_pos = preserve_pos->position();
349                     pos_valid = false;
350                 } else {
351                     joined_pos = Geom::middle_point(back_pos, front_pos);
352                 }
353                 sel_beg->setType(NODE_CUSP, false);
354                 sel_beg->move(joined_pos);
355                 // do not move handles if they aren't degenerate
356                 if (!sel_beg->back()->isDegenerate()) {
357                     sel_beg->back()->setPosition(back_pos);
358                 }
359                 if (!sel_end.prev()->front()->isDegenerate()) {
360                     sel_beg->front()->setPosition(front_pos);
361                 }
362                 sel_beg = sel_beg.next();
363                 while (sel_beg != sel_end) {
364                     NodeList::iterator next = sel_beg.next();
365                     sp->erase(sel_beg);
366                     sel_beg = next;
367                     --num_selected;
368                 }
369             }
370             --num_selected; // for the joined node or single selected node
371         }
372     }
375 /** Remove nodes in the middle of selected segments. */
376 void PathManipulator::weldSegments()
378     if (_num_selected < 2) return;
379     hideDragPoint();
381     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
382         SubpathPtr sp = *i;
383         unsigned num_selected = 0, num_unselected = 0;
384         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
385             if (j->selected()) ++num_selected;
386             else ++num_unselected;
387         }
388         if (num_selected < 3) continue;
389         if (num_unselected == 0 && sp->closed()) {
390             // if all nodes in a closed subpath are selected, the operation doesn't make much sense
391             continue;
392         }
394         // Start from unselected node in closed paths, so that we don't start in the middle
395         // of a selection
396         NodeList::iterator sel_beg = sp->begin(), sel_end;
397         if (sp->closed()) {
398             while (sel_beg->selected()) ++sel_beg;
399         }
401         // Work loop
402         while (num_selected > 0) {
403             // Find selected node
404             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
405             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
406                 "but there are still nodes to process!");
408             // note: this is initialized to zero, because the loop below counts sel_beg as well
409             // the loop conditions are simpler that way
410             unsigned num_points = 0;
412             // find the end of selected segment
413             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
414                 ++num_points;
415             }
416             if (num_points > 2) {
417                 // remove nodes in the middle
418                 sel_beg = sel_beg.next();
419                 while (sel_beg != sel_end.prev()) {
420                     NodeList::iterator next = sel_beg.next();
421                     sp->erase(sel_beg);
422                     sel_beg = next;
423                 }
424                 sel_beg = sel_end;
425             }
426             num_selected -= num_points;
427         }
428     }
431 /** Break the subpath at selected nodes. It also works for single node closed paths. */
432 void PathManipulator::breakNodes()
434     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
435         SubpathPtr sp = *i;
436         NodeList::iterator cur = sp->begin(), end = sp->end();
437         if (!sp->closed()) {
438             // Each open path must have at least two nodes so no checks are required.
439             // For 2-node open paths, cur == end
440             ++cur;
441             --end;
442         }
443         for (; cur != end; ++cur) {
444             if (!cur->selected()) continue;
445             SubpathPtr ins;
446             bool becomes_open = false;
448             if (sp->closed()) {
449                 // Move the node to break at to the beginning of path
450                 if (cur != sp->begin())
451                     sp->splice(sp->begin(), *sp, cur, sp->end());
452                 sp->setClosed(false);
453                 ins = sp;
454                 becomes_open = true;
455             } else {
456                 SubpathPtr new_sp(new NodeList(_subpaths));
457                 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
458                 _subpaths.insert(i, new_sp);
459                 ins = new_sp;
460             }
462             Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
463             ins->insert(ins->end(), n);
464             cur->setType(NODE_CUSP, false);
465             n->back()->setRelativePos(cur->back()->relativePos());
466             cur->back()->retract();
467             n->sink();
469             if (becomes_open) {
470                 cur = sp->begin(); // this will be increased to ++sp->begin()
471                 end = --sp->end();
472             }
473         }
474     }
477 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
478  * in a way that attempts to preserve the original shape of the curve. */
479 void PathManipulator::deleteNodes(bool keep_shape)
481     if (_num_selected == 0) return;
482     hideDragPoint();
484     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
485         SubpathPtr sp = *i;
487         // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
488         // in a closed one, delete entire subpath.
489         unsigned num_unselected = 0, num_selected = 0;
490         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
491             if (j->selected()) ++num_selected;
492             else ++num_unselected;
493         }
494         if (num_selected == 0) {
495             ++i;
496             continue;
497         }
498         if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
499             _subpaths.erase(i++);
500             continue;
501         }
503         // In closed paths, start from an unselected node - otherwise we might start in the middle
504         // of a selected stretch and the resulting bezier fit would be suboptimal
505         NodeList::iterator sel_beg = sp->begin(), sel_end;
506         if (sp->closed()) {
507             while (sel_beg->selected()) ++sel_beg;
508         }
509         sel_end = sel_beg;
510         
511         while (num_selected > 0) {
512             while (sel_beg && !sel_beg->selected()) {
513                 sel_beg = sel_beg.next();
514             }
515             sel_end = sel_beg;
517             while (sel_end && sel_end->selected()) {
518                 sel_end = sel_end.next();
519             }
520             
521             num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
522             sel_beg = sel_end;
523         }
524         ++i;
525     }
528 /** @brief Delete nodes between the two iterators.
529  * The given range can cross the beginning of the subpath in closed subpaths.
530  * @param start      Beginning of the range to delete
531  * @param end        End of the range
532  * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
533  *                   the shape before deletion
534  * @return Number of deleted nodes */
535 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
537     unsigned const samples_per_segment = 10;
538     double const t_step = 1.0 / samples_per_segment;
540     unsigned del_len = 0;
541     for (NodeList::iterator i = start; i != end; i = i.next()) {
542         ++del_len;
543     }
544     if (del_len == 0) return 0;
546     // set surrounding node types to cusp if:
547     // 1. keep_shape is on, or
548     // 2. we are deleting at the end or beginning of an open path
549     if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
550     if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
552     if (keep_shape && start.prev() && end) {
553         unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
554         Geom::Point *bezier_data = new Geom::Point[num_samples];
555         Geom::Point result[4];
556         unsigned seg = 0;
558         for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
559             Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
560             for (unsigned s = 0; s < samples_per_segment; ++s) {
561                 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
562             }
563             ++seg;
564         }
565         // Fill last point
566         bezier_data[num_samples - 1] = end->position();
567         // Compute replacement bezier curve
568         // TODO the fitting algorithm sucks - rewrite it to be awesome
569         bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
570         delete[] bezier_data;
572         start.prev()->front()->setPosition(result[1]);
573         end->back()->setPosition(result[2]);
574     }
576     // We can't use nl->erase(start, end), because it would break when the stretch
577     // crosses the beginning of a closed subpath
578     NodeList &nl = start->nodeList();
579     while (start != end) {
580         NodeList::iterator next = start.next();
581         nl.erase(start);
582         start = next;
583     }
585     return del_len;
588 /** Removes selected segments */
589 void PathManipulator::deleteSegments()
591     if (_num_selected == 0) return;
592     hideDragPoint();
594     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
595         SubpathPtr sp = *i;
596         bool has_unselected = false;
597         unsigned num_selected = 0;
598         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
599             if (j->selected()) {
600                 ++num_selected;
601             } else {
602                 has_unselected = true;
603             }
604         }
605         if (!has_unselected) {
606             _subpaths.erase(i++);
607             continue;
608         }
610         NodeList::iterator sel_beg = sp->begin();
611         if (sp->closed()) {
612             while (sel_beg && sel_beg->selected()) ++sel_beg;
613         }
614         while (num_selected > 0) {
615             if (!sel_beg->selected()) {
616                 sel_beg = sel_beg.next();
617                 continue;
618             }
619             NodeList::iterator sel_end = sel_beg;
620             unsigned num_points = 0;
621             while (sel_end && sel_end->selected()) {
622                 sel_end = sel_end.next();
623                 ++num_points;
624             }
625             if (num_points >= 2) {
626                 // Retract end handles
627                 sel_end.prev()->setType(NODE_CUSP, false);
628                 sel_end.prev()->back()->retract();
629                 sel_beg->setType(NODE_CUSP, false);
630                 sel_beg->front()->retract();
631                 if (sp->closed()) {
632                     // In closed paths, relocate the beginning of the path to the last selected
633                     // node and then unclose it. Remove the nodes from the first selected node
634                     // to the new end of path.
635                     if (sel_end.prev() != sp->begin())
636                         sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
637                     sp->setClosed(false);
638                     sp->erase(sel_beg.next(), sp->end());
639                 } else {
640                     // for open paths:
641                     // 1. At end or beginning, delete including the node on the end or beginning
642                     // 2. In the middle, delete only inner nodes
643                     if (sel_beg == sp->begin()) {
644                         sp->erase(sp->begin(), sel_end.prev());
645                     } else if (sel_end == sp->end()) {
646                         sp->erase(sel_beg.next(), sp->end());
647                     } else {
648                         SubpathPtr new_sp(new NodeList(_subpaths));
649                         new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
650                         _subpaths.insert(i, new_sp);
651                         if (sel_end.prev())
652                             sp->erase(sp->begin(), sel_end.prev());
653                     }
654                 }
655             }
656             sel_beg = sel_end;
657             num_selected -= num_points;
658         }
659         ++i;
660     }
663 /** Reverse subpaths of the path.
664  * @param selected_only If true, only paths that have at least one selected node
665  *                      will be reversed. Otherwise all subpaths will be reversed. */
666 void PathManipulator::reverseSubpaths(bool selected_only)
668     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
669         if (selected_only) {
670             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
671                 if (j->selected()) {
672                     (*i)->reverse();
673                     break; // continue with the next subpath
674                 }
675             }
676         } else {
677             (*i)->reverse();
678         }
679     }
682 /** Make selected segments curves / lines. */
683 void PathManipulator::setSegmentType(SegmentType type)
685     if (_num_selected == 0) return;
686     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
687         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
688             NodeList::iterator k = j.next();
689             if (!(k && j->selected() && k->selected())) continue;
690             switch (type) {
691             case SEGMENT_STRAIGHT:
692                 if (j->front()->isDegenerate() && k->back()->isDegenerate())
693                     break;
694                 j->front()->move(*j);
695                 k->back()->move(*k);
696                 break;
697             case SEGMENT_CUBIC_BEZIER:
698                 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
699                     break;
700                 // move both handles to 1/3 of the line
701                 j->front()->move(j->position() + (k->position() - j->position()) / 3);
702                 k->back()->move(k->position() + (j->position() - k->position()) / 3);
703                 break;
704             }
705         }
706     }
709 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
711     if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
712         n->setType(NODE_SMOOTH);
713     }
714     Handle *h = _chooseHandle(n, which);
715     double length_change;
717     if (pixel) {
718         length_change = 1.0 / _desktop->current_zoom() * dir;
719     } else {
720         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
721         length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
722         length_change *= dir;
723     }
725     Geom::Point relpos;
726     if (h->isDegenerate()) {
727         if (dir < 0) return;
728         Node *nh = n->nodeToward(h);
729         if (!nh) return;
730         relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
731     } else {
732         relpos = h->relativePos();
733         double rellen = relpos.length();
734         relpos *= ((rellen + length_change) / rellen);
735     }
736     h->setRelativePos(relpos);
737     update();
739     gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
740     _commit(_("Scale handle"), key);
743 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
745     if (n->type() != NODE_CUSP) {
746         n->setType(NODE_CUSP);
747     }
748     Handle *h = _chooseHandle(n, which);
749     if (h->isDegenerate()) return;
751     double angle;
752     if (pixel) {
753         // Rotate by "one pixel"
754         angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
755     } else {
756         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
757         int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
758         angle = M_PI * dir / snaps;
759     }
761     h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
762     update();
763     gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
764     _commit(_("Rotate handle"), key);
767 Handle *PathManipulator::_chooseHandle(Node *n, int which)
769     NodeList::iterator i = NodeList::get_iterator(n);
770     Node *prev = i.prev().ptr();
771     Node *next = i.next().ptr();
773     // on an endnode, the remaining handle automatically wins
774     if (!next) return n->back();
775     if (!prev) return n->front();
777     // compare X coord ofline segments
778     Geom::Point npos = next->position();
779     Geom::Point ppos = prev->position();
780     if (which < 0) {
781         // pick left handle.
782         // we just swap the handles and pick the right handle below.
783         std::swap(npos, ppos);
784     }
786     if (npos[Geom::X] >= ppos[Geom::X]) {
787         return n->front();
788     } else {
789         return n->back();
790     }
793 /** Set the visibility of handles. */
794 void PathManipulator::showHandles(bool show)
796     if (show == _show_handles) return;
797     if (show) {
798         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
799             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
800                 if (!j->selected()) continue;
801                 j->showHandles(true);
802                 if (j.prev()) j.prev()->showHandles(true);
803                 if (j.next()) j.next()->showHandles(true);
804             }
805         }
806     } else {
807         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
808             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
809                 j->showHandles(false);
810             }
811         }
812     }
813     _show_handles = show;
816 /** Set the visibility of outline. */
817 void PathManipulator::showOutline(bool show)
819     if (show == _show_outline) return;
820     _show_outline = show;
821     _updateOutline();
824 void PathManipulator::showPathDirection(bool show)
826     if (show == _show_path_direction) return;
827     _show_path_direction = show;
828     _updateOutline();
831 void PathManipulator::setLiveOutline(bool set)
833     _live_outline = set;
836 void PathManipulator::setLiveObjects(bool set)
838     _live_objects = set;
841 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
843     Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
844     _edit_transform = tnew;
845     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
846         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
847             j->transform(delta);
848         }
849     }
850     _createGeometryFromControlPoints();
853 /** Hide the curve drag point until the next motion event.
854  * This should be called at the beginning of every method that can delete nodes.
855  * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
856 void PathManipulator::hideDragPoint()
858     _dragpoint->setVisible(false);
859     _dragpoint->setIterator(NodeList::iterator());
862 /** Insert a node in the segment beginning with the supplied iterator,
863  * at the given time value */
864 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
866     if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
867     NodeList &list = NodeList::get(first);
868     NodeList::iterator second = first.next();
869     if (!second) throw std::invalid_argument("Subdivide after last node in open path");
871     // We need to insert the segment after 'first'. We can't simply use 'second'
872     // as the point of insertion, because when 'first' is the last node of closed path,
873     // the new node will be inserted as the first node instead.
874     NodeList::iterator insert_at = first;
875     ++insert_at;
877     NodeList::iterator inserted;
878     if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
879         // for a line segment, insert a cusp node
880         Node *n = new Node(_multi_path_manipulator._path_data.node_data,
881             Geom::lerp(t, first->position(), second->position()));
882         n->setType(NODE_CUSP, false);
883         inserted = list.insert(insert_at, n);
884     } else {
885         // build bezier curve and subdivide
886         Geom::CubicBezier temp(first->position(), first->front()->position(),
887             second->back()->position(), second->position());
888         std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
889         std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
891         // set new handle positions
892         Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
893         n->back()->setPosition(seg1[2]);
894         n->front()->setPosition(seg2[1]);
895         n->setType(NODE_SMOOTH, false);
896         inserted = list.insert(insert_at, n);
898         first->front()->move(seg1[1]);
899         second->back()->move(seg2[2]);
900     }
901     return inserted;
904 /** Find the node that is closest/farthest from the origin
905  * @param origin Point of reference
906  * @param search_selected Consider selected nodes
907  * @param search_unselected Consider unselected nodes
908  * @param closest If true, return closest node, if false, return farthest
909  * @return The matching node, or an empty iterator if none found
910  */
911 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
912     bool search_unselected, bool closest)
914     NodeList::iterator match;
915     double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
916     if (_num_selected == 0 && !search_unselected) return match;
918     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
919         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
920             if(j->selected()) {
921                 if (!search_selected) continue;
922             } else {
923                 if (!search_unselected) continue;
924             }
925             double dist = Geom::distance(*j, *origin);
926             bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
927             if (cond) {
928                 match = j;
929                 extr_dist = dist;
930             }
931         }
932     }
933     return match;
936 /** Called by the XML observer when something else than us modifies the path. */
937 void PathManipulator::_externalChange(unsigned type)
939     hideDragPoint();
941     switch (type) {
942     case PATH_CHANGE_D: {
943         _getGeometry();
945         // ugly: stored offsets of selected nodes in a vector
946         // vector<bool> should be specialized so that it takes only 1 bit per value
947         std::vector<bool> selpos;
948         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
949             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
950                 selpos.push_back(j->selected());
951             }
952         }
953         unsigned size = selpos.size(), curpos = 0;
955         _createControlPointsFromGeometry();
957         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
958             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
959                 if (curpos >= size) goto end_restore;
960                 if (selpos[curpos]) _selection.insert(j.ptr());
961                 ++curpos;
962             }
963         }
964         end_restore:
966         _updateOutline();
967         } break;
968     case PATH_CHANGE_TRANSFORM: {
969         Geom::Matrix i2d_change = _d2i_transform;
970         _i2d_transform = SP_ITEM(_path)->i2d_affine();
971         _d2i_transform = _i2d_transform.inverse();
972         i2d_change *= _i2d_transform;
973         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
974             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
975                 j->transform(i2d_change);
976             }
977         }
978         _updateOutline();
979         } break;
980     default: break;
981     }
984 /** Create nodes and handles based on the XML of the edited path. */
985 void PathManipulator::_createControlPointsFromGeometry()
987     clear();
989     // sanitize pathvector and store it in SPCurve,
990     // so that _updateDragPoint doesn't crash on paths with naked movetos
991     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
992     for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
993         // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
994         // When we erase an element, the next one slides into position,
995         // so we do not increment the iterator even though it is theoretically invalidated.
996         if (i->empty()) {
997             pathv.erase(i);
998         } else {
999             ++i;
1000         }
1001     }
1002     _spcurve->set_pathvector(pathv);
1004     pathv *= (_edit_transform * _i2d_transform);
1006     // in this loop, we know that there are no zero-segment subpaths
1007     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1008         // prepare new subpath
1009         SubpathPtr subpath(new NodeList(_subpaths));
1010         _subpaths.push_back(subpath);
1012         Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1013         subpath->push_back(previous_node);
1014         Geom::Curve const &cseg = pit->back_closed();
1015         bool fuse_ends = pit->closed()
1016             && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1018         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1019             Geom::Point pos = cit->finalPoint();
1020             Node *current_node;
1021             // if the closing segment is degenerate and the path is closed, we need to move
1022             // the handle of the first node instead of creating a new one
1023             if (fuse_ends && cit == --(pit->end_open())) {
1024                 current_node = subpath->begin().get_pointer();
1025             } else {
1026                 /* regardless of segment type, create a new node at the end
1027                  * of this segment (unless this is the last segment of a closed path
1028                  * with a degenerate closing segment */
1029                 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1030                 subpath->push_back(current_node);
1031             }
1032             // if this is a bezier segment, move handles appropriately
1033             if (Geom::CubicBezier const *cubic_bezier =
1034                 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1035             {
1036                 std::vector<Geom::Point> points = cubic_bezier->points();
1038                 previous_node->front()->setPosition(points[1]);
1039                 current_node ->back() ->setPosition(points[2]);
1040             }
1041             previous_node = current_node;
1042         }
1043         // If the path is closed, make the list cyclic
1044         if (pit->closed()) subpath->setClosed(true);
1045     }
1047     // we need to set the nodetypes after all the handles are in place,
1048     // so that pickBestType works correctly
1049     // TODO maybe migrate to inkscape:node-types?
1050     // TODO move this into SPPath - do not manipulate directly
1052     //XML Tree being used here directly while it shouldn't be.
1053     gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : 0;
1054     std::string nodetype_string = nts_raw ? nts_raw : "";
1055     /* Calculate the needed length of the nodetype string.
1056      * For closed paths, the entry is duplicated for the starting node,
1057      * so we can just use the count of segments including the closing one
1058      * to include the extra end node. */
1059     std::string::size_type nodetype_len = 0;
1060     for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1061         if (i->empty()) continue;
1062         nodetype_len += i->size_closed();
1063     }
1064     /* pad the string to required length with a bogus value.
1065      * 'b' and any other letter not recognized by the parser causes the best fit to be set
1066      * as the node type */
1067     if (nodetype_len > nodetype_string.size()) {
1068         nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1069     }
1070     std::string::iterator tsi = nodetype_string.begin();
1071     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1072         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1073             j->setType(Node::parse_nodetype(*tsi++), false);
1074         }
1075         if ((*i)->closed()) {
1076             // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1077             // the first one to remain backward compatible.
1078             (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1079         }
1080     }
1083 /** Construct the geometric representation of nodes and handles, update the outline
1084  * and display */
1085 void PathManipulator::_createGeometryFromControlPoints()
1087     Geom::PathBuilder builder;
1088     for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1089         SubpathPtr subpath = *spi;
1090         if (subpath->empty()) {
1091             _subpaths.erase(spi++);
1092             continue;
1093         }
1094         NodeList::iterator prev = subpath->begin();
1095         builder.moveTo(prev->position());
1097         for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1098             build_segment(builder, prev.ptr(), i.ptr());
1099             prev = i;
1100         }
1101         if (subpath->closed()) {
1102             // Here we link the last and first node if the path is closed.
1103             // If the last segment is Bezier, we add it.
1104             if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1105                 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1106             }
1107             // if that segment is linear, we just call closePath().
1108             builder.closePath();
1109         }
1110         ++spi;
1111     }
1112     builder.finish();
1113     _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1114     if (_live_outline)
1115         _updateOutline();
1116     if (_live_objects)
1117         _setGeometry();
1120 /** Build one segment of the geometric representation.
1121  * @relates PathManipulator */
1122 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1124     if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1125     {
1126         // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1127         // and trying to display a path using them results in funny artifacts.
1128         builder.lineTo(cur_node->position());
1129     } else {
1130         // this is a bezier segment
1131         builder.curveTo(
1132             prev_node->front()->position(),
1133             cur_node->back()->position(),
1134             cur_node->position());
1135     }
1138 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1139 std::string PathManipulator::_createTypeString()
1141     // precondition: no single-node subpaths
1142     std::stringstream tstr;
1143     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1144         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1145             tstr << j->type();
1146         }
1147         // nodestring format peculiarity: first node is counted twice for closed paths
1148         if ((*i)->closed()) tstr << (*i)->begin()->type();
1149     }
1150     return tstr.str();
1153 /** Update the path outline. */
1154 void PathManipulator::_updateOutline()
1156     if (!_show_outline) {
1157         sp_canvas_item_hide(_outline);
1158         return;
1159     }
1161     Geom::PathVector pv = _spcurve->get_pathvector();
1162     pv *= (_edit_transform * _i2d_transform);
1163     // This SPCurve thing has to be killed with extreme prejudice
1164     SPCurve *_hc = new SPCurve();
1165     if (_show_path_direction) {
1166         // To show the direction, we append additional subpaths which consist of a single
1167         // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1168         // at an angle 150 degrees from the unit tangent. This creates the appearance
1169         // of little 'harpoons' that show the direction of the subpaths.
1170         Geom::PathVector arrows;
1171         for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1172             Geom::Path &path = *i;
1173             for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1174                 Geom::Point at = j->pointAt(0.5);
1175                 Geom::Point ut = j->unitTangentAt(0.5);
1176                 // rotate the point 
1177                 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1178                 Geom::Point arrow_end = _desktop->w2d(
1179                     _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1181                 Geom::Path arrow(at);
1182                 arrow.appendNew<Geom::LineSegment>(arrow_end);
1183                 arrows.push_back(arrow);
1184             }
1185         }
1186         pv.insert(pv.end(), arrows.begin(), arrows.end());
1187     }
1188     _hc->set_pathvector(pv);
1189     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1190     sp_canvas_item_show(_outline);
1191     _hc->unref();
1194 /** Retrieve the geometry of the edited object from the object tree */
1195 void PathManipulator::_getGeometry()
1197     using namespace Inkscape::LivePathEffect;
1198     if (!_lpe_key.empty()) {
1199         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1200         if (lpe) {
1201             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1202             _spcurve->unref();
1203             _spcurve = new SPCurve(pathparam->get_pathvector());
1204         }
1205     } else {
1206         _spcurve->unref();
1207         _spcurve = sp_path_get_curve_for_edit(_path);
1208     }
1211 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1212 void PathManipulator::_setGeometry()
1214     using namespace Inkscape::LivePathEffect;
1215     if (empty()) return;
1217     if (!_lpe_key.empty()) {
1218         // copied from nodepath.cpp
1219         // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1220         // a LivePathEffectObject. (mad laughter)
1221         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1222         if (lpe) {
1223             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1224             pathparam->set_new_value(_spcurve->get_pathvector(), false);
1225             LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1226         }
1227     } else {
1228         //XML Tree being used here directly while it shouldn't be.
1229         if (_path->getRepr()->attribute("inkscape:original-d"))
1230             sp_path_set_original_curve(_path, _spcurve, false, false);
1231         else
1232             SP_SHAPE(_path)->setCurve(_spcurve, false);
1233     }
1236 /** Figure out in what attribute to store the nodetype string. */
1237 Glib::ustring PathManipulator::_nodetypesKey()
1239     if (_lpe_key.empty()) return "sodipodi:nodetypes";
1240     return _lpe_key + "-nodetypes";
1243 /** Return the XML node we are editing.
1244  * This method is wrong but necessary at the moment. */
1245 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1247     //XML Tree being used here directly while it shouldn't be.
1248     if (_lpe_key.empty()) return _path->getRepr();
1249     //XML Tree being used here directly while it shouldn't be.
1250     return LIVEPATHEFFECT(_path)->getRepr();
1253 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1255     if (event->button != 1) return false;
1256     if (held_alt(*event) && held_control(*event)) {
1257         // Ctrl+Alt+click: delete nodes
1258         hideDragPoint();
1259         NodeList::iterator iter = NodeList::get_iterator(n);
1260         NodeList &nl = iter->nodeList();
1262         if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1263             // Removing last node of closed path - delete it
1264             nl.kill();
1265         } else {
1266             // In other cases, delete the node under cursor
1267             _deleteStretch(iter, iter.next(), true);
1268         }
1270         if (!empty()) { 
1271             update();
1272         }
1273         // We need to call MPM's method because it could have been our last node
1274         _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1276         return true;
1277     } else if (held_control(*event)) {
1278         // Ctrl+click: cycle between node types
1279         if (!n->isEndNode()) {
1280             n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1281             update();
1282             _commit(_("Cycle node type"));
1283         }
1284         return true;
1285     }
1286     return false;
1289 void PathManipulator::_handleGrabbed()
1291     _selection.hideTransformHandles();
1294 void PathManipulator::_handleUngrabbed()
1296     _selection.restoreTransformHandles();
1297     _commit(_("Drag handle"));
1300 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1302     // retracting by Ctrl+click
1303     if (event->button == 1 && held_control(*event)) {
1304         h->move(h->parent()->position());
1305         update();
1306         _commit(_("Retract handle"));
1307         return true;
1308     }
1309     return false;
1312 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1314     if (selected) ++_num_selected;
1315     else --_num_selected;
1317     // don't do anything if we do not show handles
1318     if (!_show_handles) return;
1320     // only do something if a node changed selection state
1321     Node *node = dynamic_cast<Node*>(p);
1322     if (!node) return;
1324     // update handle display
1325     NodeList::iterator iters[5];
1326     iters[2] = NodeList::get_iterator(node);
1327     iters[1] = iters[2].prev();
1328     iters[3] = iters[2].next();
1329     if (selected) {
1330         // selection - show handles on this node and adjacent ones
1331         node->showHandles(true);
1332         if (iters[1]) iters[1]->showHandles(true);
1333         if (iters[3]) iters[3]->showHandles(true);
1334     } else {
1335         /* Deselection is more complex.
1336          * The change might affect 3 nodes - this one and two adjacent.
1337          * If the node and both its neighbors are deselected, hide handles.
1338          * Otherwise, leave as is. */
1339         if (iters[1]) iters[0] = iters[1].prev();
1340         if (iters[3]) iters[4] = iters[3].next();
1341         bool nodesel[5];
1342         for (int i = 0; i < 5; ++i) {
1343             nodesel[i] = iters[i] && iters[i]->selected();
1344         }
1345         for (int i = 1; i < 4; ++i) {
1346             if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1347                 iters[i]->showHandles(false);
1348             }
1349         }
1350     }
1353 /** Removes all nodes belonging to this manipulator from the control pont selection */
1354 void PathManipulator::_removeNodesFromSelection()
1356     // remove this manipulator's nodes from selection
1357     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1358         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1359             _selection.erase(j.get_pointer());
1360         }
1361     }
1364 /** Update the XML representation and put the specified annotation on the undo stack */
1365 void PathManipulator::_commit(Glib::ustring const &annotation)
1367     writeXML();
1368     DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1371 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1373     writeXML();
1374     DocumentUndo::maybeDone(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1375                             annotation.data());
1378 /** Update the position of the curve drag point such that it is over the nearest
1379  * point of the path. */
1380 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1382     Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1383     Geom::PathVector pv = _spcurve->get_pathvector();
1384     boost::optional<Geom::PathVectorPosition> pvp
1385         = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1386     if (!pvp) return;
1387     Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1388     
1389     double fracpart;
1390     std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1391     for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1392     NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1393     
1394     double stroke_tolerance = _getStrokeTolerance();
1395     if (first && first.next() &&
1396         fracpart != 0.0 &&
1397         Geom::distance(evp, nearest_point) < stroke_tolerance)
1398     {
1399         _dragpoint->setVisible(true);
1400         _dragpoint->setPosition(_desktop->w2d(nearest_point));
1401         _dragpoint->setSize(2 * stroke_tolerance);
1402         _dragpoint->setTimeValue(fracpart);
1403         _dragpoint->setIterator(first);
1404     } else {
1405         _dragpoint->setVisible(false);
1406     }
1409 /// This is called on zoom change to update the direction arrows
1410 void PathManipulator::_updateOutlineOnZoomChange()
1412     if (_show_path_direction) _updateOutline();
1415 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1416  * or segment selection, in window coordinates. */
1417 double PathManipulator::_getStrokeTolerance()
1419     /* Stroke event tolerance is equal to half the stroke's width plus the global
1420      * drag tolerance setting.  */
1421     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1422     double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1423     if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1424         ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1425             * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1426             * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1427     }
1428     return ret;
1431 } // namespace UI
1432 } // namespace Inkscape
1434 /*
1435   Local Variables:
1436   mode:c++
1437   c-file-style:"stroustrup"
1438   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1439   indent-tabs-mode:nil
1440   fill-column:99
1441   End:
1442 */
1443 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :