Code

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