Code

New node tool: implement handle snapping
[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  *
7  * Copyright (C) 2009 Authors
8  * Released under GNU GPL, read the file 'COPYING' for more information
9  */
11 #include <string>
12 #include <sstream>
13 #include <deque>
14 #include <stdexcept>
15 #include <boost/shared_ptr.hpp>
16 #include <2geom/bezier-curve.h>
17 #include <2geom/bezier-utils.h>
18 #include <2geom/svg-path.h>
19 #include <glibmm.h>
20 #include <glibmm/i18n.h>
21 #include "ui/tool/path-manipulator.h"
22 #include "desktop.h"
23 #include "desktop-handles.h"
24 #include "display/sp-canvas.h"
25 #include "display/sp-canvas-util.h"
26 #include "display/curve.h"
27 #include "display/canvas-bpath.h"
28 #include "document.h"
29 #include "live_effects/effect.h"
30 #include "live_effects/lpeobject.h"
31 #include "live_effects/parameter/path.h"
32 #include "sp-path.h"
33 #include "helper/geom.h"
34 #include "preferences.h"
35 #include "style.h"
36 #include "ui/tool/control-point-selection.h"
37 #include "ui/tool/curve-drag-point.h"
38 #include "ui/tool/event-utils.h"
39 #include "ui/tool/multi-path-manipulator.h"
40 #include "xml/node.h"
41 #include "xml/node-observer.h"
43 namespace Inkscape {
44 namespace UI {
46 namespace {
47 /// Types of path changes that we must react to.
48 enum PathChange {
49     PATH_CHANGE_D,
50     PATH_CHANGE_TRANSFORM
51 };
53 } // anonymous namespace
55 /**
56  * Notifies the path manipulator when something changes the path being edited
57  * (e.g. undo / redo)
58  */
59 class PathManipulatorObserver : public Inkscape::XML::NodeObserver {
60 public:
61     PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node)
62         : _pm(p)
63         , _node(node)
64         , _blocked(false)
65     {
66         Inkscape::GC::anchor(_node);
67         _node->addObserver(*this);
68     }
70     ~PathManipulatorObserver() {
71         _node->removeObserver(*this);
72         Inkscape::GC::release(_node);
73     }
75     virtual void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr,
76         Util::ptr_shared<char>, Util::ptr_shared<char>)
77     {
78         // do nothing if blocked
79         if (_blocked) return;
81         GQuark path_d = g_quark_from_static_string("d");
82         GQuark path_transform = g_quark_from_static_string("transform");
83         GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
85         // only react to "d" (path data) and "transform" attribute changes
86         if (attr == lpe_quark || attr == path_d) {
87             _pm->_externalChange(PATH_CHANGE_D);
88         } else if (attr == path_transform) {
89             _pm->_externalChange(PATH_CHANGE_TRANSFORM);
90         }
91     }
93     void block() { _blocked = true; }
94     void unblock() { _blocked = false; }
95 private:
96     PathManipulator *_pm;
97     Inkscape::XML::Node *_node;
98     bool _blocked;
99 };
101 void build_segment(Geom::PathBuilder &, Node *, Node *);
103 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
104         Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
105     : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
106     , _subpaths(*this)
107     , _multi_path_manipulator(mpm)
108     , _path(path)
109     , _spcurve(new SPCurve())
110     , _dragpoint(new CurveDragPoint(*this))
111     , _observer(new PathManipulatorObserver(this, SP_OBJECT(path)->repr))
112     , _edit_transform(et)
113     , _num_selected(0)
114     , _show_handles(true)
115     , _show_outline(false)
116     , _show_path_direction(false)
117     , _live_outline(true)
118     , _live_objects(true)
119     , _lpe_key(lpe_key)
121     if (_lpe_key.empty()) {
122         _i2d_transform = sp_item_i2d_affine(SP_ITEM(path));
123     } else {
124         _i2d_transform = Geom::identity();
125     }
126     _d2i_transform = _i2d_transform.inverse();
127     _dragpoint->setVisible(false);
129     _getGeometry();
131     _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
132     sp_canvas_item_hide(_outline);
133     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
134         SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
135     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
137     _selection.signal_update.connect(
138         sigc::mem_fun(*this, &PathManipulator::update));
139     _selection.signal_point_changed.connect(
140         sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
141     _desktop->signal_zoom_changed.connect(
142         sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
144     _createControlPointsFromGeometry();
147 PathManipulator::~PathManipulator()
149     delete _dragpoint;
150     delete _observer;
151     gtk_object_destroy(_outline);
152     _spcurve->unref();
153     clear();
156 /** Handle motion events to update the position of the curve drag point. */
157 bool PathManipulator::event(GdkEvent *event)
159     if (empty()) return false;
161     switch (event->type)
162     {
163     case GDK_MOTION_NOTIFY:
164         _updateDragPoint(event_point(event->motion));
165         break;
166     default: break;
167     }
168     return false;
171 /** Check whether the manipulator has any nodes. */
172 bool PathManipulator::empty() {
173     return !_path || _subpaths.empty();
176 /** Update the display and the outline of the path. */
177 void PathManipulator::update()
179     _createGeometryFromControlPoints();
182 /** Store the changes to the path in XML. */
183 void PathManipulator::writeXML()
185     if (!_live_outline)
186         _updateOutline();
187     if (!_live_objects)
188         _setGeometry();
190     if (!_path) return;
191     _observer->block();
192     if (!empty()) {
193         SP_OBJECT(_path)->updateRepr();
194         _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
195     } else {
196         // this manipulator will have to be destroyed right after this call
197         _getXMLNode()->removeObserver(*_observer);
198         sp_object_ref(_path);
199         _path->deleteObject(true, true);
200         sp_object_unref(_path);
201         _path = 0;
202     }
203     _observer->unblock();
206 /** Remove all nodes from the path. */
207 void PathManipulator::clear()
209     // no longer necessary since nodes remove themselves from selection on destruction
210     //_removeNodesFromSelection();
211     _subpaths.clear();
214 /** Select all nodes in subpaths that have something selected. */
215 void PathManipulator::selectSubpaths()
217     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
218         NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
219         for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
220             if (j->selected()) {
221                 // if at least one of the nodes from this subpath is selected,
222                 // select all nodes from this subpath
223                 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
224                     _selection.insert(ins.ptr());
225                 continue;
226             }
227         }
228     }
231 /** Move the selection forward or backward by one node in each subpath, based on the sign
232  * of the parameter. */
233 void PathManipulator::shiftSelection(int dir)
235     if (dir == 0) return;
236     if (_num_selected == 0) {
237         // select the first node of the path.
238         SubpathList::iterator s = _subpaths.begin();
239         if (s == _subpaths.end()) return;
240         NodeList::iterator n = (*s)->begin();
241         if (n != (*s)->end())
242             _selection.insert(n.ptr());
243         return;
244     }
245     // We cannot do any tricks here, like iterating in different directions based on
246     // the sign and only setting the selection of nodes behind us, because it would break
247     // for closed paths.
248     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
249         std::deque<bool> sels; // I hope this is specialized for bools!
250         unsigned num = 0;
251         
252         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
253             sels.push_back(j->selected());
254             _selection.erase(j.ptr());
255             ++num;
256         }
257         if (num == 0) continue; // should never happen! zero-node subpaths are not allowed
259         num = 0;
260         // In closed subpath, shift the selection cyclically. In an open one,
261         // let the selection 'slide into nothing' at ends.
262         if (dir > 0) {
263             if ((*i)->closed()) {
264                 bool last = sels.back();
265                 sels.pop_back();
266                 sels.push_front(last);
267             } else {
268                 sels.push_front(false);
269             }
270         } else {
271             if ((*i)->closed()) {
272                 bool first = sels.front();
273                 sels.pop_front();
274                 sels.push_back(first);
275             } else {
276                 sels.push_back(false);
277                 num = 1;
278             }
279         }
281         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
282             if (sels[num]) _selection.insert(j.ptr());
283             ++num;
284         }
285     }
288 /** Invert selection in the selected subpaths. */
289 void PathManipulator::invertSelectionInSubpaths()
291     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
292         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
293             if (j->selected()) {
294                 // found selected node - invert selection in this subpath
295                 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
296                     if (k->selected()) _selection.erase(k.ptr());
297                     else _selection.insert(k.ptr());
298                 }
299                 // next subpath
300                 break;
301             }
302         }
303     }
306 /** Insert a new node in the middle of each selected segment. */
307 void PathManipulator::insertNodes()
309     if (_num_selected < 2) return;
311     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
312         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
313             NodeList::iterator k = j.next();
314             if (k && j->selected() && k->selected()) {
315                 j = subdivideSegment(j, 0.5);
316                 _selection.insert(j.ptr());
317             }
318         }
319     }
322 /** Replace contiguous selections of nodes in each subpath with one node. */
323 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
325     if (_num_selected < 2) return;
326     hideDragPoint();
328     bool pos_valid = preserve_pos;
329     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
330         SubpathPtr sp = *i;
331         unsigned num_selected = 0, num_unselected = 0;
332         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
333             if (j->selected()) ++num_selected;
334             else ++num_unselected;
335         }
336         if (num_selected < 2) continue;
337         if (num_unselected == 0) {
338             // if all nodes in a subpath are selected, the operation doesn't make much sense
339             continue;
340         }
342         // Start from unselected node in closed paths, so that we don't start in the middle
343         // of a selection
344         NodeList::iterator sel_beg = sp->begin(), sel_end;
345         if (sp->closed()) {
346             while (sel_beg->selected()) ++sel_beg;
347         }
349         // Work loop
350         while (num_selected > 0) {
351             // Find selected node
352             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
353             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
354                 "but there are still nodes to process!");
356             // note: this is initialized to zero, because the loop below counts sel_beg as well
357             // the loop conditions are simpler that way
358             unsigned num_points = 0;
359             bool use_pos = false;
360             Geom::Point back_pos, front_pos;
361             back_pos = *sel_beg->back();
363             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
364                 ++num_points;
365                 front_pos = *sel_end->front();
366                 if (pos_valid && sel_end == preserve_pos) use_pos = true;
367             }
368             if (num_points > 1) {
369                 Geom::Point joined_pos;
370                 if (use_pos) {
371                     joined_pos = preserve_pos->position();
372                     pos_valid = false;
373                 } else {
374                     joined_pos = Geom::middle_point(back_pos, front_pos);
375                 }
376                 sel_beg->setType(NODE_CUSP, false);
377                 sel_beg->move(joined_pos);
378                 // do not move handles if they aren't degenerate
379                 if (!sel_beg->back()->isDegenerate()) {
380                     sel_beg->back()->setPosition(back_pos);
381                 }
382                 if (!sel_end.prev()->front()->isDegenerate()) {
383                     sel_beg->front()->setPosition(front_pos);
384                 }
385                 sel_beg = sel_beg.next();
386                 while (sel_beg != sel_end) {
387                     NodeList::iterator next = sel_beg.next();
388                     sp->erase(sel_beg);
389                     sel_beg = next;
390                     --num_selected;
391                 }
392             }
393             --num_selected; // for the joined node or single selected node
394         }
395     }
398 /** Remove nodes in the middle of selected segments. */
399 void PathManipulator::weldSegments()
401     if (_num_selected < 2) return;
402     hideDragPoint();
404     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
405         SubpathPtr sp = *i;
406         unsigned num_selected = 0, num_unselected = 0;
407         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
408             if (j->selected()) ++num_selected;
409             else ++num_unselected;
410         }
411         if (num_selected < 3) continue;
412         if (num_unselected == 0 && sp->closed()) {
413             // if all nodes in a closed subpath are selected, the operation doesn't make much sense
414             continue;
415         }
417         // Start from unselected node in closed paths, so that we don't start in the middle
418         // of a selection
419         NodeList::iterator sel_beg = sp->begin(), sel_end;
420         if (sp->closed()) {
421             while (sel_beg->selected()) ++sel_beg;
422         }
424         // Work loop
425         while (num_selected > 0) {
426             // Find selected node
427             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
428             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
429                 "but there are still nodes to process!");
431             // note: this is initialized to zero, because the loop below counts sel_beg as well
432             // the loop conditions are simpler that way
433             unsigned num_points = 0;
435             // find the end of selected segment
436             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
437                 ++num_points;
438             }
439             if (num_points > 2) {
440                 // remove nodes in the middle
441                 sel_beg = sel_beg.next();
442                 while (sel_beg != sel_end.prev()) {
443                     NodeList::iterator next = sel_beg.next();
444                     sp->erase(sel_beg);
445                     sel_beg = next;
446                 }
447                 sel_beg = sel_end;
448             }
449             num_selected -= num_points;
450         }
451     }
454 /** Break the subpath at selected nodes. It also works for single node closed paths. */
455 void PathManipulator::breakNodes()
457     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
458         SubpathPtr sp = *i;
459         NodeList::iterator cur = sp->begin(), end = sp->end();
460         if (!sp->closed()) {
461             // Each open path must have at least two nodes so no checks are required.
462             // For 2-node open paths, cur == end
463             ++cur;
464             --end;
465         }
466         for (; cur != end; ++cur) {
467             if (!cur->selected()) continue;
468             SubpathPtr ins;
469             bool becomes_open = false;
471             if (sp->closed()) {
472                 // Move the node to break at to the beginning of path
473                 if (cur != sp->begin())
474                     sp->splice(sp->begin(), *sp, cur, sp->end());
475                 sp->setClosed(false);
476                 ins = sp;
477                 becomes_open = true;
478             } else {
479                 SubpathPtr new_sp(new NodeList(_subpaths));
480                 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
481                 _subpaths.insert(i, new_sp);
482                 ins = new_sp;
483             }
485             Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
486             ins->insert(ins->end(), n);
487             cur->setType(NODE_CUSP, false);
488             n->back()->setRelativePos(cur->back()->relativePos());
489             cur->back()->retract();
490             n->sink();
492             if (becomes_open) {
493                 cur = sp->begin(); // this will be increased to ++sp->begin()
494                 end = --sp->end();
495             }
496         }
497     }
500 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
501  * in a way that attempts to preserve the original shape of the curve. */
502 void PathManipulator::deleteNodes(bool keep_shape)
504     if (_num_selected == 0) return;
505     hideDragPoint();
507     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
508         SubpathPtr sp = *i;
510         // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
511         // in a closed one, delete entire subpath.
512         unsigned num_unselected = 0, num_selected = 0;
513         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
514             if (j->selected()) ++num_selected;
515             else ++num_unselected;
516         }
517         if (num_selected == 0) {
518             ++i;
519             continue;
520         }
521         if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
522             _subpaths.erase(i++);
523             continue;
524         }
526         // In closed paths, start from an unselected node - otherwise we might start in the middle
527         // of a selected stretch and the resulting bezier fit would be suboptimal
528         NodeList::iterator sel_beg = sp->begin(), sel_end;
529         if (sp->closed()) {
530             while (sel_beg->selected()) ++sel_beg;
531         }
532         sel_end = sel_beg;
533         
534         while (num_selected > 0) {
535             while (sel_beg && !sel_beg->selected()) {
536                 sel_beg = sel_beg.next();
537             }
538             sel_end = sel_beg;
540             while (sel_end && sel_end->selected()) {
541                 sel_end = sel_end.next();
542             }
543             
544             num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
545             sel_beg = sel_end;
546         }
547         ++i;
548     }
551 /** @brief Delete nodes between the two iterators.
552  * The given range can cross the beginning of the subpath in closed subpaths.
553  * @param start      Beginning of the range to delete
554  * @param end        End of the range
555  * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
556  *                   the shape before deletion
557  * @return Number of deleted nodes */
558 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
560     unsigned const samples_per_segment = 10;
561     double const t_step = 1.0 / samples_per_segment;
563     unsigned del_len = 0;
564     for (NodeList::iterator i = start; i != end; i = i.next()) {
565         ++del_len;
566     }
567     if (del_len == 0) return 0;
569     // set surrounding node types to cusp if:
570     // 1. keep_shape is on, or
571     // 2. we are deleting at the end or beginning of an open path
572     if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
573     if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
575     if (keep_shape && start.prev() && end) {
576         unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
577         Geom::Point *bezier_data = new Geom::Point[num_samples];
578         Geom::Point result[4];
579         unsigned seg = 0;
581         for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
582             Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
583             for (unsigned s = 0; s < samples_per_segment; ++s) {
584                 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
585             }
586             ++seg;
587         }
588         // Fill last point
589         bezier_data[num_samples - 1] = end->position();
590         // Compute replacement bezier curve
591         // TODO the fitting algorithm sucks - rewrite it to be awesome
592         bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
593         delete[] bezier_data;
595         start.prev()->front()->setPosition(result[1]);
596         end->back()->setPosition(result[2]);
597     }
599     // We can't use nl->erase(start, end), because it would break when the stretch
600     // crosses the beginning of a closed subpath
601     NodeList &nl = start->nodeList();
602     while (start != end) {
603         NodeList::iterator next = start.next();
604         nl.erase(start);
605         start = next;
606     }
608     return del_len;
611 /** Removes selected segments */
612 void PathManipulator::deleteSegments()
614     if (_num_selected == 0) return;
615     hideDragPoint();
617     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
618         SubpathPtr sp = *i;
619         bool has_unselected = false;
620         unsigned num_selected = 0;
621         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
622             if (j->selected()) {
623                 ++num_selected;
624             } else {
625                 has_unselected = true;
626             }
627         }
628         if (!has_unselected) {
629             _subpaths.erase(i++);
630             continue;
631         }
633         NodeList::iterator sel_beg = sp->begin();
634         if (sp->closed()) {
635             while (sel_beg && sel_beg->selected()) ++sel_beg;
636         }
637         while (num_selected > 0) {
638             if (!sel_beg->selected()) {
639                 sel_beg = sel_beg.next();
640                 continue;
641             }
642             NodeList::iterator sel_end = sel_beg;
643             unsigned num_points = 0;
644             while (sel_end && sel_end->selected()) {
645                 sel_end = sel_end.next();
646                 ++num_points;
647             }
648             if (num_points >= 2) {
649                 // Retract end handles
650                 sel_end.prev()->setType(NODE_CUSP, false);
651                 sel_end.prev()->back()->retract();
652                 sel_beg->setType(NODE_CUSP, false);
653                 sel_beg->front()->retract();
654                 if (sp->closed()) {
655                     // In closed paths, relocate the beginning of the path to the last selected
656                     // node and then unclose it. Remove the nodes from the first selected node
657                     // to the new end of path.
658                     if (sel_end.prev() != sp->begin())
659                         sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
660                     sp->setClosed(false);
661                     sp->erase(sel_beg.next(), sp->end());
662                 } else {
663                     // for open paths:
664                     // 1. At end or beginning, delete including the node on the end or beginning
665                     // 2. In the middle, delete only inner nodes
666                     if (sel_beg == sp->begin()) {
667                         sp->erase(sp->begin(), sel_end.prev());
668                     } else if (sel_end == sp->end()) {
669                         sp->erase(sel_beg.next(), sp->end());
670                     } else {
671                         SubpathPtr new_sp(new NodeList(_subpaths));
672                         new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
673                         _subpaths.insert(i, new_sp);
674                         if (sel_end.prev())
675                             sp->erase(sp->begin(), sel_end.prev());
676                     }
677                 }
678             }
679             sel_beg = sel_end;
680             num_selected -= num_points;
681         }
682         ++i;
683     }
686 /** Reverse subpaths of the path.
687  * @param selected_only If true, only paths that have at least one selected node
688  *                      will be reversed. Otherwise all subpaths will be reversed. */
689 void PathManipulator::reverseSubpaths(bool selected_only)
691     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
692         if (selected_only) {
693             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
694                 if (j->selected()) {
695                     (*i)->reverse();
696                     break; // continue with the next subpath
697                 }
698             }
699         } else {
700             (*i)->reverse();
701         }
702     }
705 /** Make selected segments curves / lines. */
706 void PathManipulator::setSegmentType(SegmentType type)
708     if (_num_selected == 0) return;
709     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
710         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
711             NodeList::iterator k = j.next();
712             if (!(k && j->selected() && k->selected())) continue;
713             switch (type) {
714             case SEGMENT_STRAIGHT:
715                 if (j->front()->isDegenerate() && k->back()->isDegenerate())
716                     break;
717                 j->front()->move(*j);
718                 k->back()->move(*k);
719                 break;
720             case SEGMENT_CUBIC_BEZIER:
721                 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
722                     break;
723                 j->front()->move(j->position() + (k->position() - j->position()) / 3);
724                 k->back()->move(k->position() + (j->position() - k->position()) / 3);
725                 break;
726             }
727         }
728     }
731 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
733     if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
734         n->setType(NODE_SMOOTH);
735     }
736     Handle *h = _chooseHandle(n, which);
737     double length_change;
739     if (pixel) {
740         length_change = 1.0 / _desktop->current_zoom() * dir;
741     } else {
742         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
743         length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
744         length_change *= dir;
745     }
747     Geom::Point relpos = h->relativePos();
748     double rellen = relpos.length();
749     h->setRelativePos(relpos * ((rellen + length_change) / rellen));
750     update();
752     gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
753     _commit(_("Scale handle"), key);
756 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
758     if (n->type() != NODE_CUSP) {
759         n->setType(NODE_CUSP);
760     }
761     Handle *h = _chooseHandle(n, which);
762     double angle;
764     if (pixel) {
765         // Rotate by "one pixel"
766         angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
767     } else {
768         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
769         int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
770         angle = M_PI * dir / snaps;
771     }
772     h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
773     update();
774     gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
775     _commit(_("Rotate handle"), key);
778 Handle *PathManipulator::_chooseHandle(Node *n, int which)
780     Geom::Point f = n->front()->position(), b = n->back()->position();
781     if (which < 0) {
782         // pick left handle.
783         // we just swap the handles and pick the right handle below.
784         std::swap(f, b);
785     }
786     if (f[Geom::X] >= b[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     switch (type) {
940     case PATH_CHANGE_D: {
941         _getGeometry();
943         // ugly: stored offsets of selected nodes in a vector
944         // vector<bool> should be specialized so that it takes only 1 bit per value
945         std::vector<bool> selpos;
946         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
947             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
948                 selpos.push_back(j->selected());
949             }
950         }
951         unsigned size = selpos.size(), curpos = 0;
953         _createControlPointsFromGeometry();
955         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
956             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
957                 if (curpos >= size) goto end_restore;
958                 if (selpos[curpos]) _selection.insert(j.ptr());
959                 ++curpos;
960             }
961         }
962         end_restore:
964         _updateOutline();
965         } break;
966     case PATH_CHANGE_TRANSFORM: {
967         Geom::Matrix i2d_change = _d2i_transform;
968         _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
969         _d2i_transform = _i2d_transform.inverse();
970         i2d_change *= _i2d_transform;
971         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
972             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
973                 j->transform(i2d_change);
974             }
975         }
976         _updateOutline();
977         } break;
978     default: break;
979     }
982 /** Create nodes and handles based on the XML of the edited path. */
983 void PathManipulator::_createControlPointsFromGeometry()
985     clear();
987     // sanitize pathvector and store it in SPCurve,
988     // so that _updateDragPoint doesn't crash on paths with naked movetos
989     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
990     for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
991         // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
992         // When we erase an element, the next one slides into position,
993         // so we do not increment the iterator even though it is theoretically invalidated.
994         if (i->empty()) {
995             pathv.erase(i);
996         } else {
997             ++i;
998         }
999     }
1000     _spcurve->set_pathvector(pathv);
1002     pathv *= (_edit_transform * _i2d_transform);
1004     // in this loop, we know that there are no zero-segment subpaths
1005     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1006         // prepare new subpath
1007         SubpathPtr subpath(new NodeList(_subpaths));
1008         _subpaths.push_back(subpath);
1010         Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1011         subpath->push_back(previous_node);
1012         Geom::Curve const &cseg = pit->back_closed();
1013         bool fuse_ends = pit->closed()
1014             && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1016         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1017             Geom::Point pos = cit->finalPoint();
1018             Node *current_node;
1019             // if the closing segment is degenerate and the path is closed, we need to move
1020             // the handle of the first node instead of creating a new one
1021             if (fuse_ends && cit == --(pit->end_open())) {
1022                 current_node = subpath->begin().get_pointer();
1023             } else {
1024                 /* regardless of segment type, create a new node at the end
1025                  * of this segment (unless this is the last segment of a closed path
1026                  * with a degenerate closing segment */
1027                 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1028                 subpath->push_back(current_node);
1029             }
1030             // if this is a bezier segment, move handles appropriately
1031             if (Geom::CubicBezier const *cubic_bezier =
1032                 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1033             {
1034                 std::vector<Geom::Point> points = cubic_bezier->points();
1036                 previous_node->front()->setPosition(points[1]);
1037                 current_node ->back() ->setPosition(points[2]);
1038             }
1039             previous_node = current_node;
1040         }
1041         // If the path is closed, make the list cyclic
1042         if (pit->closed()) subpath->setClosed(true);
1043     }
1045     // we need to set the nodetypes after all the handles are in place,
1046     // so that pickBestType works correctly
1047     // TODO maybe migrate to inkscape:node-types?
1048     // TODO move this into SPPath - do not manipulate directly
1049     gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
1050     std::string nodetype_string = nts_raw ? nts_raw : "";
1051     /* Calculate the needed length of the nodetype string.
1052      * For closed paths, the entry is duplicated for the starting node,
1053      * so we can just use the count of segments including the closing one
1054      * to include the extra end node. */
1055     std::string::size_type nodetype_len = 0;
1056     for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1057         if (i->empty()) continue;
1058         nodetype_len += i->size_closed();
1059     }
1060     /* pad the string to required length with a bogus value.
1061      * 'b' and any other letter not recognized by the parser causes the best fit to be set
1062      * as the node type */
1063     if (nodetype_len > nodetype_string.size()) {
1064         nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1065     }
1066     std::string::iterator tsi = nodetype_string.begin();
1067     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1068         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1069             j->setType(Node::parse_nodetype(*tsi++), false);
1070         }
1071         if ((*i)->closed()) {
1072             // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1073             // the first one to remain backward compatible.
1074             (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1075         }
1076     }
1079 /** Construct the geometric representation of nodes and handles, update the outline
1080  * and display */
1081 void PathManipulator::_createGeometryFromControlPoints()
1083     Geom::PathBuilder builder;
1084     for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1085         SubpathPtr subpath = *spi;
1086         if (subpath->empty()) {
1087             _subpaths.erase(spi++);
1088             continue;
1089         }
1090         NodeList::iterator prev = subpath->begin();
1091         builder.moveTo(prev->position());
1093         for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1094             build_segment(builder, prev.ptr(), i.ptr());
1095             prev = i;
1096         }
1097         if (subpath->closed()) {
1098             // Here we link the last and first node if the path is closed.
1099             // If the last segment is Bezier, we add it.
1100             if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1101                 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1102             }
1103             // if that segment is linear, we just call closePath().
1104             builder.closePath();
1105         }
1106         ++spi;
1107     }
1108     builder.finish();
1109     _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1110     if (_live_outline)
1111         _updateOutline();
1112     if (_live_objects)
1113         _setGeometry();
1116 /** Build one segment of the geometric representation.
1117  * @relates PathManipulator */
1118 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1120     if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1121     {
1122         // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1123         // and trying to display a path using them results in funny artifacts.
1124         builder.lineTo(cur_node->position());
1125     } else {
1126         // this is a bezier segment
1127         builder.curveTo(
1128             prev_node->front()->position(),
1129             cur_node->back()->position(),
1130             cur_node->position());
1131     }
1134 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1135 std::string PathManipulator::_createTypeString()
1137     // precondition: no single-node subpaths
1138     std::stringstream tstr;
1139     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1140         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1141             tstr << j->type();
1142         }
1143         // nodestring format peculiarity: first node is counted twice for closed paths
1144         if ((*i)->closed()) tstr << (*i)->begin()->type();
1145     }
1146     return tstr.str();
1149 /** Update the path outline. */
1150 void PathManipulator::_updateOutline()
1152     if (!_show_outline) {
1153         sp_canvas_item_hide(_outline);
1154         return;
1155     }
1157     Geom::PathVector pv = _spcurve->get_pathvector();
1158     pv *= (_edit_transform * _i2d_transform);
1159     // This SPCurve thing has to be killed with extreme prejudice
1160     SPCurve *_hc = new SPCurve();
1161     if (_show_path_direction) {
1162         // To show the direction, we append additional subpaths which consist of a single
1163         // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1164         // at an angle 150 degrees from the unit tangent. This creates the appearance
1165         // of little 'harpoons' that show the direction of the subpaths.
1166         Geom::PathVector arrows;
1167         for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1168             Geom::Path &path = *i;
1169             for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1170                 Geom::Point at = j->pointAt(0.5);
1171                 Geom::Point ut = j->unitTangentAt(0.5);
1172                 // rotate the point 
1173                 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1174                 Geom::Point arrow_end = _desktop->w2d(
1175                     _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1177                 Geom::Path arrow(at);
1178                 arrow.appendNew<Geom::LineSegment>(arrow_end);
1179                 arrows.push_back(arrow);
1180             }
1181         }
1182         pv.insert(pv.end(), arrows.begin(), arrows.end());
1183     }
1184     _hc->set_pathvector(pv);
1185     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1186     sp_canvas_item_show(_outline);
1187     _hc->unref();
1190 /** Retrieve the geometry of the edited object from the object tree */
1191 void PathManipulator::_getGeometry()
1193     using namespace Inkscape::LivePathEffect;
1194     if (!_lpe_key.empty()) {
1195         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1196         if (lpe) {
1197             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1198             _spcurve->unref();
1199             _spcurve = new SPCurve(pathparam->get_pathvector());
1200         }
1201     } else {
1202         _spcurve->unref();
1203         _spcurve = sp_path_get_curve_for_edit(_path);
1204     }
1207 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1208 void PathManipulator::_setGeometry()
1210     using namespace Inkscape::LivePathEffect;
1211     if (empty()) return;
1213     if (!_lpe_key.empty()) {
1214         // copied from nodepath.cpp
1215         // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1216         // a LivePathEffectObject. (mad laughter)
1217         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1218         if (lpe) {
1219             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1220             pathparam->set_new_value(_spcurve->get_pathvector(), false);
1221             LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1222         }
1223     } else {
1224         if (_path->repr->attribute("inkscape:original-d"))
1225             sp_path_set_original_curve(_path, _spcurve, false, false);
1226         else
1227             sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1228     }
1231 /** Figure out in what attribute to store the nodetype string. */
1232 Glib::ustring PathManipulator::_nodetypesKey()
1234     if (_lpe_key.empty()) return "sodipodi:nodetypes";
1235     return _lpe_key + "-nodetypes";
1238 /** Return the XML node we are editing.
1239  * This method is wrong but necessary at the moment. */
1240 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1242     if (_lpe_key.empty()) return _path->repr;
1243     return LIVEPATHEFFECT(_path)->repr;
1246 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1248     if (event->button != 1) return false;
1249     if (held_alt(*event) && held_control(*event)) {
1250         // Ctrl+Alt+click: delete nodes
1251         hideDragPoint();
1252         NodeList::iterator iter = NodeList::get_iterator(n);
1253         NodeList &nl = iter->nodeList();
1255         if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1256             // Removing last node of closed path - delete it
1257             nl.kill();
1258         } else {
1259             // In other cases, delete the node under cursor
1260             _deleteStretch(iter, iter.next(), true);
1261         }
1263         if (!empty()) { 
1264             update();
1265         }
1266         // We need to call MPM's method because it could have been our last node
1267         _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1269         return true;
1270     } else if (held_control(*event)) {
1271         // Ctrl+click: cycle between node types
1272         if (n->isEndNode()) {
1273             if (n->type() == NODE_CUSP) {
1274                 n->setType(NODE_SMOOTH);
1275             } else {
1276                 n->setType(NODE_CUSP);
1277             }
1278         } else {
1279             n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1280         }
1281         update();
1282         _commit(_("Cycle node type"));
1283         return true;
1284     }
1285     return false;
1288 void PathManipulator::_handleGrabbed()
1290     _selection.hideTransformHandles();
1293 void PathManipulator::_handleUngrabbed()
1295     _selection.restoreTransformHandles();
1296     _commit(_("Drag handle"));
1299 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1301     // retracting by Ctrl+click
1302     if (event->button == 1 && held_control(*event)) {
1303         h->move(h->parent()->position());
1304         update();
1305         _commit(_("Retract handle"));
1306         return true;
1307     }
1308     return false;
1311 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1313     if (selected) ++_num_selected;
1314     else --_num_selected;
1316     // don't do anything if we do not show handles
1317     if (!_show_handles) return;
1319     // only do something if a node changed selection state
1320     Node *node = dynamic_cast<Node*>(p);
1321     if (!node) return;
1323     // update handle display
1324     NodeList::iterator iters[5];
1325     iters[2] = NodeList::get_iterator(node);
1326     iters[1] = iters[2].prev();
1327     iters[3] = iters[2].next();
1328     if (selected) {
1329         // selection - show handles on this node and adjacent ones
1330         node->showHandles(true);
1331         if (iters[1]) iters[1]->showHandles(true);
1332         if (iters[3]) iters[3]->showHandles(true);
1333     } else {
1334         /* Deselection is more complex.
1335          * The change might affect 3 nodes - this one and two adjacent.
1336          * If the node and both its neighbors are deselected, hide handles.
1337          * Otherwise, leave as is. */
1338         if (iters[1]) iters[0] = iters[1].prev();
1339         if (iters[3]) iters[4] = iters[3].next();
1340         bool nodesel[5];
1341         for (int i = 0; i < 5; ++i) {
1342             nodesel[i] = iters[i] && iters[i]->selected();
1343         }
1344         for (int i = 1; i < 4; ++i) {
1345             if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1346                 iters[i]->showHandles(false);
1347             }
1348         }
1349     }
1352 /** Removes all nodes belonging to this manipulator from the control pont selection */
1353 void PathManipulator::_removeNodesFromSelection()
1355     // remove this manipulator's nodes from selection
1356     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1357         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1358             _selection.erase(j.get_pointer());
1359         }
1360     }
1363 /** Update the XML representation and put the specified annotation on the undo stack */
1364 void PathManipulator::_commit(Glib::ustring const &annotation)
1366     writeXML();
1367     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1370 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1372     writeXML();
1373     sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1374             annotation.data());
1377 /** Update the position of the curve drag point such that it is over the nearest
1378  * point of the path. */
1379 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1381     Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1382     Geom::PathVector pv = _spcurve->get_pathvector();
1383     boost::optional<Geom::PathVectorPosition> pvp
1384         = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1385     if (!pvp) return;
1386     Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1387     
1388     double fracpart;
1389     std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1390     for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1391     NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1392     
1393     double stroke_tolerance = _getStrokeTolerance();
1394     if (Geom::distance(evp, nearest_point) < stroke_tolerance) {
1395         _dragpoint->setVisible(true);
1396         _dragpoint->setPosition(_desktop->w2d(nearest_point));
1397         _dragpoint->setSize(2 * stroke_tolerance);
1398         _dragpoint->setTimeValue(fracpart);
1399         _dragpoint->setIterator(first);
1400     } else {
1401         _dragpoint->setVisible(false);
1402     }
1405 /// This is called on zoom change to update the direction arrows
1406 void PathManipulator::_updateOutlineOnZoomChange()
1408     if (_show_path_direction) _updateOutline();
1411 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1412  * or segment selection, in window coordinates. */
1413 double PathManipulator::_getStrokeTolerance()
1415     /* Stroke event tolerance is equal to half the stroke's width plus the global
1416      * drag tolerance setting.  */
1417     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1418     double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1419     if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1420         ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1421             * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1422             * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1423     }
1424     return ret;
1427 } // namespace UI
1428 } // namespace Inkscape
1430 /*
1431   Local Variables:
1432   mode:c++
1433   c-file-style:"stroustrup"
1434   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1435   indent-tabs-mode:nil
1436   fill-column:99
1437   End:
1438 */
1439 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :