Code

(Probably) fix a crash in the node tool and fix Ctrl+Alt dragging
[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: Shift, Ctrl, Alt");
321     } else {
322         more = C_("Path handle tip", "more: 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 %g° "
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 %g° 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 %g° 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 %g° 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 handle 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 has a degenerate handle,
568                 // drag out the second handle to 1/3 the length of the linear segment
569                 if (_front.isDegenerate()) {
570                     double dist = Geom::distance(_next()->position(), position());
571                     _front.setRelativePos(Geom::unit_vector(-_back.relativePos()) * dist / 3);
572                 }
573                 if (_back.isDegenerate()) {
574                     double dist = Geom::distance(_prev()->position(), position());
575                     _back.setRelativePos(Geom::unit_vector(-_front.relativePos()) * dist / 3);
576                 }
577             } else if (isDegenerate()) {
578                 _updateAutoHandles();
579             } else if (_front.isDegenerate()) {
580                 // if the front handle is degenerate and this...next is a line segment,
581                 // make back colinear; otherwise pull out the other handle
582                 // to 1/3 of distance to prev
583                 if (next_line) {
584                     _back.setDirection(*_next(), *this);
585                 } else if (_prev()) {
586                     Geom::Point dir = direction(_back, *this);
587                     _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir);
588                 }
589             } else if (_back.isDegenerate()) {
590                 if (prev_line) {
591                     _front.setDirection(*_prev(), *this);
592                 } else if (_next()) {
593                     Geom::Point dir = direction(_front, *this);
594                     _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir);
595                 }
596             } else {
597                 // both handles are extended. make colinear while keeping length
598                 // first make back colinear with the vector front ---> back,
599                 // then make front colinear with back ---> node
600                 // (not back ---> front because back's position was changed in the first call)
601                 _back.setDirection(_front, _back);
602                 _front.setDirection(_back, *this);
603             }
604             } break;
605         case NODE_SYMMETRIC:
606             if (isEndNode()) return; // symmetric handles make no sense for endnodes
607             if (isDegenerate()) {
608                 // similar to auto handles but set the same length for both
609                 Geom::Point vec_next = _next()->position() - position();
610                 Geom::Point vec_prev = _prev()->position() - position();
611                 double len_next = vec_next.length(), len_prev = vec_prev.length();
612                 double len = (len_next + len_prev) / 6; // take 1/3 of average
613                 if (len == 0) return;
615                 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
616                 _back.setRelativePos(-dir * len);
617                 _front.setRelativePos(dir * len);
618             } else {
619                 // Both handles are extended. Compute average length, use direction from
620                 // back handle to front handle. This also works correctly for degenerates
621                 double len = (_front.length() + _back.length()) / 2;
622                 Geom::Point dir = direction(_back, _front);
623                 _front.setRelativePos(dir * len);
624                 _back.setRelativePos(-dir * len);
625             }
626             break;
627         default: break;
628         }
629     }
630     _type = type;
631     _setShape(_node_type_to_shape(type));
632     updateState();
635 /** Pick the best type for this node, based on the position of its handles.
636  * This is what assigns types to nodes created using the pen tool. */
637 void Node::pickBestType()
639     _type = NODE_CUSP;
640     bool front_degen = _front.isDegenerate();
641     bool back_degen = _back.isDegenerate();
642     bool both_degen = front_degen && back_degen;
643     bool neither_degen = !front_degen && !back_degen;
644     do {
645         // if both handles are degenerate, do nothing
646         if (both_degen) break;
647         // if neither are degenerate, check their respective positions
648         if (neither_degen) {
649             Geom::Point front_delta = _front.position() - position();
650             Geom::Point back_delta = _back.position() - position();
651             // for now do not automatically make nodes symmetric, it can be annoying
652             /*if (Geom::are_near(front_delta, -back_delta)) {
653                 _type = NODE_SYMMETRIC;
654                 break;
655             }*/
656             if (Geom::are_near(Geom::unit_vector(front_delta),
657                 Geom::unit_vector(-back_delta)))
658             {
659                 _type = NODE_SMOOTH;
660                 break;
661             }
662         }
663         // check whether the handle aligns with the previous line segment.
664         // we know that if front is degenerate, back isn't, because
665         // both_degen was false
666         if (front_degen && _next() && _next()->_back.isDegenerate()) {
667             Geom::Point segment_delta = Geom::unit_vector(_next()->position() - position());
668             Geom::Point handle_delta = Geom::unit_vector(_back.position() - position());
669             if (Geom::are_near(segment_delta, -handle_delta)) {
670                 _type = NODE_SMOOTH;
671                 break;
672             }
673         } else if (back_degen && _prev() && _prev()->_front.isDegenerate()) {
674             Geom::Point segment_delta = Geom::unit_vector(_prev()->position() - position());
675             Geom::Point handle_delta = Geom::unit_vector(_front.position() - position());
676             if (Geom::are_near(segment_delta, -handle_delta)) {
677                 _type = NODE_SMOOTH;
678                 break;
679             }
680         }
681     } while (false);
682     _setShape(_node_type_to_shape(_type));
683     updateState();
686 bool Node::isEndNode()
688     return !_prev() || !_next();
691 /** Move the node to the bottom of its canvas group. Useful for node break, to ensure that
692  * the selected nodes are above the unselected ones. */
693 void Node::sink()
695     sp_canvas_item_move_to_z(_canvas_item, 0);
698 NodeType Node::parse_nodetype(char x)
700     switch (x) {
701     case 'a': return NODE_AUTO;
702     case 'c': return NODE_CUSP;
703     case 's': return NODE_SMOOTH;
704     case 'z': return NODE_SYMMETRIC;
705     default: return NODE_PICK_BEST;
706     }
709 /** Customized event handler to catch scroll events needed for selection grow/shrink. */
710 bool Node::_eventHandler(GdkEvent *event)
712     static NodeList::iterator origin;
713     static int dir;
715     switch (event->type)
716     {
717     case GDK_SCROLL:
718         if (event->scroll.direction == GDK_SCROLL_UP) {
719             dir = 1;
720         } else if (event->scroll.direction == GDK_SCROLL_DOWN) {
721             dir = -1;
722         } else break;
723         if (held_control(event->scroll)) {
724             _selection.spatialGrow(this, dir);
725         } else {
726             _linearGrow(dir);
727         }
728         return true;
729     default:
730         break;
731     }
732     return ControlPoint::_eventHandler(event);
735 // TODO Move this to 2Geom!
736 static double bezier_length (Geom::Point a0, Geom::Point a1, Geom::Point a2, Geom::Point a3)
738     double lower = Geom::distance(a0, a3);
739     double upper = Geom::distance(a0, a1) + Geom::distance(a1, a2) + Geom::distance(a2, a3);
741     if (upper - lower < Geom::EPSILON) return (lower + upper)/2;
743     Geom::Point // Casteljau subdivision
744         b0 = a0,
745         c0 = a3,
746         b1 = 0.5*(a0 + a1),
747         t0 = 0.5*(a1 + a2),
748         c1 = 0.5*(a2 + a3),
749         b2 = 0.5*(b1 + t0),
750         c2 = 0.5*(t0 + c1),
751         b3 = 0.5*(b2 + c2); // == c3
752     return bezier_length(b0, b1, b2, b3) + bezier_length(b3, c2, c1, c0);
755 /** Select or deselect a node in this node's subpath based on its path distance from this node.
756  * @param dir If negative, shrink selection by one node; if positive, grow by one node */
757 void Node::_linearGrow(int dir)
759     // Interestingly, we do not need any help from PathManipulator when doing linear grow.
760     // First handle the trivial case of growing over an unselected node.
761     if (!selected() && dir > 0) {
762         _selection.insert(this);
763         return;
764     }
766     NodeList::iterator this_iter = NodeList::get_iterator(this);
767     NodeList::iterator fwd = this_iter, rev = this_iter;
768     double distance_back = 0, distance_front = 0;
770     // Linear grow is simple. We find the first unselected nodes in each direction
771     // and compare the linear distances to them.
772     if (dir > 0) {
773         if (!selected()) {
774             _selection.insert(this);
775             return;
776         }
778         // find first unselected nodes on both sides
779         while (fwd && fwd->selected()) {
780             NodeList::iterator n = fwd.next();
781             distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
782             fwd = n;
783             if (fwd == this_iter)
784                 // there is no unselected node in this cyclic subpath
785                 return;
786         }
787         // do the same for the second direction. Do not check for equality with
788         // this node, because there is at least one unselected node in the subpath,
789         // so we are guaranteed to stop.
790         while (rev && rev->selected()) {
791             NodeList::iterator p = rev.prev();
792             distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
793             rev = p;
794         }
796         NodeList::iterator t; // node to select
797         if (fwd && rev) {
798             if (distance_front <= distance_back) t = fwd;
799             else t = rev;
800         } else {
801             if (fwd) t = fwd;
802             if (rev) t = rev;
803         }
804         if (t) _selection.insert(t.ptr());
806     // Linear shrink is more complicated. We need to find the farthest selected node.
807     // This means we have to check the entire subpath. We go in the direction in which
808     // the distance we traveled is lower. We do this until we run out of nodes (ends of path)
809     // or the two iterators meet. On the way, we store the last selected node and its distance
810     // in each direction (if any). At the end, we choose the one that is farther and deselect it.
811     } else {
812         // both iterators that store last selected nodes are initially empty
813         NodeList::iterator last_fwd, last_rev;
814         double last_distance_back = 0, last_distance_front = 0;
816         while (rev || fwd) {
817             if (fwd && (!rev || distance_front <= distance_back)) {
818                 if (fwd->selected()) {
819                     last_fwd = fwd;
820                     last_distance_front = distance_front;
821                 }
822                 NodeList::iterator n = fwd.next();
823                 if (n) distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
824                 fwd = n;
825             } else if (rev && (!fwd || distance_front > distance_back)) {
826                 if (rev->selected()) {
827                     last_rev = rev;
828                     last_distance_back = distance_back;
829                 }
830                 NodeList::iterator p = rev.prev();
831                 if (p) distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
832                 rev = p;
833             }
834             // Check whether we walked the entire cyclic subpath.
835             // This is initially true because both iterators start from this node,
836             // so this check cannot go in the while condition.
837             // When this happens, we need to check the last node, pointed to by the iterators.
838             if (fwd && fwd == rev) {
839                 if (!fwd->selected()) break;
840                 NodeList::iterator fwdp = fwd.prev(), revn = rev.next();
841                 double df = distance_front + bezier_length(*fwdp, fwdp->_front, fwd->_back, *fwd);
842                 double db = distance_back + bezier_length(*revn, revn->_back, rev->_front, *rev);
843                 if (df > db) {
844                     last_fwd = fwd;
845                     last_distance_front = df;
846                 } else {
847                     last_rev = rev;
848                     last_distance_back = db;
849                 }
850                 break;
851             }
852         }
854         NodeList::iterator t;
855         if (last_fwd && last_rev) {
856             if (last_distance_front >= last_distance_back) t = last_fwd;
857             else t = last_rev;
858         } else {
859             if (last_fwd) t = last_fwd;
860             if (last_rev) t = last_rev;
861         }
862         if (t) _selection.erase(t.ptr());
863     }
866 void Node::_setState(State state)
868     // change node size to match type and selection state
869     switch (_type) {
870     case NODE_AUTO:
871     case NODE_CUSP:
872         if (selected()) _setSize(11);
873         else _setSize(9);
874         break;
875     default:
876         if(selected()) _setSize(9);
877         else _setSize(7);
878         break;
879     }
880     SelectableControlPoint::_setState(state);
883 bool Node::grabbed(GdkEventMotion *event)
885     if (SelectableControlPoint::grabbed(event))
886         return true;
888     // Dragging out handles with Shift + drag on a node.
889     if (!held_shift(*event)) return false;
891     Handle *h;
892     Geom::Point evp = event_point(*event);
893     Geom::Point rel_evp = evp - _last_click_event_point();
895     // This should work even if dragtolerance is zero and evp coincides with node position.
896     double angle_next = HUGE_VAL;
897     double angle_prev = HUGE_VAL;
898     bool has_degenerate = false;
899     // determine which handle to drag out based on degeneration and the direction of drag
900     if (_front.isDegenerate() && _next()) {
901         Geom::Point next_relpos = _desktop->d2w(_next()->position())
902             - _desktop->d2w(position());
903         angle_next = fabs(Geom::angle_between(rel_evp, next_relpos));
904         has_degenerate = true;
905     }
906     if (_back.isDegenerate() && _prev()) {
907         Geom::Point prev_relpos = _desktop->d2w(_prev()->position())
908             - _desktop->d2w(position());
909         angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos));
910         has_degenerate = true;
911     }
912     if (!has_degenerate) return false;
913     h = angle_next < angle_prev ? &_front : &_back;
915     h->setPosition(_desktop->w2d(evp));
916     h->setVisible(true);
917     h->transferGrab(this, event);
918     Handle::_drag_out = true;
919     return true;
922 void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event)
924     // For a note on how snapping is implemented in Inkscape, see snap.h.
925     SnapManager &sm = _desktop->namedview->snap_manager;
926     bool snap = sm.someSnapperMightSnap();
927     std::vector<Inkscape::SnapCandidatePoint> unselected;
928     if (snap) {
929         /* setup
930          * TODO We are doing this every time a snap happens. It should once be done only once
931          *      per drag - maybe in the grabbed handler?
932          * TODO Unselected nodes vector must be valid during the snap run, because it is not
933          *      copied. Fix this in snap.h and snap.cpp, then the above.
934          * TODO Snapping to unselected segments of selected paths doesn't work yet. */
936         // Build the list of unselected nodes.
937         typedef ControlPointSelection::Set Set;
938         Set &nodes = _selection.allPoints();
939         for (Set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
940             if (!(*i)->selected()) {
941                 Node *n = static_cast<Node*>(*i);
942                 Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType());
943                 unselected.push_back(p);
944             }
945         }
946         sm.setupIgnoreSelection(_desktop, true, &unselected);
947     }
949     if (held_control(*event)) {
950         Geom::Point origin = _last_drag_origin();
951         Inkscape::SnappedPoint fp, bp;
952         if (held_alt(*event)) {
953             // with Ctrl+Alt, constrain to handle lines
954             // project the new position onto a handle line that is closer
955             boost::optional<Geom::Point> front_point, back_point;
956             boost::optional<Inkscape::Snapper::ConstraintLine> line_front, line_back;
957             if (_front.isDegenerate()) {
958                 if (_is_line_segment(this, _next()))
959                     front_point = _next()->position() - origin;
960             } else {
961                 front_point = _front.relativePos();
962             }
963             if (_back.isDegenerate()) {
964                 if (_is_line_segment(_prev(), this))
965                     back_point = _prev()->position() - origin;
966             } else {
967                 back_point = _back.relativePos();
968             }
969             if (front_point)
970                 line_front = Inkscape::Snapper::ConstraintLine(origin, *front_point);
971             if (back_point)
972                 line_back = Inkscape::Snapper::ConstraintLine(origin, *back_point);
974             // TODO: combine the snap and non-snap branches by modifying snap.h / snap.cpp
975             if (snap) {
976                 if (line_front) {
977                     fp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(),
978                         _snapSourceType()), *line_front);
979                 }
980                 if (line_back) {
981                     bp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(),
982                         _snapSourceType()), *line_back);
983                 }
984             }
985             if (fp.getSnapped() || bp.getSnapped()) {
986                 if (fp.isOtherSnapBetter(bp, false)) {
987                     bp.getPoint(new_pos);
988                 } else {
989                     fp.getPoint(new_pos);
990                 }
991             } else {
992                 boost::optional<Geom::Point> pos;
993                 if (line_front) {
994                     pos = line_front->projection(new_pos);
995                 }
996                 if (line_back) {
997                     Geom::Point pos2 = line_back->projection(new_pos);
998                     if (!pos || (pos && Geom::distance(new_pos, *pos) > Geom::distance(new_pos, pos2)))
999                         pos = pos2;
1000                 }
1001                 if (pos) {
1002                     new_pos = *pos;
1003                 } else {
1004                     new_pos = origin;
1005                 }
1006             }
1007         } else {
1008             // with Ctrl, constrain to axes
1009             // TODO combine the two branches
1010             if (snap) {
1011                 Inkscape::Snapper::ConstraintLine line_x(origin, Geom::Point(1, 0));
1012                 Inkscape::Snapper::ConstraintLine line_y(origin, Geom::Point(0, 1));
1013                 fp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(), _snapSourceType()), line_x);
1014                 bp = sm.constrainedSnap(Inkscape::SnapCandidatePoint(position(), _snapSourceType()), line_y);
1015             }
1016             if (fp.getSnapped() || bp.getSnapped()) {
1017                 if (fp.isOtherSnapBetter(bp, false)) {
1018                     fp = bp;
1019                 }
1020                 fp.getPoint(new_pos);
1021             } else {
1022                 Geom::Point origin = _last_drag_origin();
1023                 Geom::Point delta = new_pos - origin;
1024                 Geom::Dim2 d = (fabs(delta[Geom::X]) < fabs(delta[Geom::Y])) ? Geom::X : Geom::Y;
1025                 new_pos[d] = origin[d];
1026             }
1027         }
1028     } else if (snap) {
1029         sm.freeSnapReturnByRef(new_pos, _snapSourceType());
1030     }
1032     SelectableControlPoint::dragged(new_pos, event);
1035 bool Node::clicked(GdkEventButton *event)
1037     if(_pm()._nodeClicked(this, event))
1038         return true;
1039     return SelectableControlPoint::clicked(event);
1042 Inkscape::SnapSourceType Node::_snapSourceType()
1044     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1045         return SNAPSOURCE_NODE_SMOOTH;
1046     return SNAPSOURCE_NODE_CUSP;
1048 Inkscape::SnapTargetType Node::_snapTargetType()
1050     if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1051         return SNAPTARGET_NODE_SMOOTH;
1052     return SNAPTARGET_NODE_CUSP;
1055 Glib::ustring Node::_getTip(unsigned state)
1057     if (state_held_shift(state)) {
1058         bool can_drag_out = (_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate());
1059         if (can_drag_out) {
1060             /*if (state_held_control(state)) {
1061                 return format_tip(C_("Path node tip",
1062                     "<b>Shift+Ctrl:</b> drag out a handle and snap its angle "
1063                     "to %f° increments"), snap_increment_degrees());
1064             }*/
1065             return C_("Path node tip",
1066                 "<b>Shift:</b> drag out a handle, click to toggle selection");
1067         }
1068         return C_("Path node tip", "<b>Shift:</b> click to toggle selection");
1069     }
1071     if (state_held_control(state)) {
1072         if (state_held_alt(state)) {
1073             return C_("Path node tip", "<b>Ctrl+Alt:</b> move along handle lines, click to delete node");
1074         }
1075         return C_("Path node tip",
1076             "<b>Ctrl:</b> move along axes, click to change node type");
1077     }
1079     // assemble tip from node name
1080     char const *nodetype = node_type_to_localized_string(_type);
1081     if (_selection.transformHandlesEnabled() && selected()) {
1082         if (_selection.size() == 1) {
1083             return format_tip(C_("Path node tip",
1084                 "<b>%s:</b> drag to shape the path (more: Shift, Ctrl, Alt)"), nodetype);
1085         }
1086         return format_tip(C_("Path node tip",
1087             "<b>%s:</b> drag to shape the path, click to toggle scale/rotation handles (more: Shift, Ctrl, Alt)"), nodetype);
1088     }
1089     return format_tip(C_("Path node tip",
1090         "<b>%s:</b> drag to shape the path, click to select only this node (more: Shift, Ctrl, Alt)"), nodetype);
1093 Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/)
1095     Geom::Point dist = position() - _last_drag_origin();
1096     GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
1097     GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
1098     Glib::ustring ret = format_tip(C_("Path node tip", "Move node by %s, %s"),
1099         x->str, y->str);
1100     g_string_free(x, TRUE);
1101     g_string_free(y, TRUE);
1102     return ret;
1105 char const *Node::node_type_to_localized_string(NodeType type)
1107     switch (type) {
1108     case NODE_CUSP: return _("Cusp node");
1109     case NODE_SMOOTH: return _("Smooth node");
1110     case NODE_SYMMETRIC: return _("Symmetric node");
1111     case NODE_AUTO: return _("Auto-smooth node");
1112     default: return "";
1113     }
1116 /** Determine whether two nodes are joined by a linear segment. */
1117 bool Node::_is_line_segment(Node *first, Node *second)
1119     if (!first || !second) return false;
1120     if (first->_next() == second)
1121         return first->_front.isDegenerate() && second->_back.isDegenerate();
1122     if (second->_next() == first)
1123         return second->_front.isDegenerate() && first->_back.isDegenerate();
1124     return false;
1127 SPCtrlShapeType Node::_node_type_to_shape(NodeType type)
1129     switch(type) {
1130     case NODE_CUSP: return SP_CTRL_SHAPE_DIAMOND;
1131     case NODE_SMOOTH: return SP_CTRL_SHAPE_SQUARE;
1132     case NODE_AUTO: return SP_CTRL_SHAPE_CIRCLE;
1133     case NODE_SYMMETRIC: return SP_CTRL_SHAPE_SQUARE;
1134     default: return SP_CTRL_SHAPE_DIAMOND;
1135     }
1139 /**
1140  * @class NodeList
1141  * @brief An editable list of nodes representing a subpath.
1142  *
1143  * It can optionally be cyclic to represent a closed path.
1144  * The list has iterators that act like plain node iterators, but can also be used
1145  * to obtain shared pointers to nodes.
1146  */
1148 NodeList::NodeList(SubpathList &splist)
1149     : _list(splist)
1150     , _closed(false)
1152     this->list = this;
1153     this->next = this;
1154     this->prev = this;
1157 NodeList::~NodeList()
1159     clear();
1162 bool NodeList::empty()
1164     return next == this;
1167 NodeList::size_type NodeList::size()
1169     size_type sz = 0;
1170     for (ListNode *ln = next; ln != this; ln = ln->next) ++sz;
1171     return sz;
1174 bool NodeList::closed()
1176     return _closed;
1179 /** A subpath is degenerate if it has no segments - either one node in an open path
1180  * or no nodes in a closed path */
1181 bool NodeList::degenerate()
1183     return closed() ? empty() : ++begin() == end();
1186 NodeList::iterator NodeList::before(double t, double *fracpart)
1188     double intpart;
1189     *fracpart = std::modf(t, &intpart);
1190     int index = intpart;
1192     iterator ret = begin();
1193     std::advance(ret, index);
1194     return ret;
1197 // insert a node before i
1198 NodeList::iterator NodeList::insert(iterator i, Node *x)
1200     ListNode *ins = i._node;
1201     x->next = ins;
1202     x->prev = ins->prev;
1203     ins->prev->next = x;
1204     ins->prev = x;
1205     x->ListNode::list = this;
1206     return iterator(x);
1209 void NodeList::splice(iterator pos, NodeList &list)
1211     splice(pos, list, list.begin(), list.end());
1214 void NodeList::splice(iterator pos, NodeList &list, iterator i)
1216     NodeList::iterator j = i;
1217     ++j;
1218     splice(pos, list, i, j);
1221 void NodeList::splice(iterator pos, NodeList &list, iterator first, iterator last)
1223     ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node;
1224     for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->next) {
1225         ln->list = this;
1226     }
1227     ins_beg->prev->next = ins_end;
1228     ins_end->prev->next = at;
1229     at->prev->next = ins_beg;
1231     ListNode *atprev = at->prev;
1232     at->prev = ins_end->prev;
1233     ins_end->prev = ins_beg->prev;
1234     ins_beg->prev = atprev;
1237 void NodeList::shift(int n)
1239     // 1. make the list perfectly cyclic
1240     next->prev = prev;
1241     prev->next = next;
1242     // 2. find new begin
1243     ListNode *new_begin = next;
1244     if (n > 0) {
1245         for (; n > 0; --n) new_begin = new_begin->next;
1246     } else {
1247         for (; n < 0; ++n) new_begin = new_begin->prev;
1248     }
1249     // 3. relink begin to list
1250     next = new_begin;
1251     prev = new_begin->prev;
1252     new_begin->prev->next = this;
1253     new_begin->prev = this;
1256 void NodeList::reverse()
1258     for (ListNode *ln = next; ln != this; ln = ln->prev) {
1259         std::swap(ln->next, ln->prev);
1260         Node *node = static_cast<Node*>(ln);
1261         Geom::Point save_pos = node->front()->position();
1262         node->front()->setPosition(node->back()->position());
1263         node->back()->setPosition(save_pos);
1264     }
1265     std::swap(next, prev);
1268 void NodeList::clear()
1270     for (iterator i = begin(); i != end();) erase (i++);
1273 NodeList::iterator NodeList::erase(iterator i)
1275     // some gymnastics are required to ensure that the node is valid when deleted;
1276     // otherwise the code that updates handle visibility will break
1277     Node *rm = static_cast<Node*>(i._node);
1278     ListNode *rmnext = rm->next, *rmprev = rm->prev;
1279     ++i;
1280     delete rm;
1281     rmprev->next = rmnext;
1282     rmnext->prev = rmprev;
1283     return i;
1286 // TODO this method is very ugly!
1287 // converting SubpathList to an intrusive list might allow us to get rid of it
1288 void NodeList::kill()
1290     for (SubpathList::iterator i = _list.begin(); i != _list.end(); ++i) {
1291         if (i->get() == this) {
1292             _list.erase(i);
1293             return;
1294         }
1295     }
1298 NodeList &NodeList::get(Node *n) {
1299     return *(n->list());
1301 NodeList &NodeList::get(iterator const &i) {
1302     return *(i._node->list);
1306 /**
1307  * @class SubpathList
1308  * @brief Editable path composed of one or more subpaths
1309  */
1311 } // namespace UI
1312 } // namespace Inkscape
1314 /*
1315   Local Variables:
1316   mode:c++
1317   c-file-style:"stroustrup"
1318   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1319   indent-tabs-mode:nil
1320   fill-column:99
1321   End:
1322 */
1323 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :