1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Authors:
3  *   Krzysztof Kosiński <tweenk.pl@gmail.com>
4  *   Jon A. Cruz <jon@joncruz.org>
5  *
6  * Copyright (C) 2009 Authors
7  * Released under GNU GPL v2+, read the file 'COPYING' for more information.
8  */
9 
10 #include <atomic>
11 #include <iostream>
12 #include <stdexcept>
13 #include <boost/utility.hpp>
14 
15 #include <glib/gi18n.h>
16 #include <gdk/gdkkeysyms.h>
17 
18 #include <2geom/bezier-utils.h>
19 
20 #include "desktop.h"
21 #include "multi-path-manipulator.h"
22 #include "snap.h"
23 
24 #include "display/control/canvas-item-group.h"
25 #include "display/control/canvas-item-curve.h"
26 
27 #include "ui/tool/control-point-selection.h"
28 #include "ui/tool/event-utils.h"
29 #include "ui/tool/path-manipulator.h"
30 #include "ui/tools/node-tool.h"
31 #include "ui/tools-switch.h"
32 #include "ui/widget/canvas.h"
33 
34 namespace {
35 
nodeTypeToCtrlType(Inkscape::UI::NodeType type)36 Inkscape::CanvasItemCtrlType nodeTypeToCtrlType(Inkscape::UI::NodeType type)
37 {
38     Inkscape::CanvasItemCtrlType result = Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_CUSP;
39     switch(type) {
40         case Inkscape::UI::NODE_SMOOTH:
41             result = Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_SMOOTH;
42             break;
43         case Inkscape::UI::NODE_AUTO:
44             result = Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_AUTO;
45             break;
46         case Inkscape::UI::NODE_SYMMETRIC:
47             result = Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_SYMETRICAL;
48             break;
49         case Inkscape::UI::NODE_CUSP:
50         default:
51             result = Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_CUSP;
52             break;
53     }
54     return result;
55 }
56 
57 /**
58  * @brief provides means to estimate float point rounding error due to serialization to svg
59  *
60  *  Keeps cached value up to date with preferences option `/options/svgoutput/numericprecision`
61  *  to avoid costly direct reads
62  * */
63 class SvgOutputPrecisionWatcher : public Inkscape::Preferences::Observer {
64 public:
65     /// Returns absolute \a value`s rounding serialization error based on current preferences settings
error_of(double value)66     static double error_of(double value) {
67         return value * instance().rel_error;
68     }
69 
notify(const Inkscape::Preferences::Entry & new_val)70     void notify(const Inkscape::Preferences::Entry &new_val) override {
71         int digits = new_val.getIntLimited(6, 1, 16);
72         set_numeric_precision(digits);
73     }
74 
75 private:
SvgOutputPrecisionWatcher()76   SvgOutputPrecisionWatcher() : Observer("/options/svgoutput/numericprecision"), rel_error(1) {
77         Inkscape::Preferences::get()->addObserver(*this);
78         int digits = Inkscape::Preferences::get()->getIntLimited("/options/svgoutput/numericprecision", 6, 1, 16);
79         set_numeric_precision(digits);
80     }
81 
~SvgOutputPrecisionWatcher()82     ~SvgOutputPrecisionWatcher() override {
83         Inkscape::Preferences::get()->removeObserver(*this);
84     }
85     /// Update cached value of relative error with number of significant digits
set_numeric_precision(int digits)86     void set_numeric_precision(int digits) {
87         double relative_error = 0.5; // the error is half of last digit
88         while (digits > 0) {
89             relative_error /= 10;
90             digits--;
91         }
92         rel_error = relative_error;
93     }
94 
instance()95     static SvgOutputPrecisionWatcher &instance() {
96         static SvgOutputPrecisionWatcher _instance;
97         return _instance;
98     }
99 
100     std::atomic<double> rel_error; /// Cached relative error
101 };
102 
103 /// Returns absolute error of \a point as if serialized to svg with current preferences
serializing_error_of(const Geom::Point & point)104 double serializing_error_of(const Geom::Point &point) {
105     return SvgOutputPrecisionWatcher::error_of(point.length());
106 }
107 
108 /**
109  * @brief Returns true if three points are collinear within current serializing precision
110  *
111  * The algorithm of collinearity check is explicitly used to calculate the check error.
112  *
113  * This function can be sufficiently reduced or even removed completely if `Geom::are_collinear`
114  * would declare it's check algorithm as part of the public API.
115  *
116  * */
are_collinear_within_serializing_error(const Geom::Point & A,const Geom::Point & B,const Geom::Point & C)117 bool are_collinear_within_serializing_error(const Geom::Point &A, const Geom::Point &B, const Geom::Point &C) {
118     const double tolerance_factor = 10; // to account other factors which increase uncertainty
119     const double tolerance_A = serializing_error_of(A) * tolerance_factor;
120     const double tolerance_B = serializing_error_of(B) * tolerance_factor;
121     const double tolerance_C = serializing_error_of(C) * tolerance_factor;
122     const double CB_length = (B - C).length();
123     const double AB_length = (B - A).length();
124     Geom::Point C_reflect_scaled = B + (B - C) / CB_length * AB_length;
125     double tolerance_C_reflect_scaled = tolerance_B
126                                         + (tolerance_B + tolerance_C)
127                                           * (1 + (tolerance_A + tolerance_B) / AB_length)
128                                           * (1 + (tolerance_C + tolerance_B) / CB_length);
129     return Geom::are_near(C_reflect_scaled, A, tolerance_C_reflect_scaled + tolerance_A);
130 }
131 
132 } // namespace
133 
134 namespace Inkscape {
135 namespace UI {
136 
137 const double NO_POWER = 0.0;
138 const double DEFAULT_START_POWER = 1.0/3.0;
139 
140 ControlPoint::ColorSet Node::node_colors = {
141     {0xbfbfbf00, 0x000000ff}, // normal fill, stroke
142     {0xff000000, 0x000000ff}, // mouseover fill, stroke
143     {0xff000000, 0x000000ff}, // clicked fill, stroke
144     //
145     {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected
146     {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected
147     {0xff000000, 0x000000ff}  // clicked fill, stroke when selected
148 };
149 
150 ControlPoint::ColorSet Handle::_handle_colors = {
151     {0xffffffff, 0x000000ff}, // normal fill, stroke
152     {0xff000000, 0x000000ff}, // mouseover fill, stroke
153     {0xff000000, 0x000000ff}, // clicked fill, stroke
154     //
155     {0xffffffff, 0x000000ff}, // normal fill, stroke
156     {0xff000000, 0x000000ff}, // mouseover fill, stroke
157     {0xff000000, 0x000000ff}  // clicked fill, stroke
158 };
159 
operator <<(std::ostream & out,NodeType type)160 std::ostream &operator<<(std::ostream &out, NodeType type)
161 {
162     switch(type) {
163     case NODE_CUSP: out << 'c'; break;
164     case NODE_SMOOTH: out << 's'; break;
165     case NODE_AUTO: out << 'a'; break;
166     case NODE_SYMMETRIC: out << 'z'; break;
167     default: out << 'b'; break;
168     }
169     return out;
170 }
171 
172 /** Computes an unit vector of the direction from first to second control point */
direction(Geom::Point const & first,Geom::Point const & second)173 static Geom::Point direction(Geom::Point const &first, Geom::Point const &second) {
174     return Geom::unit_vector(second - first);
175 }
176 
177 Geom::Point Handle::_saved_other_pos(0, 0);
178 
179 double Handle::_saved_length = 0.0;
180 
181 bool Handle::_drag_out = false;
182 
Handle(NodeSharedData const & data,Geom::Point const & initial_pos,Node * parent)183 Handle::Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent)
184     : ControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER,
185                    Inkscape::CANVAS_ITEM_CTRL_TYPE_ROTATE,
186                    _handle_colors, data.handle_group)
187     , _handle_line(new Inkscape::CanvasItemCurve(data.handle_line_group))
188     , _parent(parent)
189     , _degenerate(true)
190 {
191     setVisible(false);
192 }
193 
~Handle()194 Handle::~Handle()
195 {
196     delete _handle_line;
197 }
198 
setVisible(bool v)199 void Handle::setVisible(bool v)
200 {
201     ControlPoint::setVisible(v);
202     if (v) {
203         _handle_line->show();
204     } else {
205         _handle_line->hide();
206     }
207 }
208 
move(Geom::Point const & new_pos)209 void Handle::move(Geom::Point const &new_pos)
210 {
211     Handle *other = this->other();
212     Node *node_towards = _parent->nodeToward(this); // node in direction of this handle
213     Node *node_away = _parent->nodeAwayFrom(this); // node in the opposite direction
214     Handle *towards = node_towards ? node_towards->handleAwayFrom(_parent) : nullptr;
215     Handle *towards_second = node_towards ? node_towards->handleToward(_parent) : nullptr;
216     double bspline_weight = 0.0;
217 
218     if (Geom::are_near(new_pos, _parent->position())) {
219         // The handle becomes degenerate.
220         // Adjust node type as necessary.
221         if (other->isDegenerate()) {
222             // If both handles become degenerate, convert to parent cusp node
223             _parent->setType(NODE_CUSP, false);
224         } else {
225             // Only 1 handle becomes degenerate
226             switch (_parent->type()) {
227             case NODE_AUTO:
228             case NODE_SYMMETRIC:
229                 _parent->setType(NODE_SMOOTH, false);
230                 break;
231             default:
232                 // do nothing for other node types
233                 break;
234             }
235         }
236         // If the segment between the handle and the node in its direction becomes linear,
237         // and there are smooth nodes at its ends, make their handles collinear with the segment.
238         if (towards && towards_second->isDegenerate()) {
239             if (node_towards->type() == NODE_SMOOTH) {
240                 towards->setDirection(*_parent, *node_towards);
241             }
242             if (_parent->type() == NODE_SMOOTH) {
243                 other->setDirection(*node_towards, *_parent);
244             }
245         }
246         setPosition(new_pos);
247 
248         // move the handle and its opposite the same proportion
249         if(_pm()._isBSpline()){
250             setPosition(_pm()._bsplineHandleReposition(this, false));
251             bspline_weight = _pm()._bsplineHandlePosition(this, false);
252             this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight));
253         }
254         return;
255     }
256 
257     if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
258         // restrict movement to the line joining the nodes
259         Geom::Point direction = _parent->position() - node_away->position();
260         Geom::Point delta = new_pos - _parent->position();
261         // project the relative position on the direction line
262         Geom::Coord direction_length = Geom::L2sq(direction);
263         Geom::Point new_delta;
264         if (direction_length == 0) {
265             // joining line has zero length - any direction is okay, prevent division by zero
266             new_delta = delta;
267         } else {
268             new_delta = (Geom::dot(delta, direction) / direction_length) * direction;
269         }
270         setRelativePos(new_delta);
271 
272         // move the handle and its opposite the same proportion
273         if(_pm()._isBSpline()){
274             setPosition(_pm()._bsplineHandleReposition(this, false));
275             bspline_weight = _pm()._bsplineHandlePosition(this, false);
276             this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight));
277         }
278 
279         return;
280     }
281 
282     switch (_parent->type()) {
283     case NODE_AUTO:
284         _parent->setType(NODE_SMOOTH, false);
285         // fall through - auto nodes degrade into smooth nodes
286     case NODE_SMOOTH: {
287         // for smooth nodes, we need to rotate the opposite handle
288         // so that it's collinear with the dragged one, while conserving length.
289         other->setDirection(new_pos, *_parent);
290         } break;
291     case NODE_SYMMETRIC:
292         // for symmetric nodes, place the other handle on the opposite side
293         other->setRelativePos(-(new_pos - _parent->position()));
294         break;
295     default: break;
296     }
297     setPosition(new_pos);
298 
299     // move the handle and its opposite the same proportion
300     if(_pm()._isBSpline()){
301         setPosition(_pm()._bsplineHandleReposition(this, false));
302         bspline_weight = _pm()._bsplineHandlePosition(this, false);
303         this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), bspline_weight));
304     }
305     Inkscape::UI::Tools::sp_update_helperpath(_desktop);
306 }
307 
setPosition(Geom::Point const & p)308 void Handle::setPosition(Geom::Point const &p)
309 {
310     ControlPoint::setPosition(p);
311     _handle_line->set_coords(_parent->position(), position());
312 
313     // update degeneration info and visibility
314     if (Geom::are_near(position(), _parent->position()))
315         _degenerate = true;
316     else _degenerate = false;
317 
318     if (_parent->_handles_shown && _parent->visible() && !_degenerate) {
319         setVisible(true);
320     } else {
321         setVisible(false);
322     }
323 }
324 
setLength(double len)325 void Handle::setLength(double len)
326 {
327     if (isDegenerate()) return;
328     Geom::Point dir = Geom::unit_vector(relativePos());
329     setRelativePos(dir * len);
330 }
331 
retract()332 void Handle::retract()
333 {
334     move(_parent->position());
335 }
336 
setDirection(Geom::Point const & from,Geom::Point const & to)337 void Handle::setDirection(Geom::Point const &from, Geom::Point const &to)
338 {
339     setDirection(to - from);
340 }
341 
setDirection(Geom::Point const & dir)342 void Handle::setDirection(Geom::Point const &dir)
343 {
344     Geom::Point unitdir = Geom::unit_vector(dir);
345     setRelativePos(unitdir * length());
346 }
347 
348 /**
349  * See also: Node::node_type_to_localized_string(NodeType type)
350  */
handle_type_to_localized_string(NodeType type)351 char const *Handle::handle_type_to_localized_string(NodeType type)
352 {
353     switch(type) {
354     case NODE_CUSP:
355         return _("Corner node handle");
356     case NODE_SMOOTH:
357         return _("Smooth node handle");
358     case NODE_SYMMETRIC:
359         return _("Symmetric node handle");
360     case NODE_AUTO:
361         return _("Auto-smooth node handle");
362     default:
363         return "";
364     }
365 }
366 
_eventHandler(Inkscape::UI::Tools::ToolBase * event_context,GdkEvent * event)367 bool Handle::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event)
368 {
369     switch (event->type)
370     {
371     case GDK_KEY_PRESS:
372 
373         switch (shortcut_key(event->key))
374         {
375         case GDK_KEY_s:
376         case GDK_KEY_S:
377 
378             /* if Shift+S is pressed while hovering over a cusp node handle,
379                hold the handle in place; otherwise, process normally.
380                this handle is guaranteed not to be degenerate. */
381 
382             if (held_only_shift(event->key) && _parent->_type == NODE_CUSP) {
383 
384                 // make opposite handle collinear,
385                 // but preserve length, unless degenerate
386                 if (other()->isDegenerate())
387                     other()->setRelativePos(-relativePos());
388                 else
389                     other()->setDirection(-relativePos());
390                 _parent->setType(NODE_SMOOTH, false);
391 
392                 // update display
393                 _parent->_pm().update();
394 
395                 // update undo history
396                 _parent->_pm()._commit(_("Change node type"));
397 
398                 return true;
399             }
400             break;
401 
402         case GDK_KEY_y:
403         case GDK_KEY_Y:
404 
405             /* if Shift+Y is pressed while hovering over a cusp, smooth, or auto node handle,
406                hold the handle in place; otherwise, process normally.
407                this handle is guaranteed not to be degenerate. */
408 
409             if (held_only_shift(event->key) && (_parent->_type == NODE_CUSP ||
410                                                 _parent->_type == NODE_SMOOTH ||
411                                                 _parent->_type == NODE_AUTO)) {
412 
413                 // make opposite handle collinear, and of equal length
414                 other()->setRelativePos(-relativePos());
415                 _parent->setType(NODE_SYMMETRIC, false);
416 
417                 // update display
418                 _parent->_pm().update();
419 
420                 // update undo history
421                 _parent->_pm()._commit(_("Change node type"));
422 
423                 return true;
424             }
425             break;
426         }
427         break;
428 
429     case GDK_2BUTTON_PRESS:
430 
431         // double-click event to set the handles of a node
432         // to the position specified by DEFAULT_START_POWER
433         handle_2button_press();
434         break;
435     }
436 
437     return ControlPoint::_eventHandler(event_context, event);
438 }
439 
440 // this function moves the handle and its opposite to the position specified by DEFAULT_START_POWER
handle_2button_press()441 void Handle::handle_2button_press(){
442     if(_pm()._isBSpline()){
443         setPosition(_pm()._bsplineHandleReposition(this, DEFAULT_START_POWER));
444         this->other()->setPosition(_pm()._bsplineHandleReposition(this->other(), DEFAULT_START_POWER));
445         _pm().update();
446     }
447 }
448 
grabbed(GdkEventMotion *)449 bool Handle::grabbed(GdkEventMotion *)
450 {
451     _saved_other_pos = other()->position();
452     _saved_length = _drag_out ? 0 : length();
453     _pm()._handleGrabbed();
454     return false;
455 }
456 
dragged(Geom::Point & new_pos,GdkEventMotion * event)457 void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event)
458 {
459     Geom::Point parent_pos = _parent->position();
460     Geom::Point origin = _last_drag_origin();
461     SnapManager &sm = _desktop->namedview->snap_manager;
462     bool snap = held_shift(*event) ? false : sm.someSnapperMightSnap();
463     std::optional<Inkscape::Snapper::SnapConstraint> ctrl_constraint;
464 
465     // with Alt, preserve length
466     if (held_alt(*event)) {
467         new_pos = parent_pos + Geom::unit_vector(new_pos - parent_pos) * _saved_length;
468         snap = false;
469     }
470     // with Ctrl, constrain to M_PI/rotationsnapsperpi increments from vertical
471     // and the original position.
472     if (held_control(*event)) {
473         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
474         int snaps = 2 * prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
475 
476         // note: if snapping to the original position is only desired in the original
477         // direction of the handle, change to Ray instead of Line
478         Geom::Line original_line(parent_pos, origin);
479         Geom::Line perp_line(parent_pos, parent_pos + Geom::rot90(origin - parent_pos));
480         Geom::Point snap_pos = parent_pos + Geom::constrain_angle(
481             Geom::Point(0,0), new_pos - parent_pos, snaps, Geom::Point(1,0));
482         Geom::Point orig_pos = original_line.pointAt(original_line.nearestTime(new_pos));
483         Geom::Point perp_pos = perp_line.pointAt(perp_line.nearestTime(new_pos));
484 
485         Geom::Point result = snap_pos;
486         ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - snap_pos);
487         if (Geom::distance(orig_pos, new_pos) < Geom::distance(result, new_pos)) {
488             result = orig_pos;
489             ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - orig_pos);
490         }
491         if (Geom::distance(perp_pos, new_pos) < Geom::distance(result, new_pos)) {
492             result = perp_pos;
493             ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - perp_pos);
494         }
495         new_pos = result;
496         // move the handle and its opposite in X fixed positions depending on parameter "steps with control"
497         // by default in live BSpline
498         if(_pm()._isBSpline()){
499             setPosition(new_pos);
500             int steps = _pm()._bsplineGetSteps();
501             new_pos=_pm()._bsplineHandleReposition(this,ceilf(_pm()._bsplineHandlePosition(this, false)*steps)/steps);
502         }
503     }
504 
505     std::vector<Inkscape::SnapCandidatePoint> unselected;
506     // if the snap adjustment is activated and it is not BSpline
507     if (snap && !_pm()._isBSpline()) {
508         ControlPointSelection::Set &nodes = _parent->_selection.allPoints();
509         for (auto node : nodes) {
510             Node *n = static_cast<Node*>(node);
511             unselected.push_back(n->snapCandidatePoint());
512         }
513         sm.setupIgnoreSelection(_desktop, true, &unselected);
514 
515         Node *node_away = _parent->nodeAwayFrom(this);
516         if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
517             Inkscape::Snapper::SnapConstraint cl(_parent->position(),
518                 _parent->position() - node_away->position());
519             Inkscape::SnappedPoint p;
520             p = sm.constrainedSnap(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_NODE_HANDLE), cl);
521             new_pos = p.getPoint();
522         } else if (ctrl_constraint) {
523             // NOTE: this is subtly wrong.
524             // We should get all possible constraints and snap along them using
525             // multipleConstrainedSnaps, instead of first snapping to angle and then to objects
526             Inkscape::SnappedPoint p;
527             p = sm.constrainedSnap(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_NODE_HANDLE), *ctrl_constraint);
528             new_pos = p.getPoint();
529         } else {
530             sm.freeSnapReturnByRef(new_pos, SNAPSOURCE_NODE_HANDLE);
531         }
532         sm.unSetup();
533     }
534 
535 
536     // with Shift, if the node is cusp, rotate the other handle as well
537     if (_parent->type() == NODE_CUSP && !_drag_out) {
538         if (held_shift(*event)) {
539             Geom::Point other_relpos = _saved_other_pos - parent_pos;
540             other_relpos *= Geom::Rotate(Geom::angle_between(origin - parent_pos, new_pos - parent_pos));
541             other()->setRelativePos(other_relpos);
542         } else {
543             // restore the position
544             other()->setPosition(_saved_other_pos);
545         }
546     }
547     // if it is BSpline, but SHIFT or CONTROL are not pressed, fix it in the original position
548     if(_pm()._isBSpline() && !held_shift(*event) && !held_control(*event)){
549         new_pos=_last_drag_origin();
550     }
551     move(new_pos); // needed for correct update, even though it's redundant
552     _pm().update();
553 }
554 
ungrabbed(GdkEventButton * event)555 void Handle::ungrabbed(GdkEventButton *event)
556 {
557     // hide the handle if it's less than dragtolerance away from the node
558     // however, never do this for cancelled drag / broken grab
559     // TODO is this actually a good idea?
560     if (event) {
561         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
562         int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
563 
564         Geom::Point dist = _desktop->d2w(_parent->position()) - _desktop->d2w(position());
565         if (dist.length() <= drag_tolerance) {
566             move(_parent->position());
567         }
568     }
569 
570     // HACK: If the handle was dragged out, call parent's ungrabbed handler,
571     // so that transform handles reappear
572     if (_drag_out) {
573         _parent->ungrabbed(event);
574     }
575     _drag_out = false;
576 
577     _pm()._handleUngrabbed();
578 }
579 
clicked(GdkEventButton * event)580 bool Handle::clicked(GdkEventButton *event)
581 {
582     _pm()._handleClicked(this, event);
583     return true;
584 }
585 
other() const586 Handle const *Handle::other() const
587 {
588     return const_cast<Handle *>(this)->other();
589 }
590 
other()591 Handle *Handle::other()
592 {
593     if (this == &_parent->_front) {
594         return &_parent->_back;
595     } else {
596         return &_parent->_front;
597     }
598 }
599 
snap_increment_degrees()600 static double snap_increment_degrees() {
601     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
602     int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
603     return 180.0 / snaps;
604 }
605 
_getTip(unsigned state) const606 Glib::ustring Handle::_getTip(unsigned state) const
607 {
608     /* a trick to mark as BSpline if the node has no strength;
609        we are going to use it later to show the appropriate messages.
610        we cannot do it in any different way because the function is constant. */
611     Handle *h = const_cast<Handle *>(this);
612     bool isBSpline = _pm()._isBSpline();
613     bool can_shift_rotate = _parent->type() == NODE_CUSP && !other()->isDegenerate();
614     Glib::ustring s = C_("Path handle tip",
615                          "node control handle");   // not expected
616 
617     if (state_held_alt(state) && !isBSpline) {
618         if (state_held_control(state)) {
619             if (state_held_shift(state) && can_shift_rotate) {
620                 s = format_tip(C_("Path handle tip",
621                     "<b>Shift+Ctrl+Alt</b>: "
622                     "preserve length and snap rotation angle to %g° increments, "
623                     "and rotate both handles"),
624                     snap_increment_degrees());
625             }
626             else {
627                 s = format_tip(C_("Path handle tip",
628                     "<b>Ctrl+Alt</b>: "
629                     "preserve length and snap rotation angle to %g° increments"),
630                     snap_increment_degrees());
631             }
632         }
633         else {
634             if (state_held_shift(state) && can_shift_rotate) {
635                 s = C_("Path handle tip",
636                     "<b>Shift+Alt</b>: preserve handle length and rotate both handles");
637             }
638             else {
639                 s = C_("Path handle tip",
640                     "<b>Alt</b>: preserve handle length while dragging");
641             }
642         }
643     }
644     else {
645         if (state_held_control(state)) {
646             if (state_held_shift(state) && can_shift_rotate && !isBSpline) {
647                 s = format_tip(C_("Path handle tip",
648                     "<b>Shift+Ctrl</b>: "
649                     "snap rotation angle to %g° increments, and rotate both handles"),
650                     snap_increment_degrees());
651             }
652             else if (isBSpline) {
653                 s = C_("Path handle tip",
654                     "<b>Ctrl</b>: "
655                     "Snap handle to steps defined in BSpline Live Path Effect");
656             }
657             else {
658                 s = format_tip(C_("Path handle tip",
659                     "<b>Ctrl</b>: "
660                     "snap rotation angle to %g° increments, click to retract"),
661                     snap_increment_degrees());
662             }
663         }
664         else if (state_held_shift(state) && can_shift_rotate && !isBSpline) {
665             s = C_("Path handle tip",
666                 "<b>Shift</b>: rotate both handles by the same angle");
667         }
668         else if (state_held_shift(state) && isBSpline) {
669             s = C_("Path handle tip",
670                 "<b>Shift</b>: move handle");
671         }
672         else {
673             char const *handletype = handle_type_to_localized_string(_parent->_type);
674             char const *more;
675 
676             if (can_shift_rotate && !isBSpline) {
677                 more = C_("Path handle tip",
678                           "Shift, Ctrl, Alt");
679             }
680             else if (isBSpline) {
681                 more = C_("Path handle tip",
682                           "Ctrl");
683             }
684             else {
685                 more = C_("Path handle tip",
686                           "Ctrl, Alt");
687             }
688 
689             if (_parent->type() == NODE_CUSP) {
690                 s = format_tip(C_("Path handle tip",
691                                   "<b>%s</b>: "
692                                   "drag to shape the path"  ", "
693                                   "hover to lock"  ", "
694                                   "Shift+S to make smooth"    ", "
695                                   "Shift+Y to make symmetric" ". "
696                                   "(more: %s)"),
697                                handletype, more);
698             }
699             else if (_parent->type() == NODE_SMOOTH) {
700                 s = format_tip(C_("Path handle tip",
701                                   "<b>%s</b>: "
702                                   "drag to shape the path"  ", "
703                                   "hover to lock"  ", "
704                                   "Shift+Y to make symmetric" ". "
705                                   "(more: %s)"),
706                                handletype, more);
707             }
708             else if (_parent->type() == NODE_AUTO) {
709                 s = format_tip(C_("Path handle tip",
710                                   "<b>%s</b>: "
711                                   "drag to make smooth, "
712                                   "hover to lock"  ", "
713                                   "Shift+Y to make symmetric" ". "
714                                   "(more: %s)"),
715                                handletype, more);
716             }
717             else if (_parent->type() == NODE_SYMMETRIC) {
718                 s = format_tip(C_("Path handle tip",
719                                   "<b>%s</b>: "
720                                   "drag to shape the path" ". "
721                                   "(more: %s)"),
722                                handletype, more);
723             }
724             else if (isBSpline) {
725                 double power = _pm()._bsplineHandlePosition(h);
726                 s = format_tip(C_("Path handle tip",
727                                   "<b>BSpline node handle</b> (%.3g power): "
728                                   "Shift-drag to move, "
729                                   "double-click to reset. "
730                                   "(more: %s)"),
731                                power, more);
732             }
733             else {
734                 s = C_("Path handle tip",
735                        "<b>unknown node handle</b>");   // not expected
736             }
737         }
738     }
739 
740     return (s);
741 }
742 
_getDragTip(GdkEventMotion *) const743 Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/) const
744 {
745     Geom::Point dist = position() - _last_drag_origin();
746     // report angle in mathematical convention
747     double angle = Geom::angle_between(Geom::Point(-1,0), position() - _parent->position());
748     angle += M_PI; // angle is (-M_PI...M_PI] - offset by +pi and scale to 0...360
749     angle *= 360.0 / (2 * M_PI);
750 
751     Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(dist[Geom::X], "px");
752     Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(dist[Geom::Y], "px");
753     Inkscape::Util::Quantity len_q = Inkscape::Util::Quantity(length(), "px");
754     Glib::ustring x = x_q.string(_desktop->namedview->display_units);
755     Glib::ustring y = y_q.string(_desktop->namedview->display_units);
756     Glib::ustring len = len_q.string(_desktop->namedview->display_units);
757     Glib::ustring ret = format_tip(C_("Path handle tip",
758         "Move handle by %s, %s; angle %.2f°, length %s"), x.c_str(), y.c_str(), angle, len.c_str());
759     return ret;
760 }
761 
Node(NodeSharedData const & data,Geom::Point const & initial_pos)762 Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos) :
763     SelectableControlPoint(data.desktop, initial_pos, SP_ANCHOR_CENTER,
764                            Inkscape::CANVAS_ITEM_CTRL_TYPE_NODE_CUSP,
765                            *data.selection,
766                            node_colors, data.node_group),
767     _front(data, initial_pos, this),
768     _back(data, initial_pos, this),
769     _type(NODE_CUSP),
770     _handles_shown(false)
771 {
772     _canvas_item_ctrl->set_name("CanvasItemCtrl:Node");
773     // NOTE we do not set type here, because the handles are still degenerate
774 }
775 
_next() const776 Node const *Node::_next() const
777 {
778     return const_cast<Node*>(this)->_next();
779 }
780 
781 // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined.
_next()782 Node *Node::_next()
783 {
784     NodeList::iterator n = NodeList::get_iterator(this).next();
785     if (n) {
786         return n.ptr();
787     } else {
788         return nullptr;
789     }
790 }
791 
_prev() const792 Node const *Node::_prev() const
793 {
794     return const_cast<Node *>(this)->_prev();
795 }
796 
_prev()797 Node *Node::_prev()
798 {
799     NodeList::iterator p = NodeList::get_iterator(this).prev();
800     if (p) {
801         return p.ptr();
802     } else {
803         return nullptr;
804     }
805 }
806 
move(Geom::Point const & new_pos)807 void Node::move(Geom::Point const &new_pos)
808 {
809     // move handles when the node moves.
810     Geom::Point old_pos = position();
811     Geom::Point delta = new_pos - position();
812 
813     // save the previous nodes strength to apply it again once the node is moved
814     double nodeWeight = NO_POWER;
815     double nextNodeWeight = NO_POWER;
816     double prevNodeWeight = NO_POWER;
817     Node *n = this;
818     Node * nextNode = n->nodeToward(n->front());
819     Node * prevNode = n->nodeToward(n->back());
820     nodeWeight = fmax(_pm()._bsplineHandlePosition(n->front(), false),_pm()._bsplineHandlePosition(n->back(), false));
821     if(prevNode){
822         prevNodeWeight = _pm()._bsplineHandlePosition(prevNode->front());
823     }
824     if(nextNode){
825         nextNodeWeight = _pm()._bsplineHandlePosition(nextNode->back());
826     }
827 
828     setPosition(new_pos);
829 
830     _front.setPosition(_front.position() + delta);
831     _back.setPosition(_back.position() + delta);
832 
833     // if the node has a smooth handle after a line segment, it should be kept collinear
834     // with the segment
835     _fixNeighbors(old_pos, new_pos);
836 
837     // move the affected handles. First the node ones, later the adjoining ones.
838     if(_pm()._isBSpline()){
839         _front.setPosition(_pm()._bsplineHandleReposition(this->front(),nodeWeight));
840         _back.setPosition(_pm()._bsplineHandleReposition(this->back(),nodeWeight));
841         if(prevNode){
842             prevNode->front()->setPosition(_pm()._bsplineHandleReposition(prevNode->front(), prevNodeWeight));
843         }
844         if(nextNode){
845             nextNode->back()->setPosition(_pm()._bsplineHandleReposition(nextNode->back(), nextNodeWeight));
846         }
847     }
848     Inkscape::UI::Tools::sp_update_helperpath(_desktop);
849 }
850 
transform(Geom::Affine const & m)851 void Node::transform(Geom::Affine const &m)
852 {
853 
854     Geom::Point old_pos = position();
855 
856     // save the previous nodes strength to apply it again once the node is moved
857     double nodeWeight = NO_POWER;
858     double nextNodeWeight = NO_POWER;
859     double prevNodeWeight = NO_POWER;
860     Node *n = this;
861     Node * nextNode = n->nodeToward(n->front());
862     Node * prevNode = n->nodeToward(n->back());
863     nodeWeight = _pm()._bsplineHandlePosition(n->front());
864     if(prevNode){
865         prevNodeWeight = _pm()._bsplineHandlePosition(prevNode->front());
866     }
867     if(nextNode){
868         nextNodeWeight = _pm()._bsplineHandlePosition(nextNode->back());
869     }
870 
871     setPosition(position() * m);
872     _front.setPosition(_front.position() * m);
873     _back.setPosition(_back.position() * m);
874 
875     /* Affine transforms keep handle invariants for smooth and symmetric nodes,
876      * but smooth nodes at ends of linear segments and auto nodes need special treatment */
877     _fixNeighbors(old_pos, position());
878 
879     // move the involved handles. First the node ones, later the adjoining ones.
880     if(_pm()._isBSpline()){
881         _front.setPosition(_pm()._bsplineHandleReposition(this->front(), nodeWeight));
882         _back.setPosition(_pm()._bsplineHandleReposition(this->back(), nodeWeight));
883         if(prevNode){
884             prevNode->front()->setPosition(_pm()._bsplineHandleReposition(prevNode->front(), prevNodeWeight));
885         }
886         if(nextNode){
887             nextNode->back()->setPosition(_pm()._bsplineHandleReposition(nextNode->back(), nextNodeWeight));
888         }
889     }
890 }
891 
bounds() const892 Geom::Rect Node::bounds() const
893 {
894     Geom::Rect b(position(), position());
895     b.expandTo(_front.position());
896     b.expandTo(_back.position());
897     return b;
898 }
899 
_fixNeighbors(Geom::Point const & old_pos,Geom::Point const & new_pos)900 void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos)
901 {
902     // This method restores handle invariants for neighboring nodes,
903     // and invariants that are based on positions of those nodes for this one.
904 
905     // Fix auto handles
906     if (_type == NODE_AUTO) _updateAutoHandles();
907     if (old_pos != new_pos) {
908         if (_next() && _next()->_type == NODE_AUTO) _next()->_updateAutoHandles();
909         if (_prev() && _prev()->_type == NODE_AUTO) _prev()->_updateAutoHandles();
910     }
911 
912     /* Fix smooth handles at the ends of linear segments.
913        Rotate the appropriate handle to be collinear with the segment.
914        If there is a smooth node at the other end of the segment, rotate it too. */
915     Handle *handle, *other_handle;
916     Node *other;
917     if (_is_line_segment(this, _next())) {
918         handle = &_back;
919         other = _next();
920         other_handle = &_next()->_front;
921     } else if (_is_line_segment(_prev(), this)) {
922         handle = &_front;
923         other = _prev();
924         other_handle = &_prev()->_back;
925     } else return;
926 
927     if (_type == NODE_SMOOTH && !handle->isDegenerate()) {
928         handle->setDirection(other->position(), new_pos);
929     }
930     // also update the handle on the other end of the segment
931     if (other->_type == NODE_SMOOTH && !other_handle->isDegenerate()) {
932         other_handle->setDirection(new_pos, other->position());
933     }
934 }
935 
_updateAutoHandles()936 void Node::_updateAutoHandles()
937 {
938     // Recompute the position of automatic handles. For endnodes, retract both handles.
939     // (It's only possible to create an end auto node through the XML editor.)
940     if (isEndNode()) {
941         _front.retract();
942         _back.retract();
943         return;
944     }
945 
946     // auto nodes automatically adjust their handles to give
947     // an appearance of smoothness, no matter what their surroundings are.
948     Geom::Point vec_next = _next()->position() - position();
949     Geom::Point vec_prev = _prev()->position() - position();
950     double len_next = vec_next.length(), len_prev = vec_prev.length();
951     if (len_next > 0 && len_prev > 0) {
952         // "dir" is an unit vector perpendicular to the bisector of the angle created
953         // by the previous node, this auto node and the next node.
954         Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
955         // Handle lengths are equal to 1/3 of the distance from the adjacent node.
956         _back.setRelativePos(-dir * (len_prev / 3));
957         _front.setRelativePos(dir * (len_next / 3));
958     } else {
959         // If any of the adjacent nodes coincides, retract both handles.
960         _front.retract();
961         _back.retract();
962     }
963 }
964 
showHandles(bool v)965 void Node::showHandles(bool v)
966 {
967     _handles_shown = v;
968     if (!_front.isDegenerate()) {
969         _front.setVisible(v);
970     }
971     if (!_back.isDegenerate()) {
972         _back.setVisible(v);
973     }
974 
975 }
976 
updateHandles()977 void Node::updateHandles()
978 {
979     _handleControlStyling();
980 
981     _front._handleControlStyling();
982     _back._handleControlStyling();
983 }
984 
985 
setType(NodeType type,bool update_handles)986 void Node::setType(NodeType type, bool update_handles)
987 {
988     if (type == NODE_PICK_BEST) {
989         pickBestType();
990         updateState(); // The size of the control might have changed
991         return;
992     }
993 
994     // if update_handles is true, adjust handle positions to match the node type
995     // handle degenerate handles appropriately
996     if (update_handles) {
997         switch (type) {
998         case NODE_CUSP:
999             // nothing to do
1000             break;
1001         case NODE_AUTO:
1002             // auto handles make no sense for endnodes
1003             if (isEndNode()) return;
1004             _updateAutoHandles();
1005             break;
1006         case NODE_SMOOTH: {
1007             // ignore attempts to make smooth endnodes.
1008             if (isEndNode()) return;
1009             // rotate handles to be collinear
1010             // for degenerate nodes set positions like auto handles
1011             bool prev_line = _is_line_segment(_prev(), this);
1012             bool next_line = _is_line_segment(this, _next());
1013             if (_type == NODE_SMOOTH) {
1014                 // For a node that is already smooth and has a degenerate handle,
1015                 // drag out the second handle without changing the direction of the first one.
1016                 if (_front.isDegenerate()) {
1017                     double dist = Geom::distance(_next()->position(), position());
1018                     _front.setRelativePos(Geom::unit_vector(-_back.relativePos()) * dist / 3);
1019                 }
1020                 if (_back.isDegenerate()) {
1021                     double dist = Geom::distance(_prev()->position(), position());
1022                     _back.setRelativePos(Geom::unit_vector(-_front.relativePos()) * dist / 3);
1023                 }
1024             } else if (isDegenerate()) {
1025                 _updateAutoHandles();
1026             } else if (_front.isDegenerate()) {
1027                 // if the front handle is degenerate and next path segment is a line, make back collinear;
1028                 // otherwise, pull out the other handle to 1/3 of distance to prev.
1029                 if (next_line) {
1030                     _back.setDirection(*_next(), *this);
1031                 } else if (_prev()) {
1032                     Geom::Point dir = direction(_back, *this);
1033                     _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir);
1034                 }
1035             } else if (_back.isDegenerate()) {
1036                 if (prev_line) {
1037                     _front.setDirection(*_prev(), *this);
1038                 } else if (_next()) {
1039                     Geom::Point dir = direction(_front, *this);
1040                     _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir);
1041                 }
1042             } else {
1043                 /* both handles are extended. make collinear while keeping length.
1044                    first make back collinear with the vector front ---> back,
1045                    then make front collinear with back ---> node.
1046                    (not back ---> front, because back's position was changed in the first call) */
1047                 _back.setDirection(_front, _back);
1048                 _front.setDirection(_back, *this);
1049             }
1050             } break;
1051         case NODE_SYMMETRIC:
1052             if (isEndNode()) return; // symmetric handles make no sense for endnodes
1053             if (isDegenerate()) {
1054                 // similar to auto handles but set the same length for both
1055                 Geom::Point vec_next = _next()->position() - position();
1056                 Geom::Point vec_prev = _prev()->position() - position();
1057                 double len_next = vec_next.length(), len_prev = vec_prev.length();
1058                 double len = (len_next + len_prev) / 6; // take 1/3 of average
1059                 if (len == 0) return;
1060 
1061                 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
1062                 _back.setRelativePos(-dir * len);
1063                 _front.setRelativePos(dir * len);
1064             } else {
1065                 // Both handles are extended. Compute average length, use direction from
1066                 // back handle to front handle. This also works correctly for degenerates
1067                 double len = (_front.length() + _back.length()) / 2;
1068                 Geom::Point dir = direction(_back, _front);
1069                 _front.setRelativePos(dir * len);
1070                 _back.setRelativePos(-dir * len);
1071             }
1072             break;
1073         default: break;
1074         }
1075         // in node type changes, for BSpline traces, we can either maintain them
1076         // with NO_POWER power in border mode, or give them the default power in curve mode.
1077         if(_pm()._isBSpline()){
1078             double weight = NO_POWER;
1079             if(_pm()._bsplineHandlePosition(this->front()) != NO_POWER ){
1080                 weight = DEFAULT_START_POWER;
1081             }
1082             _front.setPosition(_pm()._bsplineHandleReposition(this->front(), weight));
1083             _back.setPosition(_pm()._bsplineHandleReposition(this->back(), weight));
1084         }
1085     }
1086     _type = type;
1087     _setControlType(nodeTypeToCtrlType(_type));
1088     updateState();
1089 }
1090 
pickBestType()1091 void Node::pickBestType()
1092 {
1093     _type = NODE_CUSP;
1094     bool front_degen = _front.isDegenerate();
1095     bool back_degen = _back.isDegenerate();
1096     bool both_degen = front_degen && back_degen;
1097     bool neither_degen = !front_degen && !back_degen;
1098     do {
1099         // if both handles are degenerate, do nothing
1100         if (both_degen) break;
1101         // if neither are degenerate, check their respective positions
1102         if (neither_degen) {
1103             // for now do not automatically make nodes symmetric, it can be annoying
1104             /*if (Geom::are_near(front_delta, -back_delta)) {
1105                 _type = NODE_SYMMETRIC;
1106                 break;
1107             }*/
1108             if (are_collinear_within_serializing_error(_front.position(), position(), _back.position())) {
1109                 _type = NODE_SMOOTH;
1110                 break;
1111             }
1112         }
1113         // check whether the handle aligns with the previous line segment.
1114         // we know that if front is degenerate, back isn't, because
1115         // both_degen was false
1116         if (front_degen && _next() && _next()->_back.isDegenerate()) {
1117             if (are_collinear_within_serializing_error(_next()->position(), position(), _back.position())) {
1118                 _type = NODE_SMOOTH;
1119                 break;
1120             }
1121         } else if (back_degen && _prev() && _prev()->_front.isDegenerate()) {
1122             if (are_collinear_within_serializing_error(_prev()->position(), position(), _front.position())) {
1123                 _type = NODE_SMOOTH;
1124                 break;
1125             }
1126         }
1127     } while (false);
1128     _setControlType(nodeTypeToCtrlType(_type));
1129     updateState();
1130 }
1131 
isEndNode() const1132 bool Node::isEndNode() const
1133 {
1134     return !_prev() || !_next();
1135 }
1136 
sink()1137 void Node::sink()
1138 {
1139     _canvas_item_ctrl->set_z_position(0);
1140 }
1141 
parse_nodetype(char x)1142 NodeType Node::parse_nodetype(char x)
1143 {
1144     switch (x) {
1145     case 'a': return NODE_AUTO;
1146     case 'c': return NODE_CUSP;
1147     case 's': return NODE_SMOOTH;
1148     case 'z': return NODE_SYMMETRIC;
1149     default: return NODE_PICK_BEST;
1150     }
1151 }
1152 
_eventHandler(Inkscape::UI::Tools::ToolBase * event_context,GdkEvent * event)1153 bool Node::_eventHandler(Inkscape::UI::Tools::ToolBase *event_context, GdkEvent *event)
1154 {
1155     int dir = 0;
1156 
1157     switch (event->type)
1158     {
1159     case GDK_SCROLL:
1160         if (event->scroll.direction == GDK_SCROLL_UP) {
1161             dir = 1;
1162         } else if (event->scroll.direction == GDK_SCROLL_DOWN) {
1163             dir = -1;
1164         } else if (event->scroll.direction == GDK_SCROLL_SMOOTH) {
1165             dir = event->scroll.delta_y > 0 ? -1 : 1;
1166         } else {
1167             break;
1168         }
1169         if (held_control(event->scroll)) {
1170             _linearGrow(dir);
1171         } else {
1172             _selection.spatialGrow(this, dir);
1173         }
1174         return true;
1175     case GDK_KEY_PRESS:
1176         switch (shortcut_key(event->key))
1177         {
1178         case GDK_KEY_Page_Up:
1179             dir = 1;
1180             break;
1181         case GDK_KEY_Page_Down:
1182             dir = -1;
1183             break;
1184         default: goto bail_out;
1185         }
1186 
1187         if (held_control(event->key)) {
1188             _linearGrow(dir);
1189         } else {
1190             _selection.spatialGrow(this, dir);
1191         }
1192         return true;
1193 
1194     default:
1195         break;
1196     }
1197 
1198     bail_out:
1199     return ControlPoint::_eventHandler(event_context, event);
1200 }
1201 
_linearGrow(int dir)1202 void Node::_linearGrow(int dir)
1203 {
1204     // Interestingly, we do not need any help from PathManipulator when doing linear grow.
1205     // First handle the trivial case of growing over an unselected node.
1206     if (!selected() && dir > 0) {
1207         _selection.insert(this);
1208         return;
1209     }
1210 
1211     NodeList::iterator this_iter = NodeList::get_iterator(this);
1212     NodeList::iterator fwd = this_iter, rev = this_iter;
1213     double distance_back = 0, distance_front = 0;
1214 
1215     // Linear grow is simple. We find the first unselected nodes in each direction
1216     // and compare the linear distances to them.
1217     if (dir > 0) {
1218         if (!selected()) {
1219             _selection.insert(this);
1220             return;
1221         }
1222 
1223         // find first unselected nodes on both sides
1224         while (fwd && fwd->selected()) {
1225             NodeList::iterator n = fwd.next();
1226             distance_front += Geom::bezier_length(*fwd, fwd->_front, n->_back, *n);
1227             fwd = n;
1228             if (fwd == this_iter)
1229                 // there is no unselected node in this cyclic subpath
1230                 return;
1231         }
1232         // do the same for the second direction. Do not check for equality with
1233         // this node, because there is at least one unselected node in the subpath,
1234         // so we are guaranteed to stop.
1235         while (rev && rev->selected()) {
1236             NodeList::iterator p = rev.prev();
1237             distance_back += Geom::bezier_length(*rev, rev->_back, p->_front, *p);
1238             rev = p;
1239         }
1240 
1241         NodeList::iterator t; // node to select
1242         if (fwd && rev) {
1243             if (distance_front <= distance_back) t = fwd;
1244             else t = rev;
1245         } else {
1246             if (fwd) t = fwd;
1247             if (rev) t = rev;
1248         }
1249         if (t) _selection.insert(t.ptr());
1250 
1251     // Linear shrink is more complicated. We need to find the farthest selected node.
1252     // This means we have to check the entire subpath. We go in the direction in which
1253     // the distance we traveled is lower. We do this until we run out of nodes (ends of path)
1254     // or the two iterators meet. On the way, we store the last selected node and its distance
1255     // in each direction (if any). At the end, we choose the one that is farther and deselect it.
1256     } else {
1257         // both iterators that store last selected nodes are initially empty
1258         NodeList::iterator last_fwd, last_rev;
1259         double last_distance_back = 0, last_distance_front = 0;
1260 
1261         while (rev || fwd) {
1262             if (fwd && (!rev || distance_front <= distance_back)) {
1263                 if (fwd->selected()) {
1264                     last_fwd = fwd;
1265                     last_distance_front = distance_front;
1266                 }
1267                 NodeList::iterator n = fwd.next();
1268                 if (n) distance_front += Geom::bezier_length(*fwd, fwd->_front, n->_back, *n);
1269                 fwd = n;
1270             } else if (rev && (!fwd || distance_front > distance_back)) {
1271                 if (rev->selected()) {
1272                     last_rev = rev;
1273                     last_distance_back = distance_back;
1274                 }
1275                 NodeList::iterator p = rev.prev();
1276                 if (p) distance_back += Geom::bezier_length(*rev, rev->_back, p->_front, *p);
1277                 rev = p;
1278             }
1279             // Check whether we walked the entire cyclic subpath.
1280             // This is initially true because both iterators start from this node,
1281             // so this check cannot go in the while condition.
1282             // When this happens, we need to check the last node, pointed to by the iterators.
1283             if (fwd && fwd == rev) {
1284                 if (!fwd->selected()) break;
1285                 NodeList::iterator fwdp = fwd.prev(), revn = rev.next();
1286                 double df = distance_front + Geom::bezier_length(*fwdp, fwdp->_front, fwd->_back, *fwd);
1287                 double db = distance_back + Geom::bezier_length(*revn, revn->_back, rev->_front, *rev);
1288                 if (df > db) {
1289                     last_fwd = fwd;
1290                     last_distance_front = df;
1291                 } else {
1292                     last_rev = rev;
1293                     last_distance_back = db;
1294                 }
1295                 break;
1296             }
1297         }
1298 
1299         NodeList::iterator t;
1300         if (last_fwd && last_rev) {
1301             if (last_distance_front >= last_distance_back) t = last_fwd;
1302             else t = last_rev;
1303         } else {
1304             if (last_fwd) t = last_fwd;
1305             if (last_rev) t = last_rev;
1306         }
1307         if (t) _selection.erase(t.ptr());
1308     }
1309 }
1310 
_setState(State state)1311 void Node::_setState(State state)
1312 {
1313     // change node size to match type and selection state
1314     _canvas_item_ctrl->set_size_extra(selected() ? 2 : 0);
1315     switch (state) {
1316         // These were used to set "active" and "prelight" flags but the flags weren't being used.
1317         case STATE_NORMAL:
1318         case STATE_MOUSEOVER:
1319             break;
1320         case STATE_CLICKED:
1321             // show the handles when selecting the nodes
1322             if(_pm()._isBSpline()){
1323                 this->front()->setPosition(_pm()._bsplineHandleReposition(this->front()));
1324                 this->back()->setPosition(_pm()._bsplineHandleReposition(this->back()));
1325             }
1326             break;
1327     }
1328     SelectableControlPoint::_setState(state);
1329 }
1330 
grabbed(GdkEventMotion * event)1331 bool Node::grabbed(GdkEventMotion *event)
1332 {
1333     if (SelectableControlPoint::grabbed(event)) {
1334         return true;
1335     }
1336 
1337     // Dragging out handles with Shift + drag on a node.
1338     if (!held_shift(*event)) {
1339         return false;
1340     }
1341 
1342     Geom::Point evp = event_point(*event);
1343     Geom::Point rel_evp = evp - _last_click_event_point();
1344 
1345     // This should work even if dragtolerance is zero and evp coincides with node position.
1346     double angle_next = HUGE_VAL;
1347     double angle_prev = HUGE_VAL;
1348     bool has_degenerate = false;
1349     // determine which handle to drag out based on degeneration and the direction of drag
1350     if (_front.isDegenerate() && _next()) {
1351         Geom::Point next_relpos = _desktop->d2w(_next()->position())
1352             - _desktop->d2w(position());
1353         angle_next = fabs(Geom::angle_between(rel_evp, next_relpos));
1354         has_degenerate = true;
1355     }
1356     if (_back.isDegenerate() && _prev()) {
1357         Geom::Point prev_relpos = _desktop->d2w(_prev()->position())
1358             - _desktop->d2w(position());
1359         angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos));
1360         has_degenerate = true;
1361     }
1362     if (!has_degenerate) {
1363         return false;
1364     }
1365 
1366     Handle *h = angle_next < angle_prev ? &_front : &_back;
1367 
1368     h->setPosition(_desktop->w2d(evp));
1369     h->setVisible(true);
1370     h->transferGrab(this, event);
1371     Handle::_drag_out = true;
1372     return true;
1373 }
1374 
dragged(Geom::Point & new_pos,GdkEventMotion * event)1375 void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event)
1376 {
1377     // For a note on how snapping is implemented in Inkscape, see snap.h.
1378     SnapManager &sm = _desktop->namedview->snap_manager;
1379     // even if we won't really snap, we might still call the one of the
1380     // constrainedSnap() methods to enforce the constraints, so we need
1381     // to setup the snapmanager anyway; this is also required for someSnapperMightSnap()
1382     sm.setup(_desktop);
1383 
1384     // do not snap when Shift is pressed
1385     bool snap = !held_shift(*event) && sm.someSnapperMightSnap();
1386 
1387     Inkscape::SnappedPoint sp;
1388     std::vector<Inkscape::SnapCandidatePoint> unselected;
1389     if (snap) {
1390         /* setup
1391          * TODO We are doing this every time a snap happens. It should once be done only once
1392          *      per drag - maybe in the grabbed handler?
1393          * TODO Unselected nodes vector must be valid during the snap run, because it is not
1394          *      copied. Fix this in snap.h and snap.cpp, then the above.
1395          * TODO Snapping to unselected segments of selected paths doesn't work yet. */
1396 
1397         // Build the list of unselected nodes.
1398         typedef ControlPointSelection::Set Set;
1399         Set &nodes = _selection.allPoints();
1400         for (auto node : nodes) {
1401             if (!node->selected()) {
1402                 Node *n = static_cast<Node*>(node);
1403                 Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType());
1404                 unselected.push_back(p);
1405             }
1406         }
1407         sm.unSetup();
1408         sm.setupIgnoreSelection(_desktop, true, &unselected);
1409     }
1410 
1411     // Snap candidate point for free snapping; this will consider snapping tangentially
1412     // and perpendicularly and therefore the origin or direction vector must be set
1413     Inkscape::SnapCandidatePoint scp_free(new_pos, _snapSourceType());
1414 
1415     std::optional<Geom::Point> front_point, back_point;
1416     Geom::Point origin = _last_drag_origin();
1417     Geom::Point dummy_cp;
1418     if (_front.isDegenerate()) {
1419         if (_is_line_segment(this, _next())) {
1420             front_point = _next()->position() - origin;
1421             if (_next()->selected()) {
1422                 dummy_cp = _next()->position() - position();
1423                 scp_free.addVector(dummy_cp);
1424             } else {
1425                 dummy_cp = _next()->position();
1426                 scp_free.addOrigin(dummy_cp);
1427             }
1428         }
1429     } else {
1430         front_point = _front.relativePos();
1431         scp_free.addVector(*front_point);
1432     }
1433     if (_back.isDegenerate()) {
1434         if (_is_line_segment(_prev(), this)) {
1435             back_point = _prev()->position() - origin;
1436             if (_prev()->selected()) {
1437                 dummy_cp = _prev()->position() - position();
1438                 scp_free.addVector(dummy_cp);
1439             } else {
1440                 dummy_cp = _prev()->position();
1441                 scp_free.addOrigin(dummy_cp);
1442             }
1443         }
1444     } else {
1445         back_point = _back.relativePos();
1446         scp_free.addVector(*back_point);
1447     }
1448 
1449     if (held_control(*event)) {
1450         // We're about to consider a constrained snap, which is already limited to 1D
1451         // Therefore tangential or perpendicular snapping will not be considered, and therefore
1452         // all calls above to scp_free.addVector() and scp_free.addOrigin() can be neglected
1453         std::vector<Inkscape::Snapper::SnapConstraint> constraints;
1454         if (held_alt(*event)) {
1455             // with Ctrl+Alt, constrain to handle lines
1456             // project the new position onto a handle line that is closer;
1457             // also snap to perpendiculars of handle lines
1458 
1459             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1460             int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
1461             double min_angle = M_PI / snaps;
1462 
1463             std::optional<Geom::Point> fperp_point, bperp_point;
1464             if (front_point) {
1465                 constraints.emplace_back(origin, *front_point);
1466                 fperp_point = Geom::rot90(*front_point);
1467             }
1468             if (back_point) {
1469                 constraints.emplace_back(origin, *back_point);
1470                 bperp_point = Geom::rot90(*back_point);
1471             }
1472             // perpendiculars only snap when they are further than snap increment away
1473             // from the second handle constraint
1474             if (fperp_point && (!back_point ||
1475                 (fabs(Geom::angle_between(*fperp_point, *back_point)) > min_angle &&
1476                  fabs(Geom::angle_between(*fperp_point, *back_point)) < M_PI - min_angle)))
1477             {
1478                 constraints.emplace_back(origin, *fperp_point);
1479             }
1480             if (bperp_point && (!front_point ||
1481                 (fabs(Geom::angle_between(*bperp_point, *front_point)) > min_angle &&
1482                  fabs(Geom::angle_between(*bperp_point, *front_point)) < M_PI - min_angle)))
1483             {
1484                 constraints.emplace_back(origin, *bperp_point);
1485             }
1486 
1487             sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event));
1488         } else {
1489             // with Ctrl, constrain to axes
1490             constraints.emplace_back(origin, Geom::Point(1, 0));
1491             constraints.emplace_back(origin, Geom::Point(0, 1));
1492             sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event));
1493         }
1494         new_pos = sp.getPoint();
1495     } else if (snap) {
1496         Inkscape::SnappedPoint sp = sm.freeSnap(scp_free);
1497         new_pos = sp.getPoint();
1498     }
1499 
1500     sm.unSetup();
1501 
1502     SelectableControlPoint::dragged(new_pos, event);
1503 }
1504 
clicked(GdkEventButton * event)1505 bool Node::clicked(GdkEventButton *event)
1506 {
1507     if(_pm()._nodeClicked(this, event))
1508         return true;
1509     return SelectableControlPoint::clicked(event);
1510 }
1511 
_snapSourceType() const1512 Inkscape::SnapSourceType Node::_snapSourceType() const
1513 {
1514     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1515         return SNAPSOURCE_NODE_SMOOTH;
1516     return SNAPSOURCE_NODE_CUSP;
1517 }
_snapTargetType() const1518 Inkscape::SnapTargetType Node::_snapTargetType() const
1519 {
1520     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1521         return SNAPTARGET_NODE_SMOOTH;
1522     return SNAPTARGET_NODE_CUSP;
1523 }
1524 
snapCandidatePoint()1525 Inkscape::SnapCandidatePoint Node::snapCandidatePoint()
1526 {
1527     return SnapCandidatePoint(position(), _snapSourceType(), _snapTargetType());
1528 }
1529 
handleToward(Node * to)1530 Handle *Node::handleToward(Node *to)
1531 {
1532     if (_next() == to) {
1533         return front();
1534     }
1535     if (_prev() == to) {
1536         return back();
1537     }
1538     g_error("Node::handleToward(): second node is not adjacent!");
1539     return nullptr;
1540 }
1541 
nodeToward(Handle * dir)1542 Node *Node::nodeToward(Handle *dir)
1543 {
1544     if (front() == dir) {
1545         return _next();
1546     }
1547     if (back() == dir) {
1548         return _prev();
1549     }
1550     g_error("Node::nodeToward(): handle is not a child of this node!");
1551     return nullptr;
1552 }
1553 
handleAwayFrom(Node * to)1554 Handle *Node::handleAwayFrom(Node *to)
1555 {
1556     if (_next() == to) {
1557         return back();
1558     }
1559     if (_prev() == to) {
1560         return front();
1561     }
1562     g_error("Node::handleAwayFrom(): second node is not adjacent!");
1563     return nullptr;
1564 }
1565 
nodeAwayFrom(Handle * h)1566 Node *Node::nodeAwayFrom(Handle *h)
1567 {
1568     if (front() == h) {
1569         return _prev();
1570     }
1571     if (back() == h) {
1572         return _next();
1573     }
1574     g_error("Node::nodeAwayFrom(): handle is not a child of this node!");
1575     return nullptr;
1576 }
1577 
_getTip(unsigned state) const1578 Glib::ustring Node::_getTip(unsigned state) const
1579 {
1580     bool isBSpline = _pm()._isBSpline();
1581     Handle *h = const_cast<Handle *>(&_front);
1582     Glib::ustring s = C_("Path node tip",
1583                          "node handle");   // not expected
1584 
1585     if (state_held_shift(state)) {
1586         bool can_drag_out = (_next() && _front.isDegenerate()) ||
1587                             (_prev() &&  _back.isDegenerate());
1588 
1589         if (can_drag_out) {
1590             /*if (state_held_control(state)) {
1591                 s = format_tip(C_("Path node tip",
1592                     "<b>Shift+Ctrl:</b> drag out a handle and snap its angle "
1593                     "to %f° increments"), snap_increment_degrees());
1594             }*/
1595             s = C_("Path node tip",
1596                 "<b>Shift</b>: drag out a handle, click to toggle selection");
1597         }
1598         else {
1599             s = C_("Path node tip",
1600                    "<b>Shift</b>: click to toggle selection");
1601         }
1602     }
1603 
1604     else if (state_held_control(state)) {
1605         if (state_held_alt(state)) {
1606             s = C_("Path node tip",
1607                    "<b>Ctrl+Alt</b>: move along handle lines, click to delete node");
1608         }
1609         else {
1610             s = C_("Path node tip",
1611             "<b>Ctrl</b>: move along axes, click to change node type");
1612         }
1613     }
1614 
1615     else if (state_held_alt(state)) {
1616         s = C_("Path node tip",
1617                "<b>Alt</b>: sculpt nodes");
1618     }
1619 
1620     else {   // No modifiers: assemble tip from node type
1621         char const *nodetype = node_type_to_localized_string(_type);
1622         double power = _pm()._bsplineHandlePosition(h);
1623 
1624         if (_selection.transformHandlesEnabled() && selected()) {
1625             if (_selection.size() == 1) {
1626                 if (!isBSpline) {
1627                     s = format_tip(C_("Path node tip",
1628                                       "<b>%s</b>: "
1629                                       "drag to shape the path" ". "
1630                                       "(more: Shift, Ctrl, Alt)"),
1631                                    nodetype);
1632                 }
1633                 else {
1634                     s = format_tip(C_("Path node tip",
1635                                       "<b>BSpline node</b> (%.3g power): "
1636                                       "drag to shape the path" ". "
1637                                       "(more: Shift, Ctrl, Alt)"),
1638                                    power);
1639                 }
1640             }
1641             else {
1642                 s = format_tip(C_("Path node tip",
1643                                   "<b>%s</b>: "
1644                                   "drag to shape the path"   ", "
1645                                   "click to toggle scale/rotation handles" ". "
1646                                   "(more: Shift, Ctrl, Alt)"),
1647                                nodetype);
1648             }
1649         }
1650         else if (!isBSpline) {
1651             s = format_tip(C_("Path node tip",
1652                               "<b>%s</b>: "
1653                               "drag to shape the path"   ", "
1654                               "click to select only this node" ". "
1655                               "(more: Shift, Ctrl, Alt)"),
1656                            nodetype);
1657         }
1658         else {
1659             s = format_tip(C_("Path node tip",
1660                               "<b>BSpline node</b> (%.3g power): "
1661                               "drag to shape the path"   ", "
1662                               "click to select only this node" ". "
1663                               "(more: Shift, Ctrl, Alt)"),
1664                            power);
1665         }
1666     }
1667 
1668     return (s);
1669 }
1670 
_getDragTip(GdkEventMotion *) const1671 Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/) const
1672 {
1673     Geom::Point dist = position() - _last_drag_origin();
1674 
1675     Inkscape::Util::Quantity x_q = Inkscape::Util::Quantity(dist[Geom::X], "px");
1676     Inkscape::Util::Quantity y_q = Inkscape::Util::Quantity(dist[Geom::Y], "px");
1677     Glib::ustring x = x_q.string(_desktop->namedview->display_units);
1678     Glib::ustring y = y_q.string(_desktop->namedview->display_units);
1679     Glib::ustring ret = format_tip(C_("Path node tip", "Move node by %s, %s"), x.c_str(), y.c_str());
1680     return ret;
1681 }
1682 
1683 /**
1684  * See also: Handle::handle_type_to_localized_string(NodeType type)
1685  */
node_type_to_localized_string(NodeType type)1686 char const *Node::node_type_to_localized_string(NodeType type)
1687 {
1688     switch (type) {
1689     case NODE_CUSP:
1690         return _("Corner node");
1691     case NODE_SMOOTH:
1692         return _("Smooth node");
1693     case NODE_SYMMETRIC:
1694         return _("Symmetric node");
1695     case NODE_AUTO:
1696         return _("Auto-smooth node");
1697     default:
1698         return "";
1699     }
1700 }
1701 
_is_line_segment(Node * first,Node * second)1702 bool Node::_is_line_segment(Node *first, Node *second)
1703 {
1704     if (!first || !second) return false;
1705     if (first->_next() == second)
1706         return first->_front.isDegenerate() && second->_back.isDegenerate();
1707     if (second->_next() == first)
1708         return second->_front.isDegenerate() && first->_back.isDegenerate();
1709     return false;
1710 }
1711 
NodeList(SubpathList & splist)1712 NodeList::NodeList(SubpathList &splist)
1713     : _list(splist)
1714     , _closed(false)
1715 {
1716     this->ln_list = this;
1717     this->ln_next = this;
1718     this->ln_prev = this;
1719 }
1720 
~NodeList()1721 NodeList::~NodeList()
1722 {
1723     clear();
1724 }
1725 
empty()1726 bool NodeList::empty()
1727 {
1728     return ln_next == this;
1729 }
1730 
size()1731 NodeList::size_type NodeList::size()
1732 {
1733     size_type sz = 0;
1734     for (ListNode *ln = ln_next; ln != this; ln = ln->ln_next) ++sz;
1735     return sz;
1736 }
1737 
closed()1738 bool NodeList::closed()
1739 {
1740     return _closed;
1741 }
1742 
degenerate()1743 bool NodeList::degenerate()
1744 {
1745     return closed() ? empty() : ++begin() == end();
1746 }
1747 
before(double t,double * fracpart)1748 NodeList::iterator NodeList::before(double t, double *fracpart)
1749 {
1750     double intpart;
1751     *fracpart = std::modf(t, &intpart);
1752     int index = intpart;
1753 
1754     iterator ret = begin();
1755     std::advance(ret, index);
1756     return ret;
1757 }
1758 
before(Geom::PathTime const & pvp)1759 NodeList::iterator NodeList::before(Geom::PathTime const &pvp)
1760 {
1761     iterator ret = begin();
1762     std::advance(ret, pvp.curve_index);
1763     return ret;
1764 }
1765 
insert(iterator pos,Node * x)1766 NodeList::iterator NodeList::insert(iterator pos, Node *x)
1767 {
1768     ListNode *ins = pos._node;
1769     x->ln_next = ins;
1770     x->ln_prev = ins->ln_prev;
1771     ins->ln_prev->ln_next = x;
1772     ins->ln_prev = x;
1773     x->ln_list = this;
1774     return iterator(x);
1775 }
1776 
splice(iterator pos,NodeList & list)1777 void NodeList::splice(iterator pos, NodeList &list)
1778 {
1779     splice(pos, list, list.begin(), list.end());
1780 }
1781 
splice(iterator pos,NodeList & list,iterator i)1782 void NodeList::splice(iterator pos, NodeList &list, iterator i)
1783 {
1784     NodeList::iterator j = i;
1785     ++j;
1786     splice(pos, list, i, j);
1787 }
1788 
splice(iterator pos,NodeList &,iterator first,iterator last)1789 void NodeList::splice(iterator pos, NodeList &/*list*/, iterator first, iterator last)
1790 {
1791     ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node;
1792     for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->ln_next) {
1793         ln->ln_list = this;
1794     }
1795     ins_beg->ln_prev->ln_next = ins_end;
1796     ins_end->ln_prev->ln_next = at;
1797     at->ln_prev->ln_next = ins_beg;
1798 
1799     ListNode *atprev = at->ln_prev;
1800     at->ln_prev = ins_end->ln_prev;
1801     ins_end->ln_prev = ins_beg->ln_prev;
1802     ins_beg->ln_prev = atprev;
1803 }
1804 
shift(int n)1805 void NodeList::shift(int n)
1806 {
1807     // 1. make the list perfectly cyclic
1808     ln_next->ln_prev = ln_prev;
1809     ln_prev->ln_next = ln_next;
1810     // 2. find new begin
1811     ListNode *new_begin = ln_next;
1812     if (n > 0) {
1813         for (; n > 0; --n) new_begin = new_begin->ln_next;
1814     } else {
1815         for (; n < 0; ++n) new_begin = new_begin->ln_prev;
1816     }
1817     // 3. relink begin to list
1818     ln_next = new_begin;
1819     ln_prev = new_begin->ln_prev;
1820     new_begin->ln_prev->ln_next = this;
1821     new_begin->ln_prev = this;
1822 }
1823 
reverse()1824 void NodeList::reverse()
1825 {
1826     for (ListNode *ln = ln_next; ln != this; ln = ln->ln_prev) {
1827         std::swap(ln->ln_next, ln->ln_prev);
1828         Node *node = static_cast<Node*>(ln);
1829         Geom::Point save_pos = node->front()->position();
1830         node->front()->setPosition(node->back()->position());
1831         node->back()->setPosition(save_pos);
1832     }
1833     std::swap(ln_next, ln_prev);
1834 }
1835 
clear()1836 void NodeList::clear()
1837 {
1838     // ugly but more efficient clearing mechanism
1839     std::vector<ControlPointSelection *> to_clear;
1840     std::vector<std::pair<SelectableControlPoint *, long> > nodes;
1841     long in = -1;
1842     for (iterator i = begin(); i != end(); ++i) {
1843         SelectableControlPoint *rm = static_cast<Node*>(i._node);
1844         if (std::find(to_clear.begin(), to_clear.end(), &rm->_selection) == to_clear.end()) {
1845             to_clear.push_back(&rm->_selection);
1846             ++in;
1847         }
1848         nodes.emplace_back(rm, in);
1849     }
1850     for (size_t i = 0, e = nodes.size(); i != e; ++i) {
1851         to_clear[nodes[i].second]->erase(nodes[i].first, false);
1852     }
1853     std::vector<std::vector<SelectableControlPoint *> > emission;
1854     for (long i = 0, e = to_clear.size(); i != e; ++i) {
1855         emission.emplace_back();
1856         for (size_t j = 0, f = nodes.size(); j != f; ++j) {
1857             if (nodes[j].second != i)
1858                 break;
1859             emission[i].push_back(nodes[j].first);
1860         }
1861     }
1862 
1863     for (size_t i = 0, e = emission.size(); i != e; ++i) {
1864         to_clear[i]->signal_selection_changed.emit(emission[i], false);
1865     }
1866 
1867     for (iterator i = begin(); i != end();)
1868         erase (i++);
1869 }
1870 
erase(iterator i)1871 NodeList::iterator NodeList::erase(iterator i)
1872 {
1873     // some gymnastics are required to ensure that the node is valid when deleted;
1874     // otherwise the code that updates handle visibility will break
1875     Node *rm = static_cast<Node*>(i._node);
1876     ListNode *rmnext = rm->ln_next, *rmprev = rm->ln_prev;
1877     ++i;
1878     delete rm;
1879     rmprev->ln_next = rmnext;
1880     rmnext->ln_prev = rmprev;
1881     return i;
1882 }
1883 
1884 // TODO this method is very ugly!
1885 // converting SubpathList to an intrusive list might allow us to get rid of it
kill()1886 void NodeList::kill()
1887 {
1888     for (SubpathList::iterator i = _list.begin(); i != _list.end(); ++i) {
1889         if (i->get() == this) {
1890             _list.erase(i);
1891             return;
1892         }
1893     }
1894 }
1895 
get(Node * n)1896 NodeList &NodeList::get(Node *n) {
1897     return n->nodeList();
1898 }
get(iterator const & i)1899 NodeList &NodeList::get(iterator const &i) {
1900     return *(i._node->ln_list);
1901 }
1902 
1903 
1904 } // namespace UI
1905 } // namespace Inkscape
1906 
1907 /*
1908   Local Variables:
1909   mode:c++
1910   c-file-style:"stroustrup"
1911   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1912   indent-tabs-mode:nil
1913   fill-column:99
1914   End:
1915 */
1916 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
1917