Code

Fix multiple minor problems in the node tool
[inkscape.git] / src / ui / tool / node.cpp
1 /** @file
2  * Editable node - 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 <iostream>
12 #include <stdexcept>
13 #include <boost/utility.hpp>
14 #include <glib.h>
15 #include <glib/gi18n.h>
16 #include <2geom/bezier-utils.h>
17 #include <2geom/transforms.h>
19 #include "display/sp-ctrlline.h"
20 #include "display/sp-canvas.h"
21 #include "display/sp-canvas-util.h"
22 #include "desktop.h"
23 #include "desktop-handles.h"
24 #include "preferences.h"
25 #include "snap.h"
26 #include "snap-preferences.h"
27 #include "sp-metrics.h"
28 #include "sp-namedview.h"
29 #include "ui/tool/control-point-selection.h"
30 #include "ui/tool/event-utils.h"
31 #include "ui/tool/multi-path-manipulator.h"
32 #include "ui/tool/node.h"
33 #include "ui/tool/path-manipulator.h"
35 namespace Inkscape {
36 namespace UI {
38 static SelectableControlPoint::ColorSet node_colors = {
39     {
40         {0xbfbfbf00, 0x000000ff}, // normal fill, stroke
41         {0xff000000, 0x000000ff}, // mouseover fill, stroke
42         {0xff000000, 0x000000ff}  // clicked fill, stroke
43     },
44     {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected
45     {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected
46     {0xff000000, 0x000000ff}  // clicked fill, stroke when selected
47 };
49 static ControlPoint::ColorSet handle_colors = {
50     {0xffffffff, 0x000000ff}, // normal fill, stroke
51     {0xff000000, 0x000000ff}, // mouseover fill, stroke
52     {0xff000000, 0x000000ff}  // clicked fill, stroke
53 };
55 std::ostream &operator<<(std::ostream &out, NodeType type)
56 {
57     switch(type) {
58     case NODE_CUSP: out << 'c'; break;
59     case NODE_SMOOTH: out << 's'; break;
60     case NODE_AUTO: out << 'a'; break;
61     case NODE_SYMMETRIC: out << 'z'; break;
62     default: out << 'b'; break;
63     }
64     return out;
65 }
67 /** Computes an unit vector of the direction from first to second control point */
68 static Geom::Point direction(Geom::Point const &first, Geom::Point const &second) {
69     return Geom::unit_vector(second - first);
70 }
72 /**
73  * @class Handle
74  * @brief Control point of a cubic Bezier curve in a path.
75  *
76  * Handle keeps the node type invariant only for the opposite handle of the same node.
77  * Keeping the invariant on node moves is left to the %Node class.
78  */
80 Geom::Point Handle::_saved_other_pos(0, 0);
81 double Handle::_saved_length = 0.0;
82 bool Handle::_drag_out = false;
84 Handle::Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent)
85     : ControlPoint(data.desktop, initial_pos, Gtk::ANCHOR_CENTER, SP_CTRL_SHAPE_CIRCLE, 7.0,
86         &handle_colors, data.handle_group)
87     , _parent(parent)
88     , _degenerate(true)
89 {
90     _cset = &handle_colors;
91     _handle_line = sp_canvas_item_new(data.handle_line_group, SP_TYPE_CTRLLINE, NULL);
92     setVisible(false);
93 }
94 Handle::~Handle()
95 {
96     //sp_canvas_item_hide(_handle_line);
97     gtk_object_destroy(GTK_OBJECT(_handle_line));
98 }
100 void Handle::setVisible(bool v)
102     ControlPoint::setVisible(v);
103     if (v) sp_canvas_item_show(_handle_line);
104     else sp_canvas_item_hide(_handle_line);
107 void Handle::move(Geom::Point const &new_pos)
109     Handle *other, *towards, *towards_second;
110     Node *node_towards; // node in direction of this handle
111     Node *node_away; // node in the opposite direction
112     if (this == &_parent->_front) {
113         other = &_parent->_back;
114         node_towards = _parent->_next();
115         node_away = _parent->_prev();
116         towards = node_towards ? &node_towards->_back : 0;
117         towards_second = node_towards ? &node_towards->_front : 0;
118     } else {
119         other = &_parent->_front;
120         node_towards = _parent->_prev();
121         node_away = _parent->_next();
122         towards = node_towards ? &node_towards->_front : 0;
123         towards_second = node_towards ? &node_towards->_back : 0;
124     }
126     if (Geom::are_near(new_pos, _parent->position())) {
127         // The handle becomes degenerate. If the segment between it and the node
128         // in its direction becomes linear and there are smooth nodes
129         // at its ends, make their handles colinear with the segment
130         if (towards && towards->isDegenerate()) {
131             if (node_towards->type() == NODE_SMOOTH) {
132                 towards_second->setDirection(*_parent, *node_towards);
133             }
134             if (_parent->type() == NODE_SMOOTH) {
135                 other->setDirection(*node_towards, *_parent);
136             }
137         }
138         setPosition(new_pos);
139         return;
140     }
142     if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
143         // restrict movement to the line joining the nodes
144         Geom::Point direction = _parent->position() - node_away->position();
145         Geom::Point delta = new_pos - _parent->position();
146         // project the relative position on the direction line
147         Geom::Point new_delta = (Geom::dot(delta, direction)
148             / Geom::L2sq(direction)) * direction;
149         setRelativePos(new_delta);
150         return;
151     }
153     switch (_parent->type()) {
154     case NODE_AUTO:
155         _parent->setType(NODE_SMOOTH, false);
156         // fall through - auto nodes degrade into smooth nodes
157     case NODE_SMOOTH: {
158         /* for smooth nodes, we need to rotate the other handle so that it's colinear
159          * with the dragged one while conserving length. */
160         other->setDirection(new_pos, *_parent);
161         } break;
162     case NODE_SYMMETRIC:
163         // for symmetric nodes, place the other handle on the opposite side
164         other->setRelativePos(-(new_pos - _parent->position()));
165         break;
166     default: break;
167     }
169     setPosition(new_pos);
172 void Handle::setPosition(Geom::Point const &p)
174     ControlPoint::setPosition(p);
175     sp_ctrlline_set_coords(SP_CTRLLINE(_handle_line), _parent->position(), position());
177     // update degeneration info and visibility
178     if (Geom::are_near(position(), _parent->position()))
179         _degenerate = true;
180     else _degenerate = false;
181     if (_parent->_handles_shown && _parent->visible() && !_degenerate) {
182         setVisible(true);
183     } else {
184         setVisible(false);
185     }
186     // If both handles become degenerate, convert to parent cusp node
187     if (_parent->isDegenerate()) {
188         _parent->setType(NODE_CUSP, false);
189     }
192 void Handle::setLength(double len)
194     if (isDegenerate()) return;
195     Geom::Point dir = Geom::unit_vector(relativePos());
196     setRelativePos(dir * len);
199 void Handle::retract()
201     setPosition(_parent->position());
204 void Handle::setDirection(Geom::Point const &from, Geom::Point const &to)
206     setDirection(to - from);
209 void Handle::setDirection(Geom::Point const &dir)
211     Geom::Point unitdir = Geom::unit_vector(dir);
212     setRelativePos(unitdir * length());
215 char const *Handle::handle_type_to_localized_string(NodeType type)
217     switch(type) {
218     case NODE_CUSP: return _("Cusp node handle");
219     case NODE_SMOOTH: return _("Smooth node handle");
220     case NODE_SYMMETRIC: return _("Symmetric node handle");
221     case NODE_AUTO: return _("Auto-smooth node handle");
222     default: return "";
223     }
226 bool Handle::grabbed(GdkEventMotion *)
228     _saved_other_pos = other().position();
229     _saved_length = _drag_out ? 0 : length();
230     _pm()._handleGrabbed();
231     return false;
234 void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event)
236     Geom::Point parent_pos = _parent->position();
237     Geom::Point origin = _last_drag_origin();
238     // with Alt, preserve length
239     if (held_alt(*event)) {
240         new_pos = parent_pos + Geom::unit_vector(new_pos - parent_pos) * _saved_length;
241     }
242     // with Ctrl, constrain to M_PI/rotationsnapsperpi increments from vertical
243     // and the original position.
244     if (held_control(*event)) {
245         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
246         int snaps = 2 * prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
248         // note: if snapping to the original position is only desired in the original
249         // direction of the handle, change 2nd line below to Ray instead of Line
250         Geom::Line original_line(parent_pos, origin);
251         Geom::Point snap_pos = parent_pos + Geom::constrain_angle(
252             Geom::Point(0,0), new_pos - parent_pos, snaps, Geom::Point(1,0));
253         Geom::Point orig_pos = original_line.pointAt(original_line.nearestPoint(new_pos));
255         if (Geom::distance(snap_pos, new_pos) < Geom::distance(orig_pos, new_pos)) {
256             new_pos = snap_pos;
257         } else {
258             new_pos = orig_pos;
259         }
260     }
261     // with Shift, if the node is cusp, rotate the other handle as well
262     if (_parent->type() == NODE_CUSP && !_drag_out) {
263         if (held_shift(*event)) {
264             Geom::Point other_relpos = _saved_other_pos - parent_pos;
265             other_relpos *= Geom::Rotate(Geom::angle_between(origin - parent_pos, new_pos - parent_pos));
266             other().setRelativePos(other_relpos);
267         } else {
268             // restore the position
269             other().setPosition(_saved_other_pos);
270         }
271     }
272     _pm().update();
275 void Handle::ungrabbed(GdkEventButton *event)
277     // hide the handle if it's less than dragtolerance away from the node
278     // TODO is this actually desired?
279     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
280     int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
282     Geom::Point dist = _desktop->d2w(_parent->position()) - _desktop->d2w(position());
283     if (dist.length() <= drag_tolerance) {
284         move(_parent->position());
285     }
287     // HACK: If the handle was dragged out, call parent's ungrabbed handler,
288     // so that transform handles reappear
289     if (_drag_out) {
290         _parent->ungrabbed(event);
291     }
292     _drag_out = false;
294     _pm()._handleUngrabbed();
297 bool Handle::clicked(GdkEventButton *event)
299     _pm()._handleClicked(this, event);
300     return true;
303 Handle &Handle::other()
305     if (this == &_parent->_front) return _parent->_back;
306     return _parent->_front;
309 static double snap_increment_degrees() {
310     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
311     int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
312     return 180.0 / snaps;
315 Glib::ustring Handle::_getTip(unsigned state)
317     char const *more;
318     bool can_shift_rotate = _parent->type() == NODE_CUSP && !other().isDegenerate();
319     if (can_shift_rotate) {
320         more = C_("Path handle tip", "more: Ctrl, Alt, Ctrl+Alt, Shift");
321     } else {
322         more = C_("Path handle tip", "more: Ctrl, Alt, Ctrl+Alt");
323     }
324     if (state_held_alt(state)) {
325         if (state_held_control(state)) {
326             if (state_held_shift(state) && can_shift_rotate) {
327                 return format_tip(C_("Path handle tip",
328                     "<b>Shift+Ctrl+Alt</b>: preserve length and snap rotation angle to %f° "
329                     "increments while rotating both handles"),
330                     snap_increment_degrees());
331             } else {
332                 return format_tip(C_("Path handle tip",
333                     "<b>Ctrl+Alt</b>: preserve length and snap rotation angle to %f° increments"),
334                     snap_increment_degrees());
335             }
336         } else {
337             if (state_held_shift(state) && can_shift_rotate) {
338                 return C_("Path handle tip",
339                     "<b>Shift+Alt:</b> preserve handle length and rotate both handles");
340             } else {
341                 return C_("Path handle tip",
342                     "<b>Alt:</b> preserve handle length while dragging");
343             }
344         }
345     } else {
346         if (state_held_control(state)) {
347             if (state_held_shift(state) && can_shift_rotate) {
348                 return format_tip(C_("Path handle tip",
349                     "<b>Ctrl:</b> snap rotation angle to %f° increments, click to retract"),
350                     snap_increment_degrees());
351             } else {
352                 return format_tip(C_("Path handle tip",
353                     "<b>Shift+Ctrl:</b> snap rotation angle to %f° increments and rotate both handles"),
354                     snap_increment_degrees());
355             }
356         } else if (state_held_shift(state) && can_shift_rotate) {
357             return C_("Path hande tip",
358                 "<b>Shift</b>: rotate both handles by the same angle");
359         }
360     }
362     switch (_parent->type()) {
363     case NODE_AUTO:
364         return format_tip(C_("Path handle tip",
365             "<b>Auto node handle:</b> drag to convert to smooth node (%s)"), more);
366     default:
367         return format_tip(C_("Path handle tip",
368             "<b>%s:</b> drag to shape the segment (%s)"),
369             handle_type_to_localized_string(_parent->type()), more);
370     }
373 Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/)
375     Geom::Point dist = position() - _last_drag_origin();
376     // report angle in mathematical convention
377     double angle = Geom::angle_between(Geom::Point(-1,0), position() - _parent->position());
378     angle += M_PI; // angle is (-M_PI...M_PI] - offset by +pi and scale to 0...360
379     angle *= 360.0 / (2 * M_PI);
380     GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
381     GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
382     GString *len = SP_PX_TO_METRIC_STRING(length(), _desktop->namedview->getDefaultMetric());
383     Glib::ustring ret = format_tip(C_("Path handle tip",
384         "Move by %s, %s; angle %.2f°, length %s"), x->str, y->str, angle, len->str);
385     g_string_free(x, TRUE);
386     g_string_free(y, TRUE);
387     g_string_free(len, TRUE);
388     return ret;
391 /**
392  * @class Node
393  * @brief Curve endpoint in an editable path.
394  *
395  * The method move() keeps node type invariants during translations.
396  */
398 Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos)
399     : SelectableControlPoint(data.desktop, initial_pos, Gtk::ANCHOR_CENTER,
400         SP_CTRL_SHAPE_DIAMOND, 9.0, *data.selection, &node_colors, data.node_group)
401     , _front(data, initial_pos, this)
402     , _back(data, initial_pos, this)
403     , _type(NODE_CUSP)
404     , _handles_shown(false)
406     // NOTE we do not set type here, because the handles are still degenerate
409 // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined.
410 Node *Node::_next()
412     NodeList::iterator n = NodeList::get_iterator(this).next();
413     if (n) return n.ptr();
414     return NULL;
416 Node *Node::_prev()
418     NodeList::iterator p = NodeList::get_iterator(this).prev();
419     if (p) return p.ptr();
420     return NULL;
423 void Node::move(Geom::Point const &new_pos)
425     // move handles when the node moves.
426     Geom::Point old_pos = position();
427     Geom::Point delta = new_pos - position();
428     setPosition(new_pos);
429     _front.setPosition(_front.position() + delta);
430     _back.setPosition(_back.position() + delta);
432     // if the node has a smooth handle after a line segment, it should be kept colinear
433     // with the segment
434     _fixNeighbors(old_pos, new_pos);
437 void Node::transform(Geom::Matrix const &m)
439     Geom::Point old_pos = position();
440     setPosition(position() * m);
441     _front.setPosition(_front.position() * m);
442     _back.setPosition(_back.position() * m);
444     /* Affine transforms keep handle invariants for smooth and symmetric nodes,
445      * but smooth nodes at ends of linear segments and auto nodes need special treatment */
446     _fixNeighbors(old_pos, position());
449 Geom::Rect Node::bounds()
451     Geom::Rect b(position(), position());
452     b.expandTo(_front.position());
453     b.expandTo(_back.position());
454     return b;
457 void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos)
459     /* This method restores handle invariants for neighboring nodes,
460      * and invariants that are based on positions of those nodes for this one. */
462     /* Fix auto handles */
463     if (_type == NODE_AUTO) _updateAutoHandles();
464     if (old_pos != new_pos) {
465         if (_next() && _next()->_type == NODE_AUTO) _next()->_updateAutoHandles();
466         if (_prev() && _prev()->_type == NODE_AUTO) _prev()->_updateAutoHandles();
467     }
469     /* Fix smooth handles at the ends of linear segments.
470      * Rotate the appropriate handle to be colinear with the segment.
471      * If there is a smooth node at the other end of the segment, rotate it too. */
472     Handle *handle, *other_handle;
473     Node *other;
474     if (_is_line_segment(this, _next())) {
475         handle = &_back;
476         other = _next();
477         other_handle = &_next()->_front;
478     } else if (_is_line_segment(_prev(), this)) {
479         handle = &_front;
480         other = _prev();
481         other_handle = &_prev()->_back;
482     } else return;
484     if (_type == NODE_SMOOTH && !handle->isDegenerate()) {
485         handle->setDirection(other->position(), new_pos);
486     }
487     // also update the handle on the other end of the segment
488     if (other->_type == NODE_SMOOTH && !other_handle->isDegenerate()) {
489         other_handle->setDirection(new_pos, other->position());
490     }
493 void Node::_updateAutoHandles()
495     // Recompute the position of automatic handles.
496     // For endnodes, retract both handles. (It's only possible to create an end auto node
497     // through the XML editor.)
498     if (isEndNode()) {
499         _front.retract();
500         _back.retract();
501         return;
502     }
504     // Auto nodes automaticaly adjust their handles to give an appearance of smoothness,
505     // no matter what their surroundings are.
506     Geom::Point vec_next = _next()->position() - position();
507     Geom::Point vec_prev = _prev()->position() - position();
508     double len_next = vec_next.length(), len_prev = vec_prev.length();
509     if (len_next > 0 && len_prev > 0) {
510         // "dir" is an unit vector perpendicular to the bisector of the angle created
511         // by the previous node, this auto node and the next node.
512         Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
513         // Handle lengths are equal to 1/3 of the distance from the adjacent node.
514         _back.setRelativePos(-dir * (len_prev / 3));
515         _front.setRelativePos(dir * (len_next / 3));
516     } else {
517         // If any of the adjacent nodes coincides, retract both handles.
518         _front.retract();
519         _back.retract();
520     }
523 void Node::showHandles(bool v)
525     _handles_shown = v;
526     if (!_front.isDegenerate()) _front.setVisible(v);
527     if (!_back.isDegenerate()) _back.setVisible(v);
530 /** Sets the node type and optionally restores the invariants associated with the given type.
531  * @param type The type to set
532  * @param update_handles Whether to restore invariants associated with the given type.
533  *                       Passing false is useful e.g. wen initially creating the path,
534  *                       and when making cusp nodes during some node algorithms.
535  *                       Pass true when used in response to an UI node type button.
536  */
537 void Node::setType(NodeType type, bool update_handles)
539     if (type == NODE_PICK_BEST) {
540         pickBestType();
541         updateState(); // The size of the control might have changed
542         return;
543     }
545     // if update_handles is true, adjust handle positions to match the node type
546     // handle degenerate handles appropriately
547     if (update_handles) {
548         switch (type) {
549         case NODE_CUSP:
550             // if the existing type is also NODE_CUSP, retract handles
551             if (_type == NODE_CUSP) {
552                 _front.retract();
553                 _back.retract();
554             }
555             break;
556         case NODE_AUTO:
557             // auto handles make no sense for endnodes
558             if (isEndNode()) return;
559             _updateAutoHandles();
560             break;
561         case NODE_SMOOTH: {
562             // rotate handles to be colinear
563             // for degenerate nodes set positions like auto handles
564             bool prev_line = _is_line_segment(_prev(), this);
565             bool next_line = _is_line_segment(this, _next());
566             if (_type == NODE_SMOOTH) {
567                 // for a node that is already smooth and at the end of a linear segment,
568                 // drag out the second handle to 1/3 the length of the linear segment
569                 if (next_line) {
570                     _front.setRelativePos((_prev()->position() - position()) / 3);
571                 }
572                 if (prev_line) {
573                     _back.setRelativePos((_next()->position() - position()) / 3);
574                 }
575             } else if (isDegenerate()) {
576                 _updateAutoHandles();
577             } else if (_front.isDegenerate()) {
578                 // if the front handle is degenerate and this...next is a line segment,
579                 // make back colinear; otherwise pull out the other handle
580                 // to 1/3 of distance to prev
581                 if (next_line) {
582                     _back.setDirection(*_next(), *this);
583                 } else if (_prev()) {
584                     Geom::Point dir = direction(_back, *this);
585                     _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir);
586                 }
587             } else if (_back.isDegenerate()) {
588                 if (prev_line) {
589                     _front.setDirection(*_prev(), *this);
590                 } else if (_next()) {
591                     Geom::Point dir = direction(_front, *this);
592                     _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir);
593                 }
594             } else {
595                 // both handles are extended. make colinear while keeping length
596                 // first make back colinear with the vector front ---> back,
597                 // then make front colinear with back ---> node
598                 // (not back ---> front because back's position was changed in the first call)
599                 _back.setDirection(_front, _back);
600                 _front.setDirection(_back, *this);
601             }
602             } break;
603         case NODE_SYMMETRIC:
604             if (isEndNode()) return; // symmetric handles make no sense for endnodes
605             if (isDegenerate()) {
606                 // similar to auto handles but set the same length for both
607                 Geom::Point vec_next = _next()->position() - position();
608                 Geom::Point vec_prev = _prev()->position() - position();
609                 double len_next = vec_next.length(), len_prev = vec_prev.length();
610                 double len = (len_next + len_prev) / 6; // take 1/3 of average
611                 if (len == 0) return;
613                 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
614                 _back.setRelativePos(-dir * len);
615                 _front.setRelativePos(dir * len);
616             } else {
617                 // Both handles are extended. Compute average length, use direction from
618                 // back handle to front handle. This also works correctly for degenerates
619                 double len = (_front.length() + _back.length()) / 2;
620                 Geom::Point dir = direction(_back, _front);
621                 _front.setRelativePos(dir * len);
622                 _back.setRelativePos(-dir * len);
623             }
624             break;
625         default: break;
626         }
627     }
628     _type = type;
629     _setShape(_node_type_to_shape(type));
630     updateState();
633 /** Pick the best type for this node, based on the position of its handles.
634  * This is what assigns types to nodes created using the pen tool. */
635 void Node::pickBestType()
637     _type = NODE_CUSP;
638     bool front_degen = _front.isDegenerate();
639     bool back_degen = _back.isDegenerate();
640     bool both_degen = front_degen && back_degen;
641     bool neither_degen = !front_degen && !back_degen;
642     do {
643         // if both handles are degenerate, do nothing
644         if (both_degen) break;
645         // if neither are degenerate, check their respective positions
646         if (neither_degen) {
647             Geom::Point front_delta = _front.position() - position();
648             Geom::Point back_delta = _back.position() - position();
649             // for now do not automatically make nodes symmetric, it can be annoying
650             /*if (Geom::are_near(front_delta, -back_delta)) {
651                 _type = NODE_SYMMETRIC;
652                 break;
653             }*/
654             if (Geom::are_near(Geom::unit_vector(front_delta),
655                 Geom::unit_vector(-back_delta)))
656             {
657                 _type = NODE_SMOOTH;
658                 break;
659             }
660         }
661         // check whether the handle aligns with the previous line segment.
662         // we know that if front is degenerate, back isn't, because
663         // both_degen was false
664         if (front_degen && _next() && _next()->_back.isDegenerate()) {
665             Geom::Point segment_delta = Geom::unit_vector(_next()->position() - position());
666             Geom::Point handle_delta = Geom::unit_vector(_back.position() - position());
667             if (Geom::are_near(segment_delta, -handle_delta)) {
668                 _type = NODE_SMOOTH;
669                 break;
670             }
671         } else if (back_degen && _prev() && _prev()->_front.isDegenerate()) {
672             Geom::Point segment_delta = Geom::unit_vector(_prev()->position() - position());
673             Geom::Point handle_delta = Geom::unit_vector(_front.position() - position());
674             if (Geom::are_near(segment_delta, -handle_delta)) {
675                 _type = NODE_SMOOTH;
676                 break;
677             }
678         }
679     } while (false);
680     _setShape(_node_type_to_shape(_type));
681     updateState();
684 bool Node::isEndNode()
686     return !_prev() || !_next();
689 /** Move the node to the bottom of its canvas group. Useful for node break, to ensure that
690  * the selected nodes are above the unselected ones. */
691 void Node::sink()
693     sp_canvas_item_move_to_z(_canvas_item, 0);
696 NodeType Node::parse_nodetype(char x)
698     switch (x) {
699     case 'a': return NODE_AUTO;
700     case 'c': return NODE_CUSP;
701     case 's': return NODE_SMOOTH;
702     case 'z': return NODE_SYMMETRIC;
703     default: return NODE_PICK_BEST;
704     }
707 /** Customized event handler to catch scroll events needed for selection grow/shrink. */
708 bool Node::_eventHandler(GdkEvent *event)
710     static NodeList::iterator origin;
711     static int dir;
713     switch (event->type)
714     {
715     case GDK_SCROLL:
716         if (event->scroll.direction == GDK_SCROLL_UP) {
717             dir = 1;
718         } else if (event->scroll.direction == GDK_SCROLL_DOWN) {
719             dir = -1;
720         } else break;
721         if (held_control(event->scroll)) {
722             _selection.spatialGrow(this, dir);
723         } else {
724             _linearGrow(dir);
725         }
726         return true;
727     default:
728         break;
729     }
730     return ControlPoint::_eventHandler(event);
733 // TODO Move this to 2Geom!
734 static double bezier_length (Geom::Point a0, Geom::Point a1, Geom::Point a2, Geom::Point a3)
736     double lower = Geom::distance(a0, a3);
737     double upper = Geom::distance(a0, a1) + Geom::distance(a1, a2) + Geom::distance(a2, a3);
739     if (upper - lower < Geom::EPSILON) return (lower + upper)/2;
741     Geom::Point // Casteljau subdivision
742         b0 = a0,
743         c0 = a3,
744         b1 = 0.5*(a0 + a1),
745         t0 = 0.5*(a1 + a2),
746         c1 = 0.5*(a2 + a3),
747         b2 = 0.5*(b1 + t0),
748         c2 = 0.5*(t0 + c1),
749         b3 = 0.5*(b2 + c2); // == c3
750     return bezier_length(b0, b1, b2, b3) + bezier_length(b3, c2, c1, c0);
753 /** Select or deselect a node in this node's subpath based on its path distance from this node.
754  * @param dir If negative, shrink selection by one node; if positive, grow by one node */
755 void Node::_linearGrow(int dir)
757     // Interestingly, we do not need any help from PathManipulator when doing linear grow.
758     // First handle the trivial case of growing over an unselected node.
759     if (!selected() && dir > 0) {
760         _selection.insert(this);
761         return;
762     }
764     NodeList::iterator this_iter = NodeList::get_iterator(this);
765     NodeList::iterator fwd = this_iter, rev = this_iter;
766     double distance_back = 0, distance_front = 0;
768     // Linear grow is simple. We find the first unselected nodes in each direction
769     // and compare the linear distances to them.
770     if (dir > 0) {
771         if (!selected()) {
772             _selection.insert(this);
773             return;
774         }
776         // find first unselected nodes on both sides
777         while (fwd && fwd->selected()) {
778             NodeList::iterator n = fwd.next();
779             distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
780             fwd = n;
781             if (fwd == this_iter)
782                 // there is no unselected node in this cyclic subpath
783                 return;
784         }
785         // do the same for the second direction. Do not check for equality with
786         // this node, because there is at least one unselected node in the subpath,
787         // so we are guaranteed to stop.
788         while (rev && rev->selected()) {
789             NodeList::iterator p = rev.prev();
790             distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
791             rev = p;
792         }
794         NodeList::iterator t; // node to select
795         if (fwd && rev) {
796             if (distance_front <= distance_back) t = fwd;
797             else t = rev;
798         } else {
799             if (fwd) t = fwd;
800             if (rev) t = rev;
801         }
802         if (t) _selection.insert(t.ptr());
804     // Linear shrink is more complicated. We need to find the farthest selected node.
805     // This means we have to check the entire subpath. We go in the direction in which
806     // the distance we traveled is lower. We do this until we run out of nodes (ends of path)
807     // or the two iterators meet. On the way, we store the last selected node and its distance
808     // in each direction (if any). At the end, we choose the one that is farther and deselect it.
809     } else {
810         // both iterators that store last selected nodes are initially empty
811         NodeList::iterator last_fwd, last_rev;
812         double last_distance_back = 0, last_distance_front = 0;
814         while (rev || fwd) {
815             if (fwd && (!rev || distance_front <= distance_back)) {
816                 if (fwd->selected()) {
817                     last_fwd = fwd;
818                     last_distance_front = distance_front;
819                 }
820                 NodeList::iterator n = fwd.next();
821                 if (n) distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
822                 fwd = n;
823             } else if (rev && (!fwd || distance_front > distance_back)) {
824                 if (rev->selected()) {
825                     last_rev = rev;
826                     last_distance_back = distance_back;
827                 }
828                 NodeList::iterator p = rev.prev();
829                 if (p) distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
830                 rev = p;
831             }
832             // Check whether we walked the entire cyclic subpath.
833             // This is initially true because both iterators start from this node,
834             // so this check cannot go in the while condition.
835             // When this happens, we need to check the last node, pointed to by the iterators.
836             if (fwd && fwd == rev) {
837                 if (!fwd->selected()) break;
838                 NodeList::iterator fwdp = fwd.prev(), revn = rev.next();
839                 double df = distance_front + bezier_length(*fwdp, fwdp->_front, fwd->_back, *fwd);
840                 double db = distance_back + bezier_length(*revn, revn->_back, rev->_front, *rev);
841                 if (df > db) {
842                     last_fwd = fwd;
843                     last_distance_front = df;
844                 } else {
845                     last_rev = rev;
846                     last_distance_back = db;
847                 }
848                 break;
849             }
850         }
852         NodeList::iterator t;
853         if (last_fwd && last_rev) {
854             if (last_distance_front >= last_distance_back) t = last_fwd;
855             else t = last_rev;
856         } else {
857             if (last_fwd) t = last_fwd;
858             if (last_rev) t = last_rev;
859         }
860         if (t) _selection.erase(t.ptr());
861     }
864 void Node::_setState(State state)
866     // change node size to match type and selection state
867     switch (_type) {
868     case NODE_AUTO:
869     case NODE_CUSP:
870         if (selected()) _setSize(11);
871         else _setSize(9);
872         break;
873     default:
874         if(selected()) _setSize(9);
875         else _setSize(7);
876         break;
877     }
878     SelectableControlPoint::_setState(state);
881 bool Node::grabbed(GdkEventMotion *event)
883     if (SelectableControlPoint::grabbed(event))
884         return true;
886     // Dragging out handles with Shift + drag on a node.
887     if (!held_shift(*event)) return false;
889     Handle *h;
890     Geom::Point evp = event_point(*event);
891     Geom::Point rel_evp = evp - _last_click_event_point();
893     // This should work even if dragtolerance is zero and evp coincides with node position.
894     double angle_next = HUGE_VAL;
895     double angle_prev = HUGE_VAL;
896     bool has_degenerate = false;
897     // determine which handle to drag out based on degeneration and the direction of drag
898     if (_front.isDegenerate() && _next()) {
899         Geom::Point next_relpos = _desktop->d2w(_next()->position())
900             - _desktop->d2w(position());
901         angle_next = fabs(Geom::angle_between(rel_evp, next_relpos));
902         has_degenerate = true;
903     }
904     if (_back.isDegenerate() && _prev()) {
905         Geom::Point prev_relpos = _desktop->d2w(_prev()->position())
906             - _desktop->d2w(position());
907         angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos));
908         has_degenerate = true;
909     }
910     if (!has_degenerate) return false;
911     h = angle_next < angle_prev ? &_front : &_back;
913     h->setPosition(_desktop->w2d(evp));
914     h->setVisible(true);
915     h->transferGrab(this, event);
916     Handle::_drag_out = true;
917     return true;
920 void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event)
922     // For a note on how snapping is implemented in Inkscape, see snap.h.
923     SnapManager &sm = _desktop->namedview->snap_manager;
924     bool snap = sm.someSnapperMightSnap();
925     std::vector<Inkscape::SnapCandidatePoint> unselected;
926     if (snap) {
927         /* setup
928          * TODO We are doing this every time a snap happens. It should once be done only once
929          *      per drag - maybe in the grabbed handler?
930          * TODO Unselected nodes vector must be valid during the snap run, because it is not
931          *      copied. Fix this in snap.h and snap.cpp, then the above.
932          * TODO Snapping to unselected segments of selected paths doesn't work yet. */
934         // Build the list of unselected nodes.
935         typedef ControlPointSelection::Set Set;
936         Set &nodes = _selection.allPoints();
937         for (Set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
938             if (!(*i)->selected()) {
939                 Node *n = static_cast<Node*>(*i);
940                 Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType());
941                 unselected.push_back(p);
942             }
943         }
944         sm.setupIgnoreSelection(_desktop, true, &unselected);
945     }
947     if (held_control(*event)) {
948         Geom::Point origin = _last_drag_origin();
949         Inkscape::SnappedPoint fp, bp;
950         if (held_alt(*event)) {
951             // with Ctrl+Alt, constrain to handle lines
952             // project the new position onto a handle line that is closer
953             boost::optional<Geom::Point> front_point, back_point;
954             boost::optional<Inkscape::Snapper::ConstraintLine> line_front, line_back;
955             if (_front.isDegenerate()) {
956                 if (_is_line_segment(this, _next()))
957                     front_point = _next()->position() - origin;
958             } else {
959                 front_point = _front.relativePos();
960             }
961             if (_back.isDegenerate()) {
962                 if (_is_line_segment(_prev(), this))
963                     back_point = _prev()->position() - origin;
964             } else {
965                 back_point = _back.relativePos();
966             }
967             if (front_point)
968                 line_front = Inkscape::Snapper::ConstraintLine(origin, *front_point);
969             if (back_point)
970                 line_back = Inkscape::Snapper::ConstraintLine(origin, *back_point);
972             // TODO: combine the snap and non-snap branches by modifying snap.h / snap.cpp
973             if (snap) {
974                 if (line_front) {
975                     fp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(),
976                         _snapSourceType()), *line_front);
977                 }
978                 if (line_back) {
979                     bp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(),
980                         _snapSourceType()), *line_back);
981                 }
982             }
983             if (fp.getSnapped() || bp.getSnapped()) {
984                 if (fp.isOtherSnapBetter(bp, false)) {
985                     bp.getPoint(new_pos);
986                 } else {
987                     fp.getPoint(new_pos);
988                 }
989             } else {
990                 boost::optional<Geom::Point> pos;
991                 if (line_front) {
992                     pos = line_front->projection(new_pos);
993                 }
994                 if (line_back) {
995                     Geom::Point pos2 = line_back->projection(new_pos);
996                     if (!pos || (pos && Geom::distance(new_pos, *pos) > Geom::distance(new_pos, pos2)))
997                         pos = pos2;
998                 }
999                 if (pos) {
1000                     new_pos = *pos;
1001                 } else {
1002                     new_pos = origin;
1003                 }
1004             }
1005         } else {
1006             // with Ctrl, constrain to axes
1007             // TODO combine the two branches
1008             if (snap) {
1009                 Inkscape::Snapper::ConstraintLine line_x(origin, Geom::Point(1, 0));
1010                 Inkscape::Snapper::ConstraintLine line_y(origin, Geom::Point(0, 1));
1011                 fp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(), _snapSourceType()), line_x);
1012                 bp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(), _snapSourceType()), line_y);
1013             }
1014             if (fp.getSnapped() || bp.getSnapped()) {
1015                 if (fp.isOtherSnapBetter(bp, false)) {
1016                     fp = bp;
1017                 }
1018                 fp.getPoint(new_pos);
1019             } else {
1020                 Geom::Point origin = _last_drag_origin();
1021                 Geom::Point delta = new_pos - origin;
1022                 Geom::Dim2 d = (fabs(delta[Geom::X]) < fabs(delta[Geom::Y])) ? Geom::X : Geom::Y;
1023                 new_pos[d] = origin[d];
1024             }
1025         }
1026     } else if (snap) {
1027         sm.freeSnapReturnByRef(new_pos, _snapSourceType());
1028     }
1030     SelectableControlPoint::dragged(new_pos, event);
1033 bool Node::clicked(GdkEventButton *event)
1035     if(_pm()._nodeClicked(this, event))
1036         return true;
1037     return SelectableControlPoint::clicked(event);
1040 Inkscape::SnapSourceType Node::_snapSourceType()
1042     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1043         return SNAPSOURCE_NODE_SMOOTH;
1044     return SNAPSOURCE_NODE_CUSP;
1046 Inkscape::SnapTargetType Node::_snapTargetType()
1048     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1049         return SNAPTARGET_NODE_SMOOTH;
1050     return SNAPTARGET_NODE_CUSP;
1053 Glib::ustring Node::_getTip(unsigned state)
1055     if (state_held_shift(state)) {
1056         bool can_drag_out = (_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate());
1057         if (can_drag_out) {
1058             /*if (state_held_control(state)) {
1059                 return format_tip(C_("Path node tip",
1060                     "<b>Shift+Ctrl:</b> drag out a handle and snap its angle "
1061                     "to %f° increments"), snap_increment_degrees());
1062             }*/
1063             return C_("Path node tip",
1064                 "<b>Shift:</b> drag out a handle, click to toggle selection");
1065         }
1066         return C_("Path node tip", "<b>Shift:</b> click to toggle selection");
1067     }
1069     if (state_held_control(state)) {
1070         if (state_held_alt(state)) {
1071             return C_("Path node tip", "<b>Ctrl+Alt:</b> move along handle lines, click to delete node");
1072         }
1073         return C_("Path node tip",
1074             "<b>Ctrl:</b> move along axes, click to change node type");
1075     }
1077     // assemble tip from node name
1078     char const *nodetype = node_type_to_localized_string(_type);
1079     if (_selection.transformHandlesEnabled() && selected()) {
1080         if (_selection.size() == 1) {
1081             return format_tip(C_("Path node tip",
1082                 "<b>%s:</b> drag to shape the path (more: Shift, Ctrl, Ctrl+Alt)"), nodetype);
1083         }
1084         return format_tip(C_("Path node tip",
1085             "<b>%s:</b> drag to shape the path, click to toggle scale/rotation handles (more: Shift, Ctrl, Ctrl+Alt)"), nodetype);
1086     }
1087     return format_tip(C_("Path node tip",
1088         "<b>%s:</b> drag to shape the path, click to select only this node (more: Shift, Ctrl, Ctrl+Alt)"), nodetype);
1091 Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/)
1093     Geom::Point dist = position() - _last_drag_origin();
1094     GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
1095     GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
1096     Glib::ustring ret = format_tip(C_("Path node tip", "Move by %s, %s"),
1097         x->str, y->str);
1098     g_string_free(x, TRUE);
1099     g_string_free(y, TRUE);
1100     return ret;
1103 char const *Node::node_type_to_localized_string(NodeType type)
1105     switch (type) {
1106     case NODE_CUSP: return _("Cusp node");
1107     case NODE_SMOOTH: return _("Smooth node");
1108     case NODE_SYMMETRIC: return _("Symmetric node");
1109     case NODE_AUTO: return _("Auto-smooth node");
1110     default: return "";
1111     }
1114 /** Determine whether two nodes are joined by a linear segment. */
1115 bool Node::_is_line_segment(Node *first, Node *second)
1117     if (!first || !second) return false;
1118     if (first->_next() == second)
1119         return first->_front.isDegenerate() && second->_back.isDegenerate();
1120     if (second->_next() == first)
1121         return second->_front.isDegenerate() && first->_back.isDegenerate();
1122     return false;
1125 SPCtrlShapeType Node::_node_type_to_shape(NodeType type)
1127     switch(type) {
1128     case NODE_CUSP: return SP_CTRL_SHAPE_DIAMOND;
1129     case NODE_SMOOTH: return SP_CTRL_SHAPE_SQUARE;
1130     case NODE_AUTO: return SP_CTRL_SHAPE_CIRCLE;
1131     case NODE_SYMMETRIC: return SP_CTRL_SHAPE_SQUARE;
1132     default: return SP_CTRL_SHAPE_DIAMOND;
1133     }
1137 /**
1138  * @class NodeList
1139  * @brief An editable list of nodes representing a subpath.
1140  *
1141  * It can optionally be cyclic to represent a closed path.
1142  * The list has iterators that act like plain node iterators, but can also be used
1143  * to obtain shared pointers to nodes.
1144  */
1146 NodeList::NodeList(SubpathList &splist)
1147     : _list(splist)
1148     , _closed(false)
1150     this->list = this;
1151     this->next = this;
1152     this->prev = this;
1155 NodeList::~NodeList()
1157     clear();
1160 bool NodeList::empty()
1162     return next == this;
1165 NodeList::size_type NodeList::size()
1167     size_type sz = 0;
1168     for (ListNode *ln = next; ln != this; ln = ln->next) ++sz;
1169     return sz;
1172 bool NodeList::closed()
1174     return _closed;
1177 /** A subpath is degenerate if it has no segments - either one node in an open path
1178  * or no nodes in a closed path */
1179 bool NodeList::degenerate()
1181     return closed() ? empty() : ++begin() == end();
1184 NodeList::iterator NodeList::before(double t, double *fracpart)
1186     double intpart;
1187     *fracpart = std::modf(t, &intpart);
1188     int index = intpart;
1190     iterator ret = begin();
1191     std::advance(ret, index);
1192     return ret;
1195 // insert a node before i
1196 NodeList::iterator NodeList::insert(iterator i, Node *x)
1198     ListNode *ins = i._node;
1199     x->next = ins;
1200     x->prev = ins->prev;
1201     ins->prev->next = x;
1202     ins->prev = x;
1203     x->ListNode::list = this;
1204     return iterator(x);
1207 void NodeList::splice(iterator pos, NodeList &list)
1209     splice(pos, list, list.begin(), list.end());
1212 void NodeList::splice(iterator pos, NodeList &list, iterator i)
1214     NodeList::iterator j = i;
1215     ++j;
1216     splice(pos, list, i, j);
1219 void NodeList::splice(iterator pos, NodeList &list, iterator first, iterator last)
1221     ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node;
1222     for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->next) {
1223         ln->list = this;
1224     }
1225     ins_beg->prev->next = ins_end;
1226     ins_end->prev->next = at;
1227     at->prev->next = ins_beg;
1229     ListNode *atprev = at->prev;
1230     at->prev = ins_end->prev;
1231     ins_end->prev = ins_beg->prev;
1232     ins_beg->prev = atprev;
1235 void NodeList::shift(int n)
1237     // 1. make the list perfectly cyclic
1238     next->prev = prev;
1239     prev->next = next;
1240     // 2. find new begin
1241     ListNode *new_begin = next;
1242     if (n > 0) {
1243         for (; n > 0; --n) new_begin = new_begin->next;
1244     } else {
1245         for (; n < 0; ++n) new_begin = new_begin->prev;
1246     }
1247     // 3. relink begin to list
1248     next = new_begin;
1249     prev = new_begin->prev;
1250     new_begin->prev->next = this;
1251     new_begin->prev = this;
1254 void NodeList::reverse()
1256     for (ListNode *ln = next; ln != this; ln = ln->prev) {
1257         std::swap(ln->next, ln->prev);
1258         Node *node = static_cast<Node*>(ln);
1259         Geom::Point save_pos = node->front()->position();
1260         node->front()->setPosition(node->back()->position());
1261         node->back()->setPosition(save_pos);
1262     }
1263     std::swap(next, prev);
1266 void NodeList::clear()
1268     for (iterator i = begin(); i != end();) erase (i++);
1271 NodeList::iterator NodeList::erase(iterator i)
1273     // some gymnastics are required to ensure that the node is valid when deleted;
1274     // otherwise the code that updates handle visibility will break
1275     Node *rm = static_cast<Node*>(i._node);
1276     ListNode *rmnext = rm->next, *rmprev = rm->prev;
1277     ++i;
1278     delete rm;
1279     rmprev->next = rmnext;
1280     rmnext->prev = rmprev;
1281     return i;
1284 // TODO this method is very ugly!
1285 // converting SubpathList to an intrusive list might allow us to get rid of it
1286 void NodeList::kill()
1288     for (SubpathList::iterator i = _list.begin(); i != _list.end(); ++i) {
1289         if (i->get() == this) {
1290             _list.erase(i);
1291             return;
1292         }
1293     }
1296 NodeList &NodeList::get(Node *n) {
1297     return *(n->list());
1299 NodeList &NodeList::get(iterator const &i) {
1300     return *(i._node->list);
1304 /**
1305  * @class SubpathList
1306  * @brief Editable path composed of one or more subpaths
1307  */
1309 } // namespace UI
1310 } // namespace Inkscape
1312 /*
1313   Local Variables:
1314   mode:c++
1315   c-file-style:"stroustrup"
1316   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1317   indent-tabs-mode:nil
1318   fill-column:99
1319   End:
1320 */
1321 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :