Code

Make Ctrl+Alt+click delete nodes.
[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) : _pm(p), _blocked(false) {}
62     virtual void notifyAttributeChanged(Inkscape::XML::Node &, GQuark attr,
63         Util::ptr_shared<char>, Util::ptr_shared<char>)
64     {
65         // do nothing if blocked
66         if (_blocked) return;
68         GQuark path_d = g_quark_from_static_string("d");
69         GQuark path_transform = g_quark_from_static_string("transform");
70         GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
72         // only react to "d" (path data) and "transform" attribute changes
73         if (attr == lpe_quark || attr == path_d) {
74             _pm->_externalChange(PATH_CHANGE_D);
75         } else if (attr == path_transform) {
76             _pm->_externalChange(PATH_CHANGE_TRANSFORM);
77         }
78     }
79     void block() { _blocked = true; }
80     void unblock() { _blocked = false; }
81 private:
82     PathManipulator *_pm;
83     bool _blocked;
84 };
86 void build_segment(Geom::PathBuilder &, Node *, Node *);
88 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
89         Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
90     : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
91     , _subpaths(*this)
92     , _multi_path_manipulator(mpm)
93     , _path(path)
94     , _spcurve(NULL)
95     , _dragpoint(new CurveDragPoint(*this))
96     , _observer(new PathManipulatorObserver(this))
97     , _edit_transform(et)
98     , _num_selected(0)
99     , _show_handles(true)
100     , _show_outline(false)
101     , _lpe_key(lpe_key)
103     if (_lpe_key.empty()) {
104         _i2d_transform = sp_item_i2d_affine(SP_ITEM(path));
105     } else {
106         _i2d_transform = Geom::identity();
107     }
108     _d2i_transform = _i2d_transform.inverse();
109     _dragpoint->setVisible(false);
111     _getGeometry();
113     _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
114     sp_canvas_item_hide(_outline);
115     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
116         SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
117     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
119     _subpaths.signal_insert_node.connect(
120         sigc::mem_fun(*this, &PathManipulator::_attachNodeHandlers));
121     // NOTE: signal_remove_node is called just before destruction. Nodes are trackable,
122     // so removing the signals manually is not necessary.
123     /*_subpaths.signal_remove_node.connect(
124         sigc::mem_fun(*this, &PathManipulator::_removeNodeHandlers));*/
126     _selection.signal_update.connect(
127         sigc::mem_fun(*this, &PathManipulator::update));
128     _selection.signal_point_changed.connect(
129         sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
130     _dragpoint->signal_update.connect(
131         sigc::mem_fun(*this, &PathManipulator::update));
132     _desktop->signal_zoom_changed.connect(
133         sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
135     _createControlPointsFromGeometry();
137     _path->repr->addObserver(*_observer);
140 PathManipulator::~PathManipulator()
142     delete _dragpoint;
143     if (_path) _path->repr->removeObserver(*_observer);
144     delete _observer;
145     gtk_object_destroy(_outline);
146     if (_spcurve) _spcurve->unref();
147     clear();
150 /** Handle motion events to update the position of the curve drag point. */
151 bool PathManipulator::event(GdkEvent *event)
153     if (empty()) return false;
155     switch (event->type)
156     {
157     case GDK_MOTION_NOTIFY:
158         _updateDragPoint(event_point(event->motion));
159         break;
160     default: break;
161     }
162     return false;
165 /** Check whether the manipulator has any nodes. */
166 bool PathManipulator::empty() {
167     return !_path || _subpaths.empty();
170 /** Update the display and the outline of the path. */
171 void PathManipulator::update()
173     _createGeometryFromControlPoints();
176 /** Store the changes to the path in XML. */
177 void PathManipulator::writeXML()
179     if (!_path) return;
180     _observer->block();
181     if (!empty()) {
182         SP_OBJECT(_path)->updateRepr();
183         _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
184     } else {
185         // this manipulator will have to be destroyed right after this call
186         _getXMLNode()->removeObserver(*_observer);
187         sp_object_ref(_path);
188         _path->deleteObject(true, true);
189         sp_object_unref(_path);
190         _path = 0;
191     }
192     _observer->unblock();
195 /** Remove all nodes from the path. */
196 void PathManipulator::clear()
198     // no longer necessary since nodes remove themselves from selection on destruction
199     //_removeNodesFromSelection();
200     _subpaths.clear();
203 /** Select all nodes in subpaths that have something selected. */
204 void PathManipulator::selectSubpaths()
206     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
207         NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
208         for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
209             if (j->selected()) {
210                 // if at least one of the nodes from this subpath is selected,
211                 // select all nodes from this subpath
212                 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
213                     _selection.insert(ins.ptr());
214                 continue;
215             }
216         }
217     }
220 /** Move the selection forward or backward by one node in each subpath, based on the sign
221  * of the parameter. */
222 void PathManipulator::shiftSelection(int dir)
224     if (dir == 0) return;
225     if (_num_selected == 0) {
226         // select the first node of the path.
227         SubpathList::iterator s = _subpaths.begin();
228         if (s == _subpaths.end()) return;
229         NodeList::iterator n = (*s)->begin();
230         if (n != (*s)->end())
231             _selection.insert(n.ptr());
232         return;
233     }
234     // We cannot do any tricks here, like iterating in different directions based on
235     // the sign and only setting the selection of nodes behind us, because it would break
236     // for closed paths.
237     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
238         std::deque<bool> sels; // I hope this is specialized for bools!
239         unsigned num = 0;
240         
241         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
242             sels.push_back(j->selected());
243             _selection.erase(j.ptr());
244             ++num;
245         }
246         if (num == 0) continue; // should never happen! zero-node subpaths are not allowed
248         num = 0;
249         // In closed subpath, shift the selection cyclically. In an open one,
250         // let the selection 'slide into nothing' at ends.
251         if (dir > 0) {
252             if ((*i)->closed()) {
253                 bool last = sels.back();
254                 sels.pop_back();
255                 sels.push_front(last);
256             } else {
257                 sels.push_front(false);
258             }
259         } else {
260             if ((*i)->closed()) {
261                 bool first = sels.front();
262                 sels.pop_front();
263                 sels.push_back(first);
264             } else {
265                 sels.push_back(false);
266                 num = 1;
267             }
268         }
270         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
271             if (sels[num]) _selection.insert(j.ptr());
272             ++num;
273         }
274     }
277 /** Invert selection in the selected subpaths. */
278 void PathManipulator::invertSelectionInSubpaths()
280     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
281         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
282             if (j->selected()) {
283                 // found selected node - invert selection in this subpath
284                 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
285                     if (k->selected()) _selection.erase(k.ptr());
286                     else _selection.insert(k.ptr());
287                 }
288                 // next subpath
289                 break;
290             }
291         }
292     }
295 /** Insert a new node in the middle of each selected segment. */
296 void PathManipulator::insertNodes()
298     if (_num_selected < 2) return;
300     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
301         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
302             NodeList::iterator k = j.next();
303             if (k && j->selected() && k->selected()) {
304                 j = subdivideSegment(j, 0.5);
305                 _selection.insert(j.ptr());
306             }
307         }
308     }
311 /** Replace contiguous selections of nodes in each subpath with one node. */
312 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
314     if (_num_selected < 2) return;
315     hideDragPoint();
317     bool pos_valid = preserve_pos;
318     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
319         SubpathPtr sp = *i;
320         unsigned num_selected = 0, num_unselected = 0;
321         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
322             if (j->selected()) ++num_selected;
323             else ++num_unselected;
324         }
325         if (num_selected < 2) continue;
326         if (num_unselected == 0) {
327             // if all nodes in a subpath are selected, the operation doesn't make much sense
328             continue;
329         }
331         // Start from unselected node in closed paths, so that we don't start in the middle
332         // of a selection
333         NodeList::iterator sel_beg = sp->begin(), sel_end;
334         if (sp->closed()) {
335             while (sel_beg->selected()) ++sel_beg;
336         }
338         // Work loop
339         while (num_selected > 0) {
340             // Find selected node
341             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
342             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
343                 "but there are still nodes to process!");
345             // note: this is initialized to zero, because the loop below counts sel_beg as well
346             // the loop conditions are simpler that way
347             unsigned num_points = 0;
348             bool use_pos = false;
349             Geom::Point back_pos, front_pos;
350             back_pos = *sel_beg->back();
352             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
353                 ++num_points;
354                 front_pos = *sel_end->front();
355                 if (pos_valid && sel_end == preserve_pos) use_pos = true;
356             }
357             if (num_points > 1) {
358                 Geom::Point joined_pos;
359                 if (use_pos) {
360                     joined_pos = preserve_pos->position();
361                     pos_valid = false;
362                 } else {
363                     joined_pos = Geom::middle_point(back_pos, front_pos);
364                 }
365                 sel_beg->setType(NODE_CUSP, false);
366                 sel_beg->move(joined_pos);
367                 // do not move handles if they aren't degenerate
368                 if (!sel_beg->back()->isDegenerate()) {
369                     sel_beg->back()->setPosition(back_pos);
370                 }
371                 if (!sel_end.prev()->front()->isDegenerate()) {
372                     sel_beg->front()->setPosition(front_pos);
373                 }
374                 sel_beg = sel_beg.next();
375                 while (sel_beg != sel_end) {
376                     NodeList::iterator next = sel_beg.next();
377                     sp->erase(sel_beg);
378                     sel_beg = next;
379                     --num_selected;
380                 }
381             }
382             --num_selected; // for the joined node or single selected node
383         }
384     }
387 /** Remove nodes in the middle of selected segments. */
388 void PathManipulator::weldSegments()
390     if (_num_selected < 2) return;
391     hideDragPoint();
393     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
394         SubpathPtr sp = *i;
395         unsigned num_selected = 0, num_unselected = 0;
396         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
397             if (j->selected()) ++num_selected;
398             else ++num_unselected;
399         }
400         if (num_selected < 3) continue;
401         if (num_unselected == 0 && sp->closed()) {
402             // if all nodes in a closed subpath are selected, the operation doesn't make much sense
403             continue;
404         }
406         // Start from unselected node in closed paths, so that we don't start in the middle
407         // of a selection
408         NodeList::iterator sel_beg = sp->begin(), sel_end;
409         if (sp->closed()) {
410             while (sel_beg->selected()) ++sel_beg;
411         }
413         // Work loop
414         while (num_selected > 0) {
415             // Find selected node
416             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
417             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
418                 "but there are still nodes to process!");
420             // note: this is initialized to zero, because the loop below counts sel_beg as well
421             // the loop conditions are simpler that way
422             unsigned num_points = 0;
424             // find the end of selected segment
425             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
426                 ++num_points;
427             }
428             if (num_points > 2) {
429                 // remove nodes in the middle
430                 sel_beg = sel_beg.next();
431                 while (sel_beg != sel_end.prev()) {
432                     NodeList::iterator next = sel_beg.next();
433                     sp->erase(sel_beg);
434                     sel_beg = next;
435                 }
436                 sel_beg = sel_end;
437             }
438             num_selected -= num_points;
439         }
440     }
443 /** Break the subpath at selected nodes. It also works for single node closed paths. */
444 void PathManipulator::breakNodes()
446     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
447         SubpathPtr sp = *i;
448         NodeList::iterator cur = sp->begin(), end = sp->end();
449         if (!sp->closed()) {
450             // Each open path must have at least two nodes so no checks are required.
451             // For 2-node open paths, cur == end
452             ++cur;
453             --end;
454         }
455         for (; cur != end; ++cur) {
456             if (!cur->selected()) continue;
457             SubpathPtr ins;
458             bool becomes_open = false;
460             if (sp->closed()) {
461                 // Move the node to break at to the beginning of path
462                 if (cur != sp->begin())
463                     sp->splice(sp->begin(), *sp, cur, sp->end());
464                 sp->setClosed(false);
465                 ins = sp;
466                 becomes_open = true;
467             } else {
468                 SubpathPtr new_sp(new NodeList(_subpaths));
469                 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
470                 _subpaths.insert(i, new_sp);
471                 ins = new_sp;
472             }
474             Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
475             ins->insert(ins->end(), n);
476             cur->setType(NODE_CUSP, false);
477             n->back()->setRelativePos(cur->back()->relativePos());
478             cur->back()->retract();
479             n->sink();
481             if (becomes_open) {
482                 cur = sp->begin(); // this will be increased to ++sp->begin()
483                 end = --sp->end();
484             }
485         }
486     }
489 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
490  * in a way that attempts to preserve the original shape of the curve. */
491 void PathManipulator::deleteNodes(bool keep_shape)
493     if (_num_selected == 0) return;
494     hideDragPoint();
496     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
497         SubpathPtr sp = *i;
499         // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
500         // in a closed one, delete entire subpath.
501         unsigned num_unselected = 0, num_selected = 0;
502         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
503             if (j->selected()) ++num_selected;
504             else ++num_unselected;
505         }
506         if (num_selected == 0) {
507             ++i;
508             continue;
509         }
510         if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
511             _subpaths.erase(i++);
512             continue;
513         }
515         // In closed paths, start from an unselected node - otherwise we might start in the middle
516         // of a selected stretch and the resulting bezier fit would be suboptimal
517         NodeList::iterator sel_beg = sp->begin(), sel_end;
518         if (sp->closed()) {
519             while (sel_beg->selected()) ++sel_beg;
520         }
521         sel_end = sel_beg;
522         
523         while (num_selected > 0) {
524             while (!sel_beg->selected()) {
525                 sel_beg = sel_beg.next();
526             }
527             sel_end = sel_beg;
529             while (sel_end && sel_end->selected()) {
530                 sel_end = sel_end.next();
531             }
532             
533             num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
534         }
535         ++i;
536     }
539 /** @brief Delete nodes between the two iterators.
540  * The given range can cross the beginning of the subpath in closed subpaths.
541  * @param start      Beginning of the range to delete
542  * @param end        End of the range
543  * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
544  *                   the shape before deletion
545  * @return Number of deleted nodes */
546 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
548     unsigned const samples_per_segment = 10;
549     double const t_step = 1.0 / samples_per_segment;
551     unsigned del_len = 0;
552     for (NodeList::iterator i = start; i != end; ++i) {
553         ++del_len;
554     }
555     if (del_len == 0) return 0;
557     // set surrounding node types to cusp if:
558     // 1. keep_shape is on, or
559     // 2. we are deleting at the end or beginning of an open path
560     if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
561     if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
563     if (keep_shape && start.prev() && end) {
564         unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
565         Geom::Point *bezier_data = new Geom::Point[num_samples];
566         Geom::Point result[4];
567         unsigned seg = 0;
569         for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
570             Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
571             for (unsigned s = 0; s < samples_per_segment; ++s) {
572                 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
573             }
574             ++seg;
575         }
576         // Fill last point
577         bezier_data[num_samples - 1] = end->position();
578         // Compute replacement bezier curve
579         // TODO the fitting algorithm sucks - rewrite it to be awesome
580         bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
581         delete[] bezier_data;
583         start.prev()->front()->setPosition(result[1]);
584         end->back()->setPosition(result[2]);
585     }
587     // We can't use nl->erase(start, end), because it would break when the stretch
588     // crosses the beginning of a closed subpath
589     NodeList *nl = start->list();
590     while (start != end) {
591         NodeList::iterator next = start.next();
592         nl->erase(start);
593         start = next;
594     }
596     return del_len;
599 /** Removes selected segments */
600 void PathManipulator::deleteSegments()
602     if (_num_selected == 0) return;
603     hideDragPoint();
605     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
606         SubpathPtr sp = *i;
607         bool has_unselected = false;
608         unsigned num_selected = 0;
609         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
610             if (j->selected()) {
611                 ++num_selected;
612             } else {
613                 has_unselected = true;
614             }
615         }
616         if (!has_unselected) {
617             _subpaths.erase(i++);
618             continue;
619         }
621         NodeList::iterator sel_beg = sp->begin();
622         if (sp->closed()) {
623             while (sel_beg && sel_beg->selected()) ++sel_beg;
624         }
625         while (num_selected > 0) {
626             if (!sel_beg->selected()) {
627                 sel_beg = sel_beg.next();
628                 continue;
629             }
630             NodeList::iterator sel_end = sel_beg;
631             unsigned num_points = 0;
632             while (sel_end && sel_end->selected()) {
633                 sel_end = sel_end.next();
634                 ++num_points;
635             }
636             if (num_points >= 2) {
637                 // Retract end handles
638                 sel_end.prev()->setType(NODE_CUSP, false);
639                 sel_end.prev()->back()->retract();
640                 sel_beg->setType(NODE_CUSP, false);
641                 sel_beg->front()->retract();
642                 if (sp->closed()) {
643                     // In closed paths, relocate the beginning of the path to the last selected
644                     // node and then unclose it. Remove the nodes from the first selected node
645                     // to the new end of path.
646                     if (sel_end.prev() != sp->begin())
647                         sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
648                     sp->setClosed(false);
649                     sp->erase(sel_beg.next(), sp->end());
650                 } else {
651                     // for open paths:
652                     // 1. At end or beginning, delete including the node on the end or beginning
653                     // 2. In the middle, delete only inner nodes
654                     if (sel_beg == sp->begin()) {
655                         sp->erase(sp->begin(), sel_end.prev());
656                     } else if (sel_end == sp->end()) {
657                         sp->erase(sel_beg.next(), sp->end());
658                     } else {
659                         SubpathPtr new_sp(new NodeList(_subpaths));
660                         new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
661                         _subpaths.insert(i, new_sp);
662                         if (sel_end.prev())
663                             sp->erase(sp->begin(), sel_end.prev());
664                     }
665                 }
666             }
667             sel_beg = sel_end;
668             num_selected -= num_points;
669         }
670         ++i;
671     }
674 /** Reverse subpaths of the path.
675  * @param selected_only If true, only paths that have at least one selected node
676  *                      will be reversed. Otherwise all subpaths will be reversed. */
677 void PathManipulator::reverseSubpaths(bool selected_only)
679     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
680         if (selected_only) {
681             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
682                 if (j->selected()) {
683                     (*i)->reverse();
684                     break; // continue with the next subpath
685                 }
686             }
687         } else {
688             (*i)->reverse();
689         }
690     }
693 /** Make selected segments curves / lines. */
694 void PathManipulator::setSegmentType(SegmentType type)
696     if (_num_selected == 0) return;
697     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
698         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
699             NodeList::iterator k = j.next();
700             if (!(k && j->selected() && k->selected())) continue;
701             switch (type) {
702             case SEGMENT_STRAIGHT:
703                 if (j->front()->isDegenerate() && k->back()->isDegenerate())
704                     break;
705                 j->front()->move(*j);
706                 k->back()->move(*k);
707                 break;
708             case SEGMENT_CUBIC_BEZIER:
709                 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
710                     break;
711                 j->front()->move(j->position() + (k->position() - j->position()) / 3);
712                 k->back()->move(k->position() + (j->position() - k->position()) / 3);
713                 break;
714             }
715         }
716     }
719 /** Set the visibility of handles. */
720 void PathManipulator::showHandles(bool show)
722     if (show == _show_handles) return;
723     if (show) {
724         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
725             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
726                 if (!j->selected()) continue;
727                 j->showHandles(true);
728                 if (j.prev()) j.prev()->showHandles(true);
729                 if (j.next()) j.next()->showHandles(true);
730             }
731         }
732     } else {
733         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
734             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
735                 j->showHandles(false);
736             }
737         }
738     }
739     _show_handles = show;
742 /** Set the visibility of outline. */
743 void PathManipulator::showOutline(bool show)
745     if (show == _show_outline) return;
746     _show_outline = show;
747     _updateOutline();
750 void PathManipulator::showPathDirection(bool show)
752     if (show == _show_path_direction) return;
753     _show_path_direction = show;
754     _updateOutline();
757 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
759     Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
760     _edit_transform = tnew;
761     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
762         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
763             j->transform(delta);
764         }
765     }
766     _createGeometryFromControlPoints();
769 /** Hide the curve drag point until the next motion event.
770  * This should be called at the beginning of every method that can delete nodes.
771  * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
772 void PathManipulator::hideDragPoint()
774     _dragpoint->setVisible(false);
775     _dragpoint->setIterator(NodeList::iterator());
778 /** Insert a node in the segment beginning with the supplied iterator,
779  * at the given time value */
780 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
782     if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
783     NodeList &list = NodeList::get(first);
784     NodeList::iterator second = first.next();
785     if (!second) throw std::invalid_argument("Subdivide after last node in open path");
787     // We need to insert the segment after 'first'. We can't simply use 'second'
788     // as the point of insertion, because when 'first' is the last node of closed path,
789     // the new node will be inserted as the first node instead.
790     NodeList::iterator insert_at = first;
791     ++insert_at;
793     NodeList::iterator inserted;
794     if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
795         // for a line segment, insert a cusp node
796         Node *n = new Node(_multi_path_manipulator._path_data.node_data,
797             Geom::lerp(t, first->position(), second->position()));
798         n->setType(NODE_CUSP, false);
799         inserted = list.insert(insert_at, n);
800     } else {
801         // build bezier curve and subdivide
802         Geom::CubicBezier temp(first->position(), first->front()->position(),
803             second->back()->position(), second->position());
804         std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
805         std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
807         // set new handle positions
808         Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
809         n->back()->setPosition(seg1[2]);
810         n->front()->setPosition(seg2[1]);
811         n->setType(NODE_SMOOTH, false);
812         inserted = list.insert(insert_at, n);
814         first->front()->move(seg1[1]);
815         second->back()->move(seg2[2]);
816     }
817     return inserted;
820 /** Find the node that is closest/farthest from the origin
821  * @param origin Point of reference
822  * @param search_selected Consider selected nodes
823  * @param search_unselected Consider unselected nodes
824  * @param closest If true, return closest node, if false, return farthest
825  * @return The matching node, or an empty iterator if none found
826  */
827 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
828     bool search_unselected, bool closest)
830     NodeList::iterator match;
831     double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
832     if (_num_selected == 0 && !search_unselected) return match;
834     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
835         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
836             if(j->selected()) {
837                 if (!search_selected) continue;
838             } else {
839                 if (!search_unselected) continue;
840             }
841             double dist = Geom::distance(*j, *origin);
842             bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
843             if (cond) {
844                 match = j;
845                 extr_dist = dist;
846             }
847         }
848     }
849     return match;
852 /** Called by the XML observer when something else than us modifies the path. */
853 void PathManipulator::_externalChange(unsigned type)
855     switch (type) {
856     case PATH_CHANGE_D: {
857         _getGeometry();
859         // ugly: stored offsets of selected nodes in a vector
860         // vector<bool> should be specialized so that it takes only 1 bit per value
861         std::vector<bool> selpos;
862         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
863             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
864                 selpos.push_back(j->selected());
865             }
866         }
867         unsigned size = selpos.size(), curpos = 0;
869         _createControlPointsFromGeometry();
871         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
872             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
873                 if (curpos >= size) goto end_restore;
874                 if (selpos[curpos]) _selection.insert(j.ptr());
875                 ++curpos;
876             }
877         }
878         end_restore:
880         _updateOutline();
881         } break;
882     case PATH_CHANGE_TRANSFORM: {
883         Geom::Matrix i2d_change = _d2i_transform;
884         _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
885         _d2i_transform = _i2d_transform.inverse();
886         i2d_change *= _i2d_transform;
887         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
888             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
889                 j->transform(i2d_change);
890             }
891         }
892         _updateOutline();
893         } break;
894     default: break;
895     }
898 /** Create nodes and handles based on the XML of the edited path. */
899 void PathManipulator::_createControlPointsFromGeometry()
901     clear();
903     // sanitize pathvector and store it in SPCurve,
904     // so that _updateDragPoint doesn't crash on paths with naked movetos
905     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
906     for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
907         if (i->empty()) pathv.erase(i++);
908         else ++i;
909     }
910     _spcurve->set_pathvector(pathv);
912     pathv *= (_edit_transform * _i2d_transform);
914     // in this loop, we know that there are no zero-segment subpaths
915     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
916         // prepare new subpath
917         SubpathPtr subpath(new NodeList(_subpaths));
918         _subpaths.push_back(subpath);
920         Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
921         subpath->push_back(previous_node);
922         Geom::Curve const &cseg = pit->back_closed();
923         bool fuse_ends = pit->closed()
924             && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
926         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
927             Geom::Point pos = cit->finalPoint();
928             Node *current_node;
929             // if the closing segment is degenerate and the path is closed, we need to move
930             // the handle of the first node instead of creating a new one
931             if (fuse_ends && cit == --(pit->end_open())) {
932                 current_node = subpath->begin().get_pointer();
933             } else {
934                 /* regardless of segment type, create a new node at the end
935                  * of this segment (unless this is the last segment of a closed path
936                  * with a degenerate closing segment */
937                 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
938                 subpath->push_back(current_node);
939             }
940             // if this is a bezier segment, move handles appropriately
941             if (Geom::CubicBezier const *cubic_bezier =
942                 dynamic_cast<Geom::CubicBezier const*>(&*cit))
943             {
944                 std::vector<Geom::Point> points = cubic_bezier->points();
946                 previous_node->front()->setPosition(points[1]);
947                 current_node ->back() ->setPosition(points[2]);
948             }
949             previous_node = current_node;
950         }
951         // If the path is closed, make the list cyclic
952         if (pit->closed()) subpath->setClosed(true);
953     }
955     // we need to set the nodetypes after all the handles are in place,
956     // so that pickBestType works correctly
957     // TODO maybe migrate to inkscape:node-types?
958     gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
959     std::string nodetype_string = nts_raw ? nts_raw : "";
960     /* Calculate the needed length of the nodetype string.
961      * For closed paths, the entry is duplicated for the starting node,
962      * so we can just use the count of segments including the closing one
963      * to include the extra end node. */
964     std::string::size_type nodetype_len = 0;
965     for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
966         if (i->empty()) continue;
967         nodetype_len += i->size_closed();
968     }
969     /* pad the string to required length with a bogus value.
970      * 'b' and any other letter not recognized by the parser causes the best fit to be set
971      * as the node type */
972     if (nodetype_len > nodetype_string.size()) {
973         nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
974     }
975     std::string::iterator tsi = nodetype_string.begin();
976     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
977         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
978             j->setType(Node::parse_nodetype(*tsi++), false);
979         }
980         if ((*i)->closed()) {
981             // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
982             // the first one to remain backward compatible.
983             (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
984         }
985     }
988 /** Construct the geometric representation of nodes and handles, update the outline
989  * and display */
990 void PathManipulator::_createGeometryFromControlPoints()
992     Geom::PathBuilder builder;
993     for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
994         SubpathPtr subpath = *spi;
995         if (subpath->empty()) {
996             _subpaths.erase(spi++);
997             continue;
998         }
999         NodeList::iterator prev = subpath->begin();
1000         builder.moveTo(prev->position());
1002         for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1003             build_segment(builder, prev.ptr(), i.ptr());
1004             prev = i;
1005         }
1006         if (subpath->closed()) {
1007             // Here we link the last and first node if the path is closed.
1008             // If the last segment is Bezier, we add it.
1009             if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1010                 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1011             }
1012             // if that segment is linear, we just call closePath().
1013             builder.closePath();
1014         }
1015         ++spi;
1016     }
1017     builder.finish();
1018     _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1019     _updateOutline();
1020     _setGeometry();
1023 /** Build one segment of the geometric representation.
1024  * @relates PathManipulator */
1025 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1027     if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1028     {
1029         // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1030         // and trying to display a path using them results in funny artifacts.
1031         builder.lineTo(cur_node->position());
1032     } else {
1033         // this is a bezier segment
1034         builder.curveTo(
1035             prev_node->front()->position(),
1036             cur_node->back()->position(),
1037             cur_node->position());
1038     }
1041 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1042 std::string PathManipulator::_createTypeString()
1044     // precondition: no single-node subpaths
1045     std::stringstream tstr;
1046     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1047         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1048             tstr << j->type();
1049         }
1050         // nodestring format peculiarity: first node is counted twice for closed paths
1051         if ((*i)->closed()) tstr << (*i)->begin()->type();
1052     }
1053     return tstr.str();
1056 /** Update the path outline. */
1057 void PathManipulator::_updateOutline()
1059     if (!_show_outline) {
1060         sp_canvas_item_hide(_outline);
1061         return;
1062     }
1064     Geom::PathVector pv = _spcurve->get_pathvector();
1065     pv *= (_edit_transform * _i2d_transform);
1066     // This SPCurve thing has to be killed with extreme prejudice
1067     SPCurve *_hc = new SPCurve();
1068     if (_show_path_direction) {
1069         // To show the direction, we append additional subpaths which consist of a single
1070         // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1071         // at an angle 150 degrees from the unit tangent. This creates the appearance
1072         // of little 'harpoons' that show the direction of the subpaths.
1073         Geom::PathVector arrows;
1074         for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1075             Geom::Path &path = *i;
1076             for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1077                 Geom::Point at = j->pointAt(0.5);
1078                 Geom::Point ut = j->unitTangentAt(0.5);
1079                 // rotate the point 
1080                 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1081                 Geom::Point arrow_end = _desktop->w2d(
1082                     _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1084                 Geom::Path arrow(at);
1085                 arrow.appendNew<Geom::LineSegment>(arrow_end);
1086                 arrows.push_back(arrow);
1087             }
1088         }
1089         pv.insert(pv.end(), arrows.begin(), arrows.end());
1090     }
1091     _hc->set_pathvector(pv);
1092     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1093     sp_canvas_item_show(_outline);
1094     _hc->unref();
1097 /** Retrieve the geometry of the edited object from the object tree */
1098 void PathManipulator::_getGeometry()
1100     using namespace Inkscape::LivePathEffect;
1101     if (!_lpe_key.empty()) {
1102         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1103         if (lpe) {
1104             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1105             if (!_spcurve)
1106                 _spcurve = new SPCurve(pathparam->get_pathvector());
1107             else
1108                 _spcurve->set_pathvector(pathparam->get_pathvector());
1109         }
1110     } else {
1111         if (_spcurve) _spcurve->unref();
1112         _spcurve = sp_path_get_curve_for_edit(_path);
1113     }
1116 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1117 void PathManipulator::_setGeometry()
1119     using namespace Inkscape::LivePathEffect;
1120     if (empty()) return;
1122     if (!_lpe_key.empty()) {
1123         // copied from nodepath.cpp
1124         // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1125         // a LivePathEffectObject. (mad laughter)
1126         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1127         if (lpe) {
1128             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1129             pathparam->set_new_value(_spcurve->get_pathvector(), false);
1130             LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1131         }
1132     } else {
1133         if (_path->repr->attribute("inkscape:original-d"))
1134             sp_path_set_original_curve(_path, _spcurve, true, false);
1135         else
1136             sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1137     }
1140 /** Figure out in what attribute to store the nodetype string. */
1141 Glib::ustring PathManipulator::_nodetypesKey()
1143     if (_lpe_key.empty()) return "sodipodi:nodetypes";
1144     return _lpe_key + "-nodetypes";
1147 /** Return the XML node we are editing.
1148  * This method is wrong but necessary at the moment. */
1149 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1151     if (_lpe_key.empty()) return _path->repr;
1152     return LIVEPATHEFFECT(_path)->repr;
1155 void PathManipulator::_attachNodeHandlers(Node *node)
1157     Handle *handles[2] = { node->front(), node->back() };
1158     for (int i = 0; i < 2; ++i) {
1159         handles[i]->signal_update.connect(
1160             sigc::mem_fun(*this, &PathManipulator::update));
1161         handles[i]->signal_ungrabbed.connect(
1162             sigc::hide(
1163                 sigc::mem_fun(*this, &PathManipulator::_handleUngrabbed)));
1164         handles[i]->signal_grabbed.connect(
1165             sigc::bind_return(
1166                 sigc::hide(
1167                     sigc::mem_fun(*this, &PathManipulator::_handleGrabbed)),
1168                 false));
1169         handles[i]->signal_clicked.connect(
1170             sigc::bind<0>(
1171                 sigc::mem_fun(*this, &PathManipulator::_handleClicked),
1172                 handles[i]));
1173     }
1174     node->signal_clicked.connect(
1175         sigc::bind<0>(
1176             sigc::mem_fun(*this, &PathManipulator::_nodeClicked),
1177             node));
1180 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1182     // cycle between node types on ctrl+click
1183     if (event->button != 1) return false;
1184     if (held_alt(*event) && held_control(*event)) {
1185         // Ctrl+Alt+click: delete nodes
1186         hideDragPoint();
1187         NodeList::iterator iter = NodeList::get_iterator(n);
1188         NodeList *nl = iter->list();
1190         if (nl->size() <= 1 || (nl->size() <= 2 && !nl->closed())) {
1191             // Removing last node of closed path - delete it
1192             nl->kill();
1193         } else {
1194             // In other cases, delete the node under cursor
1195             _deleteStretch(iter, iter.next(), true);
1196         }
1198         if (!empty()) { 
1199             update();
1200         }
1201         // We need to call MPM's method because it could have been our last node
1202         _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1204         return true;
1205     } else if (held_control(*event)) {
1206         // Ctrl+click: cycle between node types
1207         if (n->isEndNode()) {
1208             if (n->type() == NODE_CUSP) {
1209                 n->setType(NODE_SMOOTH);
1210             } else {
1211                 n->setType(NODE_CUSP);
1212             }
1213         } else {
1214             n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1215         }
1216         update();
1217         _commit(_("Cycle node type"));
1218         return true;
1219     }
1220     return false;
1223 void PathManipulator::_handleGrabbed()
1225     _selection.hideTransformHandles();
1228 void PathManipulator::_handleUngrabbed()
1230     _selection.restoreTransformHandles();
1231     _commit(_("Drag handle"));
1234 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1236     // retracting by Ctrl+click
1237     if (event->button == 1 && held_control(*event)) {
1238         h->move(h->parent()->position());
1239         update();
1240         _commit(_("Retract handle"));
1241         return true;
1242     }
1243     return false;
1246 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1248     // don't do anything if we do not show handles
1249     if (!_show_handles) return;
1251     // only do something if a node changed selection state
1252     Node *node = dynamic_cast<Node*>(p);
1253     if (!node) return;
1255     // update handle display
1256     NodeList::iterator iters[5];
1257     iters[2] = NodeList::get_iterator(node);
1258     iters[1] = iters[2].prev();
1259     iters[3] = iters[2].next();
1260     if (selected) {
1261         // selection - show handles on this node and adjacent ones
1262         node->showHandles(true);
1263         if (iters[1]) iters[1]->showHandles(true);
1264         if (iters[3]) iters[3]->showHandles(true);
1265     } else {
1266         /* Deselection is more complex.
1267          * The change might affect 3 nodes - this one and two adjacent.
1268          * If the node and both its neighbors are deselected, hide handles.
1269          * Otherwise, leave as is. */
1270         if (iters[1]) iters[0] = iters[1].prev();
1271         if (iters[3]) iters[4] = iters[3].next();
1272         bool nodesel[5];
1273         for (int i = 0; i < 5; ++i) {
1274             nodesel[i] = iters[i] && iters[i]->selected();
1275         }
1276         for (int i = 1; i < 4; ++i) {
1277             if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1278                 iters[i]->showHandles(false);
1279             }
1280         }
1281     }
1283     if (selected) ++_num_selected;
1284     else --_num_selected;
1287 /** Removes all nodes belonging to this manipulator from the control pont selection */
1288 void PathManipulator::_removeNodesFromSelection()
1290     // remove this manipulator's nodes from selection
1291     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1292         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1293             _selection.erase(j.get_pointer());
1294         }
1295     }
1298 /** Update the XML representation and put the specified annotation on the undo stack */
1299 void PathManipulator::_commit(Glib::ustring const &annotation)
1301     writeXML();
1302     sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1305 /** Update the position of the curve drag point such that it is over the nearest
1306  * point of the path. */
1307 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1309     // TODO find a way to make this faster (no transform required)
1310     Geom::PathVector pv = _spcurve->get_pathvector() * (_edit_transform * _i2d_transform);
1311     boost::optional<Geom::PathVectorPosition> pvp
1312         = Geom::nearestPoint(pv, _desktop->w2d(evp));
1313     if (!pvp) return;
1314     Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t));
1315     
1316     double fracpart;
1317     std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1318     for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1319     NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1320     
1321     double stroke_tolerance = _getStrokeTolerance();
1322     if (Geom::distance(evp, nearest_point) < stroke_tolerance) {
1323         _dragpoint->setVisible(true);
1324         _dragpoint->setPosition(_desktop->w2d(nearest_point));
1325         _dragpoint->setSize(2 * stroke_tolerance);
1326         _dragpoint->setTimeValue(fracpart);
1327         _dragpoint->setIterator(first);
1328     } else {
1329         _dragpoint->setVisible(false);
1330     }
1333 /// This is called on zoom change to update the direction arrows
1334 void PathManipulator::_updateOutlineOnZoomChange()
1336     if (_show_path_direction) _updateOutline();
1339 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1340  * or segment selection, in window coordinates. */
1341 double PathManipulator::_getStrokeTolerance()
1343     /* Stroke event tolerance is equal to half the stroke's width plus the global
1344      * drag tolerance setting.  */
1345     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1346     double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1347     if (_path && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1348         ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1349             * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1350             * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1351     }
1352     return ret;
1355 } // namespace UI
1356 } // namespace Inkscape
1358 /*
1359   Local Variables:
1360   mode:c++
1361   c-file-style:"stroustrup"
1362   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1363   indent-tabs-mode:nil
1364   fill-column:99
1365   End:
1366 */
1367 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :