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)
101 {
102 ControlPoint::setVisible(v);
103 if (v) sp_canvas_item_show(_handle_line);
104 else sp_canvas_item_hide(_handle_line);
105 }
107 void Handle::move(Geom::Point const &new_pos)
108 {
109 Handle *other = this->other();
110 Node *node_towards = _parent->nodeToward(this); // node in direction of this handle
111 Node *node_away = _parent->nodeAwayFrom(this); // node in the opposite direction
112 Handle *towards = node_towards ? node_towards->handleAwayFrom(_parent) : NULL;
113 Handle *towards_second = node_towards ? node_towards->handleToward(_parent) : NULL;
115 if (Geom::are_near(new_pos, _parent->position())) {
116 // The handle becomes degenerate.
117 // Adjust node type as necessary.
118 if (other->isDegenerate()) {
119 // If both handles become degenerate, convert to parent cusp node
120 _parent->setType(NODE_CUSP, false);
121 } else {
122 // Only 1 handle becomes degenerate
123 switch (_parent->type()) {
124 case NODE_AUTO:
125 case NODE_SYMMETRIC:
126 _parent->setType(NODE_SMOOTH, false);
127 break;
128 default:
129 // do nothing for other node types
130 break;
131 }
132 }
133 // If the segment between the handle and the node
134 // in its direction becomes linear and there are smooth nodes
135 // at its ends, make their handles colinear with the segment
136 if (towards && towards_second->isDegenerate()) {
137 if (node_towards->type() == NODE_SMOOTH) {
138 towards->setDirection(*_parent, *node_towards);
139 }
140 if (_parent->type() == NODE_SMOOTH) {
141 other->setDirection(*node_towards, *_parent);
142 }
143 }
144 setPosition(new_pos);
145 return;
146 }
148 if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
149 // restrict movement to the line joining the nodes
150 Geom::Point direction = _parent->position() - node_away->position();
151 Geom::Point delta = new_pos - _parent->position();
152 // project the relative position on the direction line
153 Geom::Point new_delta = (Geom::dot(delta, direction)
154 / Geom::L2sq(direction)) * direction;
155 setRelativePos(new_delta);
156 return;
157 }
159 switch (_parent->type()) {
160 case NODE_AUTO:
161 _parent->setType(NODE_SMOOTH, false);
162 // fall through - auto nodes degrade into smooth nodes
163 case NODE_SMOOTH: {
164 /* for smooth nodes, we need to rotate the other handle so that it's colinear
165 * with the dragged one while conserving length. */
166 other->setDirection(new_pos, *_parent);
167 } break;
168 case NODE_SYMMETRIC:
169 // for symmetric nodes, place the other handle on the opposite side
170 other->setRelativePos(-(new_pos - _parent->position()));
171 break;
172 default: break;
173 }
175 setPosition(new_pos);
176 }
178 void Handle::setPosition(Geom::Point const &p)
179 {
180 Geom::Point old_pos = position();
181 ControlPoint::setPosition(p);
182 sp_ctrlline_set_coords(SP_CTRLLINE(_handle_line), _parent->position(), position());
184 // update degeneration info and visibility
185 if (Geom::are_near(position(), _parent->position()))
186 _degenerate = true;
187 else _degenerate = false;
189 if (_parent->_handles_shown && _parent->visible() && !_degenerate) {
190 setVisible(true);
191 } else {
192 setVisible(false);
193 }
194 }
196 void Handle::setLength(double len)
197 {
198 if (isDegenerate()) return;
199 Geom::Point dir = Geom::unit_vector(relativePos());
200 setRelativePos(dir * len);
201 }
203 void Handle::retract()
204 {
205 move(_parent->position());
206 }
208 void Handle::setDirection(Geom::Point const &from, Geom::Point const &to)
209 {
210 setDirection(to - from);
211 }
213 void Handle::setDirection(Geom::Point const &dir)
214 {
215 Geom::Point unitdir = Geom::unit_vector(dir);
216 setRelativePos(unitdir * length());
217 }
219 char const *Handle::handle_type_to_localized_string(NodeType type)
220 {
221 switch(type) {
222 case NODE_CUSP: return _("Cusp node handle");
223 case NODE_SMOOTH: return _("Smooth node handle");
224 case NODE_SYMMETRIC: return _("Symmetric node handle");
225 case NODE_AUTO: return _("Auto-smooth node handle");
226 default: return "";
227 }
228 }
230 bool Handle::grabbed(GdkEventMotion *)
231 {
232 _saved_other_pos = other()->position();
233 _saved_length = _drag_out ? 0 : length();
234 _pm()._handleGrabbed();
235 return false;
236 }
238 void Handle::dragged(Geom::Point &new_pos, GdkEventMotion *event)
239 {
240 Geom::Point parent_pos = _parent->position();
241 Geom::Point origin = _last_drag_origin();
242 SnapManager &sm = _desktop->namedview->snap_manager;
243 bool snap = sm.someSnapperMightSnap();
244 boost::optional<Inkscape::Snapper::SnapConstraint> ctrl_constraint;
246 // with Alt, preserve length
247 if (held_alt(*event)) {
248 new_pos = parent_pos + Geom::unit_vector(new_pos - parent_pos) * _saved_length;
249 snap = false;
250 }
251 // with Ctrl, constrain to M_PI/rotationsnapsperpi increments from vertical
252 // and the original position.
253 if (held_control(*event)) {
254 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
255 int snaps = 2 * prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
257 // note: if snapping to the original position is only desired in the original
258 // direction of the handle, change to Ray instead of Line
259 Geom::Line original_line(parent_pos, origin);
260 Geom::Line perp_line(parent_pos, parent_pos + Geom::rot90(origin - parent_pos));
261 Geom::Point snap_pos = parent_pos + Geom::constrain_angle(
262 Geom::Point(0,0), new_pos - parent_pos, snaps, Geom::Point(1,0));
263 Geom::Point orig_pos = original_line.pointAt(original_line.nearestPoint(new_pos));
264 Geom::Point perp_pos = perp_line.pointAt(perp_line.nearestPoint(new_pos));
266 Geom::Point result = snap_pos;
267 ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - snap_pos);
268 if (Geom::distance(orig_pos, new_pos) < Geom::distance(result, new_pos)) {
269 result = orig_pos;
270 ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - orig_pos);
271 }
272 if (Geom::distance(perp_pos, new_pos) < Geom::distance(result, new_pos)) {
273 result = perp_pos;
274 ctrl_constraint = Inkscape::Snapper::SnapConstraint(parent_pos, parent_pos - perp_pos);
275 }
276 new_pos = result;
277 }
279 std::vector<Inkscape::SnapCandidatePoint> unselected;
280 if (snap) {
281 typedef ControlPointSelection::Set Set;
282 Set &nodes = _parent->_selection.allPoints();
283 for (Set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
284 Node *n = static_cast<Node*>(*i);
285 Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType());
286 unselected.push_back(p);
287 }
288 sm.setupIgnoreSelection(_desktop, true, &unselected);
290 Node *node_away = _parent->nodeAwayFrom(this);
291 if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
292 Inkscape::Snapper::SnapConstraint cl(_parent->position(),
293 _parent->position() - node_away->position());
294 Inkscape::SnappedPoint p;
295 p = sm.constrainedSnap(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_NODE_HANDLE), cl);
296 new_pos = p.getPoint();
297 } else if (ctrl_constraint) {
298 // NOTE: this is subtly wrong.
299 // We should get all possible constraints and snap along them using
300 // multipleConstrainedSnaps, instead of first snapping to angle and the to objects
301 Inkscape::SnappedPoint p;
302 p = sm.constrainedSnap(Inkscape::SnapCandidatePoint(new_pos, SNAPSOURCE_NODE_HANDLE), *ctrl_constraint);
303 new_pos = p.getPoint();
304 } else {
305 sm.freeSnapReturnByRef(new_pos, SNAPSOURCE_NODE_HANDLE);
306 }
307 sm.unSetup();
308 }
311 // with Shift, if the node is cusp, rotate the other handle as well
312 if (_parent->type() == NODE_CUSP && !_drag_out) {
313 if (held_shift(*event)) {
314 Geom::Point other_relpos = _saved_other_pos - parent_pos;
315 other_relpos *= Geom::Rotate(Geom::angle_between(origin - parent_pos, new_pos - parent_pos));
316 other()->setRelativePos(other_relpos);
317 } else {
318 // restore the position
319 other()->setPosition(_saved_other_pos);
320 }
321 }
322 move(new_pos); // needed for correct update, even though it's redundant
323 _pm().update();
324 }
326 void Handle::ungrabbed(GdkEventButton *event)
327 {
328 // hide the handle if it's less than dragtolerance away from the node
329 // TODO is this actually desired?
330 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
331 int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
333 Geom::Point dist = _desktop->d2w(_parent->position()) - _desktop->d2w(position());
334 if (dist.length() <= drag_tolerance) {
335 move(_parent->position());
336 }
338 // HACK: If the handle was dragged out, call parent's ungrabbed handler,
339 // so that transform handles reappear
340 if (_drag_out) {
341 _parent->ungrabbed(event);
342 }
343 _drag_out = false;
345 _pm()._handleUngrabbed();
346 }
348 bool Handle::clicked(GdkEventButton *event)
349 {
350 _pm()._handleClicked(this, event);
351 return true;
352 }
354 Handle *Handle::other()
355 {
356 if (this == &_parent->_front) return &_parent->_back;
357 return &_parent->_front;
358 }
360 static double snap_increment_degrees() {
361 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
362 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
363 return 180.0 / snaps;
364 }
366 Glib::ustring Handle::_getTip(unsigned state)
367 {
368 char const *more;
369 bool can_shift_rotate = _parent->type() == NODE_CUSP && !other()->isDegenerate();
370 if (can_shift_rotate) {
371 more = C_("Path handle tip", "more: Shift, Ctrl, Alt");
372 } else {
373 more = C_("Path handle tip", "more: Ctrl, Alt");
374 }
375 if (state_held_alt(state)) {
376 if (state_held_control(state)) {
377 if (state_held_shift(state) && can_shift_rotate) {
378 return format_tip(C_("Path handle tip",
379 "<b>Shift+Ctrl+Alt</b>: preserve length and snap rotation angle to %g° "
380 "increments while rotating both handles"),
381 snap_increment_degrees());
382 } else {
383 return format_tip(C_("Path handle tip",
384 "<b>Ctrl+Alt</b>: preserve length and snap rotation angle to %g° increments"),
385 snap_increment_degrees());
386 }
387 } else {
388 if (state_held_shift(state) && can_shift_rotate) {
389 return C_("Path handle tip",
390 "<b>Shift+Alt</b>: preserve handle length and rotate both handles");
391 } else {
392 return C_("Path handle tip",
393 "<b>Alt</b>: preserve handle length while dragging");
394 }
395 }
396 } else {
397 if (state_held_control(state)) {
398 if (state_held_shift(state) && can_shift_rotate) {
399 return format_tip(C_("Path handle tip",
400 "<b>Shift+Ctrl</b>: snap rotation angle to %g° increments and rotate both handles"),
401 snap_increment_degrees());
402 } else {
403 return format_tip(C_("Path handle tip",
404 "<b>Ctrl</b>: snap rotation angle to %g° increments, click to retract"),
405 snap_increment_degrees());
406 }
407 } else if (state_held_shift(state) && can_shift_rotate) {
408 return C_("Path hande tip",
409 "<b>Shift</b>: rotate both handles by the same angle");
410 }
411 }
413 switch (_parent->type()) {
414 case NODE_AUTO:
415 return format_tip(C_("Path handle tip",
416 "<b>Auto node handle</b>: drag to convert to smooth node (%s)"), more);
417 default:
418 return format_tip(C_("Path handle tip",
419 "<b>%s</b>: drag to shape the segment (%s)"),
420 handle_type_to_localized_string(_parent->type()), more);
421 }
422 }
424 Glib::ustring Handle::_getDragTip(GdkEventMotion */*event*/)
425 {
426 Geom::Point dist = position() - _last_drag_origin();
427 // report angle in mathematical convention
428 double angle = Geom::angle_between(Geom::Point(-1,0), position() - _parent->position());
429 angle += M_PI; // angle is (-M_PI...M_PI] - offset by +pi and scale to 0...360
430 angle *= 360.0 / (2 * M_PI);
431 GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
432 GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
433 GString *len = SP_PX_TO_METRIC_STRING(length(), _desktop->namedview->getDefaultMetric());
434 Glib::ustring ret = format_tip(C_("Path handle tip",
435 "Move handle by %s, %s; angle %.2f°, length %s"), x->str, y->str, angle, len->str);
436 g_string_free(x, TRUE);
437 g_string_free(y, TRUE);
438 g_string_free(len, TRUE);
439 return ret;
440 }
442 /**
443 * @class Node
444 * @brief Curve endpoint in an editable path.
445 *
446 * The method move() keeps node type invariants during translations.
447 */
449 Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos)
450 : SelectableControlPoint(data.desktop, initial_pos, Gtk::ANCHOR_CENTER,
451 SP_CTRL_SHAPE_DIAMOND, 9.0, *data.selection, &node_colors, data.node_group)
452 , _front(data, initial_pos, this)
453 , _back(data, initial_pos, this)
454 , _type(NODE_CUSP)
455 , _handles_shown(false)
456 {
457 // NOTE we do not set type here, because the handles are still degenerate
458 }
460 // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined.
461 Node *Node::_next()
462 {
463 NodeList::iterator n = NodeList::get_iterator(this).next();
464 if (n) return n.ptr();
465 return NULL;
466 }
467 Node *Node::_prev()
468 {
469 NodeList::iterator p = NodeList::get_iterator(this).prev();
470 if (p) return p.ptr();
471 return NULL;
472 }
474 void Node::move(Geom::Point const &new_pos)
475 {
476 // move handles when the node moves.
477 Geom::Point old_pos = position();
478 Geom::Point delta = new_pos - position();
479 setPosition(new_pos);
480 _front.setPosition(_front.position() + delta);
481 _back.setPosition(_back.position() + delta);
483 // if the node has a smooth handle after a line segment, it should be kept colinear
484 // with the segment
485 _fixNeighbors(old_pos, new_pos);
486 }
488 void Node::transform(Geom::Matrix const &m)
489 {
490 Geom::Point old_pos = position();
491 setPosition(position() * m);
492 _front.setPosition(_front.position() * m);
493 _back.setPosition(_back.position() * m);
495 /* Affine transforms keep handle invariants for smooth and symmetric nodes,
496 * but smooth nodes at ends of linear segments and auto nodes need special treatment */
497 _fixNeighbors(old_pos, position());
498 }
500 Geom::Rect Node::bounds()
501 {
502 Geom::Rect b(position(), position());
503 b.expandTo(_front.position());
504 b.expandTo(_back.position());
505 return b;
506 }
508 void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos)
509 {
510 /* This method restores handle invariants for neighboring nodes,
511 * and invariants that are based on positions of those nodes for this one. */
513 /* Fix auto handles */
514 if (_type == NODE_AUTO) _updateAutoHandles();
515 if (old_pos != new_pos) {
516 if (_next() && _next()->_type == NODE_AUTO) _next()->_updateAutoHandles();
517 if (_prev() && _prev()->_type == NODE_AUTO) _prev()->_updateAutoHandles();
518 }
520 /* Fix smooth handles at the ends of linear segments.
521 * Rotate the appropriate handle to be colinear with the segment.
522 * If there is a smooth node at the other end of the segment, rotate it too. */
523 Handle *handle, *other_handle;
524 Node *other;
525 if (_is_line_segment(this, _next())) {
526 handle = &_back;
527 other = _next();
528 other_handle = &_next()->_front;
529 } else if (_is_line_segment(_prev(), this)) {
530 handle = &_front;
531 other = _prev();
532 other_handle = &_prev()->_back;
533 } else return;
535 if (_type == NODE_SMOOTH && !handle->isDegenerate()) {
536 handle->setDirection(other->position(), new_pos);
537 }
538 // also update the handle on the other end of the segment
539 if (other->_type == NODE_SMOOTH && !other_handle->isDegenerate()) {
540 other_handle->setDirection(new_pos, other->position());
541 }
542 }
544 void Node::_updateAutoHandles()
545 {
546 // Recompute the position of automatic handles.
547 // For endnodes, retract both handles. (It's only possible to create an end auto node
548 // through the XML editor.)
549 if (isEndNode()) {
550 _front.retract();
551 _back.retract();
552 return;
553 }
555 // Auto nodes automaticaly adjust their handles to give an appearance of smoothness,
556 // no matter what their surroundings are.
557 Geom::Point vec_next = _next()->position() - position();
558 Geom::Point vec_prev = _prev()->position() - position();
559 double len_next = vec_next.length(), len_prev = vec_prev.length();
560 if (len_next > 0 && len_prev > 0) {
561 // "dir" is an unit vector perpendicular to the bisector of the angle created
562 // by the previous node, this auto node and the next node.
563 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
564 // Handle lengths are equal to 1/3 of the distance from the adjacent node.
565 _back.setRelativePos(-dir * (len_prev / 3));
566 _front.setRelativePos(dir * (len_next / 3));
567 } else {
568 // If any of the adjacent nodes coincides, retract both handles.
569 _front.retract();
570 _back.retract();
571 }
572 }
574 void Node::showHandles(bool v)
575 {
576 _handles_shown = v;
577 if (!_front.isDegenerate()) _front.setVisible(v);
578 if (!_back.isDegenerate()) _back.setVisible(v);
579 }
581 /** Sets the node type and optionally restores the invariants associated with the given type.
582 * @param type The type to set
583 * @param update_handles Whether to restore invariants associated with the given type.
584 * Passing false is useful e.g. wen initially creating the path,
585 * and when making cusp nodes during some node algorithms.
586 * Pass true when used in response to an UI node type button.
587 */
588 void Node::setType(NodeType type, bool update_handles)
589 {
590 if (type == NODE_PICK_BEST) {
591 pickBestType();
592 updateState(); // The size of the control might have changed
593 return;
594 }
596 // if update_handles is true, adjust handle positions to match the node type
597 // handle degenerate handles appropriately
598 if (update_handles) {
599 switch (type) {
600 case NODE_CUSP:
601 // nothing to do
602 break;
603 case NODE_AUTO:
604 // auto handles make no sense for endnodes
605 if (isEndNode()) return;
606 _updateAutoHandles();
607 break;
608 case NODE_SMOOTH: {
609 // ignore attempts to make smooth endnodes.
610 if (isEndNode()) return;
611 // rotate handles to be colinear
612 // for degenerate nodes set positions like auto handles
613 bool prev_line = _is_line_segment(_prev(), this);
614 bool next_line = _is_line_segment(this, _next());
615 if (_type == NODE_SMOOTH) {
616 // For a node that is already smooth and has a degenerate handle,
617 // drag out the second handle without changing the direction of the first one.
618 if (_front.isDegenerate()) {
619 double dist = Geom::distance(_next()->position(), position());
620 _front.setRelativePos(Geom::unit_vector(-_back.relativePos()) * dist / 3);
621 }
622 if (_back.isDegenerate()) {
623 double dist = Geom::distance(_prev()->position(), position());
624 _back.setRelativePos(Geom::unit_vector(-_front.relativePos()) * dist / 3);
625 }
626 } else if (isDegenerate()) {
627 _updateAutoHandles();
628 } else if (_front.isDegenerate()) {
629 // if the front handle is degenerate and this...next is a line segment,
630 // make back colinear; otherwise pull out the other handle
631 // to 1/3 of distance to prev
632 if (next_line) {
633 _back.setDirection(*_next(), *this);
634 } else if (_prev()) {
635 Geom::Point dir = direction(_back, *this);
636 _front.setRelativePos(Geom::distance(_prev()->position(), position()) / 3 * dir);
637 }
638 } else if (_back.isDegenerate()) {
639 if (prev_line) {
640 _front.setDirection(*_prev(), *this);
641 } else if (_next()) {
642 Geom::Point dir = direction(_front, *this);
643 _back.setRelativePos(Geom::distance(_next()->position(), position()) / 3 * dir);
644 }
645 } else {
646 // both handles are extended. make colinear while keeping length
647 // first make back colinear with the vector front ---> back,
648 // then make front colinear with back ---> node
649 // (not back ---> front because back's position was changed in the first call)
650 _back.setDirection(_front, _back);
651 _front.setDirection(_back, *this);
652 }
653 } break;
654 case NODE_SYMMETRIC:
655 if (isEndNode()) return; // symmetric handles make no sense for endnodes
656 if (isDegenerate()) {
657 // similar to auto handles but set the same length for both
658 Geom::Point vec_next = _next()->position() - position();
659 Geom::Point vec_prev = _prev()->position() - position();
660 double len_next = vec_next.length(), len_prev = vec_prev.length();
661 double len = (len_next + len_prev) / 6; // take 1/3 of average
662 if (len == 0) return;
664 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
665 _back.setRelativePos(-dir * len);
666 _front.setRelativePos(dir * len);
667 } else {
668 // Both handles are extended. Compute average length, use direction from
669 // back handle to front handle. This also works correctly for degenerates
670 double len = (_front.length() + _back.length()) / 2;
671 Geom::Point dir = direction(_back, _front);
672 _front.setRelativePos(dir * len);
673 _back.setRelativePos(-dir * len);
674 }
675 break;
676 default: break;
677 }
678 }
679 _type = type;
680 _setShape(_node_type_to_shape(type));
681 updateState();
682 }
684 /** Pick the best type for this node, based on the position of its handles.
685 * This is what assigns types to nodes created using the pen tool. */
686 void Node::pickBestType()
687 {
688 _type = NODE_CUSP;
689 bool front_degen = _front.isDegenerate();
690 bool back_degen = _back.isDegenerate();
691 bool both_degen = front_degen && back_degen;
692 bool neither_degen = !front_degen && !back_degen;
693 do {
694 // if both handles are degenerate, do nothing
695 if (both_degen) break;
696 // if neither are degenerate, check their respective positions
697 if (neither_degen) {
698 Geom::Point front_delta = _front.position() - position();
699 Geom::Point back_delta = _back.position() - position();
700 // for now do not automatically make nodes symmetric, it can be annoying
701 /*if (Geom::are_near(front_delta, -back_delta)) {
702 _type = NODE_SYMMETRIC;
703 break;
704 }*/
705 if (Geom::are_near(Geom::unit_vector(front_delta),
706 Geom::unit_vector(-back_delta)))
707 {
708 _type = NODE_SMOOTH;
709 break;
710 }
711 }
712 // check whether the handle aligns with the previous line segment.
713 // we know that if front is degenerate, back isn't, because
714 // both_degen was false
715 if (front_degen && _next() && _next()->_back.isDegenerate()) {
716 Geom::Point segment_delta = Geom::unit_vector(_next()->position() - position());
717 Geom::Point handle_delta = Geom::unit_vector(_back.position() - position());
718 if (Geom::are_near(segment_delta, -handle_delta)) {
719 _type = NODE_SMOOTH;
720 break;
721 }
722 } else if (back_degen && _prev() && _prev()->_front.isDegenerate()) {
723 Geom::Point segment_delta = Geom::unit_vector(_prev()->position() - position());
724 Geom::Point handle_delta = Geom::unit_vector(_front.position() - position());
725 if (Geom::are_near(segment_delta, -handle_delta)) {
726 _type = NODE_SMOOTH;
727 break;
728 }
729 }
730 } while (false);
731 _setShape(_node_type_to_shape(_type));
732 updateState();
733 }
735 bool Node::isEndNode()
736 {
737 return !_prev() || !_next();
738 }
740 /** Move the node to the bottom of its canvas group. Useful for node break, to ensure that
741 * the selected nodes are above the unselected ones. */
742 void Node::sink()
743 {
744 sp_canvas_item_move_to_z(_canvas_item, 0);
745 }
747 NodeType Node::parse_nodetype(char x)
748 {
749 switch (x) {
750 case 'a': return NODE_AUTO;
751 case 'c': return NODE_CUSP;
752 case 's': return NODE_SMOOTH;
753 case 'z': return NODE_SYMMETRIC;
754 default: return NODE_PICK_BEST;
755 }
756 }
758 /** Customized event handler to catch scroll events needed for selection grow/shrink. */
759 bool Node::_eventHandler(GdkEvent *event)
760 {
761 int dir = 0;
763 switch (event->type)
764 {
765 case GDK_SCROLL:
766 if (event->scroll.direction == GDK_SCROLL_UP) {
767 dir = 1;
768 } else if (event->scroll.direction == GDK_SCROLL_DOWN) {
769 dir = -1;
770 } else break;
771 if (held_control(event->scroll)) {
772 _linearGrow(dir);
773 } else {
774 _selection.spatialGrow(this, dir);
775 }
776 return true;
777 case GDK_KEY_PRESS:
778 switch (shortcut_key(event->key))
779 {
780 case GDK_Page_Up:
781 dir = 1;
782 break;
783 case GDK_Page_Down:
784 dir = -1;
785 break;
786 default: goto bail_out;
787 }
789 if (held_control(event->key)) {
790 _linearGrow(dir);
791 } else {
792 _selection.spatialGrow(this, dir);
793 }
794 return true;
795 default:
796 break;
797 }
799 bail_out:
800 return ControlPoint::_eventHandler(event);
801 }
803 // TODO Move this to 2Geom!
804 static double bezier_length (Geom::Point a0, Geom::Point a1, Geom::Point a2, Geom::Point a3)
805 {
806 double lower = Geom::distance(a0, a3);
807 double upper = Geom::distance(a0, a1) + Geom::distance(a1, a2) + Geom::distance(a2, a3);
809 if (upper - lower < Geom::EPSILON) return (lower + upper)/2;
811 Geom::Point // Casteljau subdivision
812 b0 = a0,
813 c0 = a3,
814 b1 = 0.5*(a0 + a1),
815 t0 = 0.5*(a1 + a2),
816 c1 = 0.5*(a2 + a3),
817 b2 = 0.5*(b1 + t0),
818 c2 = 0.5*(t0 + c1),
819 b3 = 0.5*(b2 + c2); // == c3
820 return bezier_length(b0, b1, b2, b3) + bezier_length(b3, c2, c1, c0);
821 }
823 /** Select or deselect a node in this node's subpath based on its path distance from this node.
824 * @param dir If negative, shrink selection by one node; if positive, grow by one node */
825 void Node::_linearGrow(int dir)
826 {
827 // Interestingly, we do not need any help from PathManipulator when doing linear grow.
828 // First handle the trivial case of growing over an unselected node.
829 if (!selected() && dir > 0) {
830 _selection.insert(this);
831 return;
832 }
834 NodeList::iterator this_iter = NodeList::get_iterator(this);
835 NodeList::iterator fwd = this_iter, rev = this_iter;
836 double distance_back = 0, distance_front = 0;
838 // Linear grow is simple. We find the first unselected nodes in each direction
839 // and compare the linear distances to them.
840 if (dir > 0) {
841 if (!selected()) {
842 _selection.insert(this);
843 return;
844 }
846 // find first unselected nodes on both sides
847 while (fwd && fwd->selected()) {
848 NodeList::iterator n = fwd.next();
849 distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
850 fwd = n;
851 if (fwd == this_iter)
852 // there is no unselected node in this cyclic subpath
853 return;
854 }
855 // do the same for the second direction. Do not check for equality with
856 // this node, because there is at least one unselected node in the subpath,
857 // so we are guaranteed to stop.
858 while (rev && rev->selected()) {
859 NodeList::iterator p = rev.prev();
860 distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
861 rev = p;
862 }
864 NodeList::iterator t; // node to select
865 if (fwd && rev) {
866 if (distance_front <= distance_back) t = fwd;
867 else t = rev;
868 } else {
869 if (fwd) t = fwd;
870 if (rev) t = rev;
871 }
872 if (t) _selection.insert(t.ptr());
874 // Linear shrink is more complicated. We need to find the farthest selected node.
875 // This means we have to check the entire subpath. We go in the direction in which
876 // the distance we traveled is lower. We do this until we run out of nodes (ends of path)
877 // or the two iterators meet. On the way, we store the last selected node and its distance
878 // in each direction (if any). At the end, we choose the one that is farther and deselect it.
879 } else {
880 // both iterators that store last selected nodes are initially empty
881 NodeList::iterator last_fwd, last_rev;
882 double last_distance_back = 0, last_distance_front = 0;
884 while (rev || fwd) {
885 if (fwd && (!rev || distance_front <= distance_back)) {
886 if (fwd->selected()) {
887 last_fwd = fwd;
888 last_distance_front = distance_front;
889 }
890 NodeList::iterator n = fwd.next();
891 if (n) distance_front += bezier_length(*fwd, fwd->_front, n->_back, *n);
892 fwd = n;
893 } else if (rev && (!fwd || distance_front > distance_back)) {
894 if (rev->selected()) {
895 last_rev = rev;
896 last_distance_back = distance_back;
897 }
898 NodeList::iterator p = rev.prev();
899 if (p) distance_back += bezier_length(*rev, rev->_back, p->_front, *p);
900 rev = p;
901 }
902 // Check whether we walked the entire cyclic subpath.
903 // This is initially true because both iterators start from this node,
904 // so this check cannot go in the while condition.
905 // When this happens, we need to check the last node, pointed to by the iterators.
906 if (fwd && fwd == rev) {
907 if (!fwd->selected()) break;
908 NodeList::iterator fwdp = fwd.prev(), revn = rev.next();
909 double df = distance_front + bezier_length(*fwdp, fwdp->_front, fwd->_back, *fwd);
910 double db = distance_back + bezier_length(*revn, revn->_back, rev->_front, *rev);
911 if (df > db) {
912 last_fwd = fwd;
913 last_distance_front = df;
914 } else {
915 last_rev = rev;
916 last_distance_back = db;
917 }
918 break;
919 }
920 }
922 NodeList::iterator t;
923 if (last_fwd && last_rev) {
924 if (last_distance_front >= last_distance_back) t = last_fwd;
925 else t = last_rev;
926 } else {
927 if (last_fwd) t = last_fwd;
928 if (last_rev) t = last_rev;
929 }
930 if (t) _selection.erase(t.ptr());
931 }
932 }
934 void Node::_setState(State state)
935 {
936 // change node size to match type and selection state
937 switch (_type) {
938 case NODE_AUTO:
939 case NODE_CUSP:
940 if (selected()) _setSize(11);
941 else _setSize(9);
942 break;
943 default:
944 if(selected()) _setSize(9);
945 else _setSize(7);
946 break;
947 }
948 SelectableControlPoint::_setState(state);
949 }
951 bool Node::grabbed(GdkEventMotion *event)
952 {
953 if (SelectableControlPoint::grabbed(event))
954 return true;
956 // Dragging out handles with Shift + drag on a node.
957 if (!held_shift(*event)) return false;
959 Handle *h;
960 Geom::Point evp = event_point(*event);
961 Geom::Point rel_evp = evp - _last_click_event_point();
963 // This should work even if dragtolerance is zero and evp coincides with node position.
964 double angle_next = HUGE_VAL;
965 double angle_prev = HUGE_VAL;
966 bool has_degenerate = false;
967 // determine which handle to drag out based on degeneration and the direction of drag
968 if (_front.isDegenerate() && _next()) {
969 Geom::Point next_relpos = _desktop->d2w(_next()->position())
970 - _desktop->d2w(position());
971 angle_next = fabs(Geom::angle_between(rel_evp, next_relpos));
972 has_degenerate = true;
973 }
974 if (_back.isDegenerate() && _prev()) {
975 Geom::Point prev_relpos = _desktop->d2w(_prev()->position())
976 - _desktop->d2w(position());
977 angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos));
978 has_degenerate = true;
979 }
980 if (!has_degenerate) return false;
981 h = angle_next < angle_prev ? &_front : &_back;
983 h->setPosition(_desktop->w2d(evp));
984 h->setVisible(true);
985 h->transferGrab(this, event);
986 Handle::_drag_out = true;
987 return true;
988 }
990 void Node::dragged(Geom::Point &new_pos, GdkEventMotion *event)
991 {
992 // For a note on how snapping is implemented in Inkscape, see snap.h.
993 SnapManager &sm = _desktop->namedview->snap_manager;
994 // even if we won't really snap, we might still call the one of the
995 // constrainedSnap() methods to enforce the constraints, so we need
996 // to setup the snapmanager anyway; this is also required for someSnapperMightSnap()
997 sm.setup(_desktop);
999 // do not snap when Shift is pressed
1000 bool snap = !held_shift(*event) && sm.someSnapperMightSnap();
1002 Inkscape::SnappedPoint sp;
1003 std::vector<Inkscape::SnapCandidatePoint> unselected;
1004 if (snap) {
1005 /* setup
1006 * TODO We are doing this every time a snap happens. It should once be done only once
1007 * per drag - maybe in the grabbed handler?
1008 * TODO Unselected nodes vector must be valid during the snap run, because it is not
1009 * copied. Fix this in snap.h and snap.cpp, then the above.
1010 * TODO Snapping to unselected segments of selected paths doesn't work yet. */
1012 // Build the list of unselected nodes.
1013 typedef ControlPointSelection::Set Set;
1014 Set &nodes = _selection.allPoints();
1015 for (Set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
1016 if (!(*i)->selected()) {
1017 Node *n = static_cast<Node*>(*i);
1018 Inkscape::SnapCandidatePoint p(n->position(), n->_snapSourceType(), n->_snapTargetType());
1019 unselected.push_back(p);
1020 }
1021 }
1022 sm.unSetup();
1023 sm.setupIgnoreSelection(_desktop, true, &unselected);
1024 }
1026 if (held_control(*event)) {
1027 Geom::Point origin = _last_drag_origin();
1028 std::vector<Inkscape::Snapper::SnapConstraint> constraints;
1029 if (held_alt(*event)) {
1030 // with Ctrl+Alt, constrain to handle lines
1031 // project the new position onto a handle line that is closer;
1032 // also snap to perpendiculars of handle lines
1034 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1035 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
1036 double min_angle = M_PI / snaps;
1038 boost::optional<Geom::Point> front_point, back_point, fperp_point, bperp_point;
1039 if (_front.isDegenerate()) {
1040 if (_is_line_segment(this, _next()))
1041 front_point = _next()->position() - origin;
1042 } else {
1043 front_point = _front.relativePos();
1044 }
1045 if (_back.isDegenerate()) {
1046 if (_is_line_segment(_prev(), this))
1047 back_point = _prev()->position() - origin;
1048 } else {
1049 back_point = _back.relativePos();
1050 }
1051 if (front_point) {
1052 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, *front_point));
1053 fperp_point = Geom::rot90(*front_point);
1054 }
1055 if (back_point) {
1056 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, *back_point));
1057 bperp_point = Geom::rot90(*back_point);
1058 }
1059 // perpendiculars only snap when they are further than snap increment away
1060 // from the second handle constraint
1061 if (fperp_point && (!back_point ||
1062 (fabs(Geom::angle_between(*fperp_point, *back_point)) > min_angle &&
1063 fabs(Geom::angle_between(*fperp_point, *back_point)) < M_PI - min_angle)))
1064 {
1065 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, *fperp_point));
1066 }
1067 if (bperp_point && (!front_point ||
1068 (fabs(Geom::angle_between(*bperp_point, *front_point)) > min_angle &&
1069 fabs(Geom::angle_between(*bperp_point, *front_point)) < M_PI - min_angle)))
1070 {
1071 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, *bperp_point));
1072 }
1074 sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event));
1075 } else {
1076 // with Ctrl, constrain to axes
1077 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, Geom::Point(1, 0)));
1078 constraints.push_back(Inkscape::Snapper::SnapConstraint(origin, Geom::Point(0, 1)));
1079 sp = sm.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()), constraints, held_shift(*event));
1080 }
1081 new_pos = sp.getPoint();
1082 } else if (snap) {
1083 sp = sm.freeSnap(Inkscape::SnapCandidatePoint(new_pos, _snapSourceType()));
1084 new_pos = sp.getPoint();
1085 }
1087 sm.unSetup();
1089 SelectableControlPoint::dragged(new_pos, event);
1090 }
1092 bool Node::clicked(GdkEventButton *event)
1093 {
1094 if(_pm()._nodeClicked(this, event))
1095 return true;
1096 return SelectableControlPoint::clicked(event);
1097 }
1099 Inkscape::SnapSourceType Node::_snapSourceType()
1100 {
1101 if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1102 return SNAPSOURCE_NODE_SMOOTH;
1103 return SNAPSOURCE_NODE_CUSP;
1104 }
1105 Inkscape::SnapTargetType Node::_snapTargetType()
1106 {
1107 if (_type == NODE_SMOOTH || _type == NODE_AUTO)
1108 return SNAPTARGET_NODE_SMOOTH;
1109 return SNAPTARGET_NODE_CUSP;
1110 }
1112 /** @brief Gets the handle that faces the given adjacent node.
1113 * Will abort with error if the given node is not adjacent. */
1114 Handle *Node::handleToward(Node *to)
1115 {
1116 if (_next() == to) {
1117 return front();
1118 }
1119 if (_prev() == to) {
1120 return back();
1121 }
1122 g_error("Node::handleToward(): second node is not adjacent!");
1123 }
1125 /** @brief Gets the node in the direction of the given handle.
1126 * Will abort with error if the handle doesn't belong to this node. */
1127 Node *Node::nodeToward(Handle *dir)
1128 {
1129 if (front() == dir) {
1130 return _next();
1131 }
1132 if (back() == dir) {
1133 return _prev();
1134 }
1135 g_error("Node::nodeToward(): handle is not a child of this node!");
1136 }
1138 /** @brief Gets the handle that goes in the direction opposite to the given adjacent node.
1139 * Will abort with error if the given node is not adjacent. */
1140 Handle *Node::handleAwayFrom(Node *to)
1141 {
1142 if (_next() == to) {
1143 return back();
1144 }
1145 if (_prev() == to) {
1146 return front();
1147 }
1148 g_error("Node::handleAwayFrom(): second node is not adjacent!");
1149 }
1151 /** @brief Gets the node in the direction opposite to the given handle.
1152 * Will abort with error if the handle doesn't belong to this node. */
1153 Node *Node::nodeAwayFrom(Handle *h)
1154 {
1155 if (front() == h) {
1156 return _prev();
1157 }
1158 if (back() == h) {
1159 return _next();
1160 }
1161 g_error("Node::nodeAwayFrom(): handle is not a child of this node!");
1162 }
1164 Glib::ustring Node::_getTip(unsigned state)
1165 {
1166 if (state_held_shift(state)) {
1167 bool can_drag_out = (_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate());
1168 if (can_drag_out) {
1169 /*if (state_held_control(state)) {
1170 return format_tip(C_("Path node tip",
1171 "<b>Shift+Ctrl:</b> drag out a handle and snap its angle "
1172 "to %f° increments"), snap_increment_degrees());
1173 }*/
1174 return C_("Path node tip",
1175 "<b>Shift</b>: drag out a handle, click to toggle selection");
1176 }
1177 return C_("Path node tip", "<b>Shift</b>: click to toggle selection");
1178 }
1180 if (state_held_control(state)) {
1181 if (state_held_alt(state)) {
1182 return C_("Path node tip", "<b>Ctrl+Alt</b>: move along handle lines, click to delete node");
1183 }
1184 return C_("Path node tip",
1185 "<b>Ctrl</b>: move along axes, click to change node type");
1186 }
1188 if (state_held_alt(state)) {
1189 return C_("Path node tip", "<b>Alt</b>: sculpt nodes");
1190 }
1192 // No modifiers: assemble tip from node type
1193 char const *nodetype = node_type_to_localized_string(_type);
1194 if (_selection.transformHandlesEnabled() && selected()) {
1195 if (_selection.size() == 1) {
1196 return format_tip(C_("Path node tip",
1197 "<b>%s</b>: drag to shape the path (more: Shift, Ctrl, Alt)"), nodetype);
1198 }
1199 return format_tip(C_("Path node tip",
1200 "<b>%s</b>: drag to shape the path, click to toggle scale/rotation handles (more: Shift, Ctrl, Alt)"), nodetype);
1201 }
1202 return format_tip(C_("Path node tip",
1203 "<b>%s</b>: drag to shape the path, click to select only this node (more: Shift, Ctrl, Alt)"), nodetype);
1204 }
1206 Glib::ustring Node::_getDragTip(GdkEventMotion */*event*/)
1207 {
1208 Geom::Point dist = position() - _last_drag_origin();
1209 GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
1210 GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
1211 Glib::ustring ret = format_tip(C_("Path node tip", "Move node by %s, %s"),
1212 x->str, y->str);
1213 g_string_free(x, TRUE);
1214 g_string_free(y, TRUE);
1215 return ret;
1216 }
1218 char const *Node::node_type_to_localized_string(NodeType type)
1219 {
1220 switch (type) {
1221 case NODE_CUSP: return _("Cusp node");
1222 case NODE_SMOOTH: return _("Smooth node");
1223 case NODE_SYMMETRIC: return _("Symmetric node");
1224 case NODE_AUTO: return _("Auto-smooth node");
1225 default: return "";
1226 }
1227 }
1229 /** Determine whether two nodes are joined by a linear segment. */
1230 bool Node::_is_line_segment(Node *first, Node *second)
1231 {
1232 if (!first || !second) return false;
1233 if (first->_next() == second)
1234 return first->_front.isDegenerate() && second->_back.isDegenerate();
1235 if (second->_next() == first)
1236 return second->_front.isDegenerate() && first->_back.isDegenerate();
1237 return false;
1238 }
1240 SPCtrlShapeType Node::_node_type_to_shape(NodeType type)
1241 {
1242 switch(type) {
1243 case NODE_CUSP: return SP_CTRL_SHAPE_DIAMOND;
1244 case NODE_SMOOTH: return SP_CTRL_SHAPE_SQUARE;
1245 case NODE_AUTO: return SP_CTRL_SHAPE_CIRCLE;
1246 case NODE_SYMMETRIC: return SP_CTRL_SHAPE_SQUARE;
1247 default: return SP_CTRL_SHAPE_DIAMOND;
1248 }
1249 }
1252 /**
1253 * @class NodeList
1254 * @brief An editable list of nodes representing a subpath.
1255 *
1256 * It can optionally be cyclic to represent a closed path.
1257 * The list has iterators that act like plain node iterators, but can also be used
1258 * to obtain shared pointers to nodes.
1259 */
1261 NodeList::NodeList(SubpathList &splist)
1262 : _list(splist)
1263 , _closed(false)
1264 {
1265 this->ln_list = this;
1266 this->ln_next = this;
1267 this->ln_prev = this;
1268 }
1270 NodeList::~NodeList()
1271 {
1272 clear();
1273 }
1275 bool NodeList::empty()
1276 {
1277 return ln_next == this;
1278 }
1280 NodeList::size_type NodeList::size()
1281 {
1282 size_type sz = 0;
1283 for (ListNode *ln = ln_next; ln != this; ln = ln->ln_next) ++sz;
1284 return sz;
1285 }
1287 bool NodeList::closed()
1288 {
1289 return _closed;
1290 }
1292 /** A subpath is degenerate if it has no segments - either one node in an open path
1293 * or no nodes in a closed path */
1294 bool NodeList::degenerate()
1295 {
1296 return closed() ? empty() : ++begin() == end();
1297 }
1299 NodeList::iterator NodeList::before(double t, double *fracpart)
1300 {
1301 double intpart;
1302 *fracpart = std::modf(t, &intpart);
1303 int index = intpart;
1305 iterator ret = begin();
1306 std::advance(ret, index);
1307 return ret;
1308 }
1310 // insert a node before i
1311 NodeList::iterator NodeList::insert(iterator i, Node *x)
1312 {
1313 ListNode *ins = i._node;
1314 x->ln_next = ins;
1315 x->ln_prev = ins->ln_prev;
1316 ins->ln_prev->ln_next = x;
1317 ins->ln_prev = x;
1318 x->ln_list = this;
1319 return iterator(x);
1320 }
1322 void NodeList::splice(iterator pos, NodeList &list)
1323 {
1324 splice(pos, list, list.begin(), list.end());
1325 }
1327 void NodeList::splice(iterator pos, NodeList &list, iterator i)
1328 {
1329 NodeList::iterator j = i;
1330 ++j;
1331 splice(pos, list, i, j);
1332 }
1334 void NodeList::splice(iterator pos, NodeList &/*list*/, iterator first, iterator last)
1335 {
1336 ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node;
1337 for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->ln_next) {
1338 ln->ln_list = this;
1339 }
1340 ins_beg->ln_prev->ln_next = ins_end;
1341 ins_end->ln_prev->ln_next = at;
1342 at->ln_prev->ln_next = ins_beg;
1344 ListNode *atprev = at->ln_prev;
1345 at->ln_prev = ins_end->ln_prev;
1346 ins_end->ln_prev = ins_beg->ln_prev;
1347 ins_beg->ln_prev = atprev;
1348 }
1350 void NodeList::shift(int n)
1351 {
1352 // 1. make the list perfectly cyclic
1353 ln_next->ln_prev = ln_prev;
1354 ln_prev->ln_next = ln_next;
1355 // 2. find new begin
1356 ListNode *new_begin = ln_next;
1357 if (n > 0) {
1358 for (; n > 0; --n) new_begin = new_begin->ln_next;
1359 } else {
1360 for (; n < 0; ++n) new_begin = new_begin->ln_prev;
1361 }
1362 // 3. relink begin to list
1363 ln_next = new_begin;
1364 ln_prev = new_begin->ln_prev;
1365 new_begin->ln_prev->ln_next = this;
1366 new_begin->ln_prev = this;
1367 }
1369 void NodeList::reverse()
1370 {
1371 for (ListNode *ln = ln_next; ln != this; ln = ln->ln_prev) {
1372 std::swap(ln->ln_next, ln->ln_prev);
1373 Node *node = static_cast<Node*>(ln);
1374 Geom::Point save_pos = node->front()->position();
1375 node->front()->setPosition(node->back()->position());
1376 node->back()->setPosition(save_pos);
1377 }
1378 std::swap(ln_next, ln_prev);
1379 }
1381 void NodeList::clear()
1382 {
1383 for (iterator i = begin(); i != end();) erase (i++);
1384 }
1386 NodeList::iterator NodeList::erase(iterator i)
1387 {
1388 // some gymnastics are required to ensure that the node is valid when deleted;
1389 // otherwise the code that updates handle visibility will break
1390 Node *rm = static_cast<Node*>(i._node);
1391 ListNode *rmnext = rm->ln_next, *rmprev = rm->ln_prev;
1392 ++i;
1393 delete rm;
1394 rmprev->ln_next = rmnext;
1395 rmnext->ln_prev = rmprev;
1396 return i;
1397 }
1399 // TODO this method is very ugly!
1400 // converting SubpathList to an intrusive list might allow us to get rid of it
1401 void NodeList::kill()
1402 {
1403 for (SubpathList::iterator i = _list.begin(); i != _list.end(); ++i) {
1404 if (i->get() == this) {
1405 _list.erase(i);
1406 return;
1407 }
1408 }
1409 }
1411 NodeList &NodeList::get(Node *n) {
1412 return n->nodeList();
1413 }
1414 NodeList &NodeList::get(iterator const &i) {
1415 return *(i._node->ln_list);
1416 }
1419 /**
1420 * @class SubpathList
1421 * @brief Editable path composed of one or more subpaths
1422 */
1424 } // namespace UI
1425 } // namespace Inkscape
1427 /*
1428 Local Variables:
1429 mode:c++
1430 c-file-style:"stroustrup"
1431 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1432 indent-tabs-mode:nil
1433 fill-column:99
1434 End:
1435 */
1436 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :