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