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/transforms.h>
17 #include "ui/tool/event-utils.h"
18 #include "ui/tool/multi-path-manipulator.h"
19 #include "ui/tool/node.h"
20 #include "ui/tool/path-manipulator.h"
21 #include "display/sp-ctrlline.h"
22 #include "display/sp-canvas.h"
23 #include "display/sp-canvas-util.h"
24 #include "desktop.h"
25 #include "desktop-handles.h"
26 #include "preferences.h"
27 #include "sp-metrics.h"
28 #include "sp-namedview.h"
30 namespace Inkscape {
31 namespace UI {
33 static SelectableControlPoint::ColorSet node_colors = {
34 {
35 {0xbfbfbf00, 0x000000ff}, // normal fill, stroke
36 {0xff000000, 0x000000ff}, // mouseover fill, stroke
37 {0xff000000, 0x000000ff} // clicked fill, stroke
38 },
39 {0x0000ffff, 0x000000ff}, // normal fill, stroke when selected
40 {0xff000000, 0x000000ff}, // mouseover fill, stroke when selected
41 {0xff000000, 0x000000ff} // clicked fill, stroke when selected
42 };
44 static ControlPoint::ColorSet handle_colors = {
45 {0xffffffff, 0x000000ff}, // normal fill, stroke
46 {0xff000000, 0x000000ff}, // mouseover fill, stroke
47 {0xff000000, 0x000000ff} // clicked fill, stroke
48 };
50 std::ostream &operator<<(std::ostream &out, NodeType type)
51 {
52 switch(type) {
53 case NODE_CUSP: out << 'c'; break;
54 case NODE_SMOOTH: out << 's'; break;
55 case NODE_AUTO: out << 'a'; break;
56 case NODE_SYMMETRIC: out << 'z'; break;
57 default: out << 'b'; break;
58 }
59 return out;
60 }
62 /** Computes an unit vector of the direction from first to second control point */
63 static Geom::Point direction(Geom::Point const &first, Geom::Point const &second) {
64 return Geom::unit_vector(second - first);
65 }
67 /**
68 * @class Handle
69 * Represents a control point of a cubic Bezier curve in a path.
70 */
72 double Handle::_saved_length = 0.0;
73 bool Handle::_drag_out = false;
75 Handle::Handle(NodeSharedData const &data, Geom::Point const &initial_pos, Node *parent)
76 : ControlPoint(data.desktop, initial_pos, Gtk::ANCHOR_CENTER, SP_CTRL_SHAPE_CIRCLE, 7.0,
77 &handle_colors, data.handle_group)
78 , _parent(parent)
79 , _degenerate(true)
80 {
81 _cset = &handle_colors;
82 _handle_line = sp_canvas_item_new(data.handle_line_group, SP_TYPE_CTRLLINE, NULL);
83 setVisible(false);
84 signal_grabbed.connect(
85 sigc::bind_return(
86 sigc::hide(
87 sigc::mem_fun(*this, &Handle::_grabbedHandler)),
88 false));
89 signal_dragged.connect(
90 sigc::hide<0>(
91 sigc::mem_fun(*this, &Handle::_draggedHandler)));
92 signal_ungrabbed.connect(
93 sigc::hide(sigc::mem_fun(*this, &Handle::_ungrabbedHandler)));
94 }
95 Handle::~Handle()
96 {
97 sp_canvas_item_hide(_handle_line);
98 gtk_object_destroy(GTK_OBJECT(_handle_line));
99 }
101 void Handle::setVisible(bool v)
102 {
103 ControlPoint::setVisible(v);
104 if (v) sp_canvas_item_show(_handle_line);
105 else sp_canvas_item_hide(_handle_line);
106 }
108 void Handle::move(Geom::Point const &new_pos)
109 {
110 Handle *other, *towards, *towards_second;
111 Node *node_towards; // node in direction of this handle
112 Node *node_away; // node in the opposite direction
113 if (this == &_parent->_front) {
114 other = &_parent->_back;
115 node_towards = _parent->_next();
116 node_away = _parent->_prev();
117 towards = node_towards ? &node_towards->_back : 0;
118 towards_second = node_towards ? &node_towards->_front : 0;
119 } else {
120 other = &_parent->_front;
121 node_towards = _parent->_prev();
122 node_away = _parent->_next();
123 towards = node_towards ? &node_towards->_front : 0;
124 towards_second = node_towards ? &node_towards->_back : 0;
125 }
127 if (Geom::are_near(new_pos, _parent->position())) {
128 // The handle becomes degenerate. If the segment between it and the node
129 // in its direction becomes linear and there are smooth nodes
130 // at its ends, make their handles colinear with the segment
131 if (towards && towards->isDegenerate()) {
132 if (node_towards->type() == NODE_SMOOTH) {
133 towards_second->setDirection(*_parent, *node_towards);
134 }
135 if (_parent->type() == NODE_SMOOTH) {
136 other->setDirection(*node_towards, *_parent);
137 }
138 }
139 setPosition(new_pos);
140 return;
141 }
143 if (_parent->type() == NODE_SMOOTH && Node::_is_line_segment(_parent, node_away)) {
144 // restrict movement to the line joining the nodes
145 Geom::Point direction = _parent->position() - node_away->position();
146 Geom::Point delta = new_pos - _parent->position();
147 // project the relative position on the direction line
148 Geom::Point new_delta = (Geom::dot(delta, direction)
149 / Geom::L2sq(direction)) * direction;
150 setRelativePos(new_delta);
151 return;
152 }
154 switch (_parent->type()) {
155 case NODE_AUTO:
156 _parent->setType(NODE_SMOOTH, false);
157 // fall through - auto nodes degrade into smooth nodes
158 case NODE_SMOOTH: {
159 /* for smooth nodes, we need to rotate the other handle so that it's colinear
160 * with the dragged one while conserving length. */
161 other->setDirection(new_pos, *_parent);
162 } break;
163 case NODE_SYMMETRIC:
164 // for symmetric nodes, place the other handle on the opposite side
165 other->setRelativePos(-(new_pos - _parent->position()));
166 break;
167 default: break;
168 }
170 setPosition(new_pos);
171 }
173 void Handle::setPosition(Geom::Point const &p)
174 {
175 ControlPoint::setPosition(p);
176 sp_ctrlline_set_coords(SP_CTRLLINE(_handle_line), _parent->position(), position());
178 // update degeneration info and visibility
179 if (Geom::are_near(position(), _parent->position()))
180 _degenerate = true;
181 else _degenerate = false;
182 if (_parent->_handles_shown && _parent->visible() && !_degenerate) {
183 setVisible(true);
184 } else {
185 setVisible(false);
186 }
187 // If both handles become degenerate, convert to parent cusp node
188 if (_parent->isDegenerate()) {
189 _parent->setType(NODE_CUSP, false);
190 }
191 }
193 void Handle::setLength(double len)
194 {
195 if (isDegenerate()) return;
196 Geom::Point dir = Geom::unit_vector(relativePos());
197 setRelativePos(dir * len);
198 }
200 void Handle::retract()
201 {
202 setPosition(_parent->position());
203 }
205 void Handle::setDirection(Geom::Point const &from, Geom::Point const &to)
206 {
207 setDirection(to - from);
208 }
210 void Handle::setDirection(Geom::Point const &dir)
211 {
212 Geom::Point unitdir = Geom::unit_vector(dir);
213 setRelativePos(unitdir * length());
214 }
216 char const *Handle::handle_type_to_localized_string(NodeType type)
217 {
218 switch(type) {
219 case NODE_CUSP: return _("Cusp node handle");
220 case NODE_SMOOTH: return _("Smooth node handle");
221 case NODE_SYMMETRIC: return _("Symmetric node handle");
222 case NODE_AUTO: return _("Auto-smooth node handle");
223 default: return "";
224 }
225 }
227 void Handle::_grabbedHandler()
228 {
229 _saved_length = _drag_out ? 0 : length();
230 }
232 void Handle::_draggedHandler(Geom::Point &new_pos, GdkEventMotion *event)
233 {
234 Geom::Point parent_pos = _parent->position();
235 // with Alt, preserve length
236 if (held_alt(*event)) {
237 new_pos = parent_pos + Geom::unit_vector(new_pos - parent_pos) * _saved_length;
238 }
239 // with Ctrl, constrain to M_PI/rotationsnapsperpi increments.
240 if (held_control(*event)) {
241 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
242 int snaps = 2 * prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
243 Geom::Point origin = _last_drag_origin();
244 Geom::Point rel_origin = origin - parent_pos;
245 new_pos = parent_pos + Geom::constrain_angle(Geom::Point(0,0), new_pos - parent_pos, snaps,
246 _drag_out ? Geom::Point(1,0) : Geom::unit_vector(rel_origin));
247 }
248 signal_update.emit();
249 }
251 void Handle::_ungrabbedHandler()
252 {
253 // hide the handle if it's less than dragtolerance away from the node
254 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
255 int drag_tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
257 Geom::Point dist = _desktop->d2w(_parent->position()) - _desktop->d2w(position());
258 if (dist.length() <= drag_tolerance) {
259 move(_parent->position());
260 }
261 _drag_out = false;
262 }
264 static double snap_increment_degrees() {
265 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
266 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
267 return 180.0 / snaps;
268 }
270 Glib::ustring Handle::_getTip(unsigned state)
271 {
272 if (state_held_alt(state)) {
273 if (state_held_control(state)) {
274 return format_tip(C_("Path handle tip",
275 "<b>Ctrl+Alt</b>: preserve length and snap rotation angle to %f° increments"),
276 snap_increment_degrees());
277 } else {
278 return C_("Path handle tip",
279 "<b>Alt:</b> preserve handle length while dragging");
280 }
281 } else {
282 if (state_held_control(state)) {
283 return format_tip(C_("Path handle tip",
284 "<b>Ctrl:</b> snap rotation angle to %f° increments, click to retract"),
285 snap_increment_degrees());
286 }
287 }
288 switch (_parent->type()) {
289 case NODE_AUTO:
290 return C_("Path handle tip",
291 "<b>Auto node handle:</b> drag to convert to smooth node");
292 default:
293 return format_tip(C_("Path handle tip", "<b>%s:</b> drag to shape the curve"),
294 handle_type_to_localized_string(_parent->type()));
295 }
296 }
298 Glib::ustring Handle::_getDragTip(GdkEventMotion *event)
299 {
300 Geom::Point dist = position() - _last_drag_origin();
301 // report angle in mathematical convention
302 double angle = Geom::angle_between(Geom::Point(-1,0), position() - _parent->position());
303 angle += M_PI; // angle is (-M_PI...M_PI] - offset by +pi and scale to 0...360
304 angle *= 360.0 / (2 * M_PI);
305 GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
306 GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
307 GString *len = SP_PX_TO_METRIC_STRING(length(), _desktop->namedview->getDefaultMetric());
308 Glib::ustring ret = format_tip(C_("Path handle tip",
309 "Move by %s, %s; angle %.2f°, length %s"), x->str, y->str, angle, len->str);
310 g_string_free(x, TRUE);
311 g_string_free(y, TRUE);
312 g_string_free(len, TRUE);
313 return ret;
314 }
316 /**
317 * @class Node
318 * Represents a curve endpoint in an editable path.
319 */
321 Node::Node(NodeSharedData const &data, Geom::Point const &initial_pos)
322 : SelectableControlPoint(data.desktop, initial_pos, Gtk::ANCHOR_CENTER,
323 SP_CTRL_SHAPE_DIAMOND, 9.0, *data.selection, &node_colors, data.node_group)
324 , _front(data, initial_pos, this)
325 , _back(data, initial_pos, this)
326 , _type(NODE_CUSP)
327 , _handles_shown(false)
328 {
329 // NOTE we do not set type here, because the handles are still degenerate
330 // connect to own grabbed signal - dragging out handles
331 signal_grabbed.connect(
332 sigc::mem_fun(*this, &Node::_grabbedHandler));
333 signal_dragged.connect( sigc::hide<0>(
334 sigc::mem_fun(*this, &Node::_draggedHandler)));
335 }
337 // NOTE: not using iterators won't make this much quicker because iterators can be 100% inlined.
338 Node *Node::_next()
339 {
340 NodeList::iterator n = NodeList::get_iterator(this).next();
341 if (n) return n.ptr();
342 return NULL;
343 }
344 Node *Node::_prev()
345 {
346 NodeList::iterator p = NodeList::get_iterator(this).prev();
347 if (p) return p.ptr();
348 return NULL;
349 }
351 void Node::move(Geom::Point const &new_pos)
352 {
353 // move handles when the node moves.
354 Geom::Point old_pos = position();
355 Geom::Point delta = new_pos - position();
356 setPosition(new_pos);
357 _front.setPosition(_front.position() + delta);
358 _back.setPosition(_back.position() + delta);
360 // if the node has a smooth handle after a line segment, it should be kept colinear
361 // with the segment
362 _fixNeighbors(old_pos, new_pos);
363 }
365 void Node::transform(Geom::Matrix const &m)
366 {
367 Geom::Point old_pos = position();
368 setPosition(position() * m);
369 _front.setPosition(_front.position() * m);
370 _back.setPosition(_back.position() * m);
372 /* Affine transforms keep handle invariants for smooth and symmetric nodes,
373 * but smooth nodes at ends of linear segments and auto nodes need special treatment */
374 _fixNeighbors(old_pos, position());
375 }
377 Geom::Rect Node::bounds()
378 {
379 Geom::Rect b(position(), position());
380 b.expandTo(_front.position());
381 b.expandTo(_back.position());
382 return b;
383 }
385 void Node::_fixNeighbors(Geom::Point const &old_pos, Geom::Point const &new_pos)
386 {
387 /* This method restores handle invariants for neighboring nodes,
388 * and invariants that are based on positions of those nodes for this one. */
390 /* Fix auto handles */
391 if (_type == NODE_AUTO) _updateAutoHandles();
392 if (old_pos != new_pos) {
393 if (_next() && _next()->_type == NODE_AUTO) _next()->_updateAutoHandles();
394 if (_prev() && _prev()->_type == NODE_AUTO) _prev()->_updateAutoHandles();
395 }
397 /* Fix smooth handles at the ends of linear segments.
398 * Rotate the appropriate handle to be colinear with the segment.
399 * If there is a smooth node at the other end of the segment, rotate it too. */
400 Handle *handle, *other_handle;
401 Node *other;
402 if (_is_line_segment(this, _next())) {
403 handle = &_back;
404 other = _next();
405 other_handle = &_next()->_front;
406 } else if (_is_line_segment(_prev(), this)) {
407 handle = &_front;
408 other = _prev();
409 other_handle = &_prev()->_back;
410 } else return;
412 if (_type == NODE_SMOOTH && !handle->isDegenerate()) {
413 handle->setDirection(other->position(), new_pos);
414 }
415 // also update the handle on the other end of the segment
416 if (other->_type == NODE_SMOOTH && !other_handle->isDegenerate()) {
417 other_handle->setDirection(new_pos, other->position());
418 }
419 }
421 void Node::_updateAutoHandles()
422 {
423 // Recompute the position of automatic handles.
424 // For endnodes, retract both handles. (It's only possible to create an end auto node
425 // through the XML editor.)
426 if (isEndNode()) {
427 _front.retract();
428 _back.retract();
429 return;
430 }
432 // Auto nodes automaticaly adjust their handles to give an appearance of smoothness,
433 // no matter what their surroundings are.
434 Geom::Point vec_next = _next()->position() - position();
435 Geom::Point vec_prev = _prev()->position() - position();
436 double len_next = vec_next.length(), len_prev = vec_prev.length();
437 if (len_next > 0 && len_prev > 0) {
438 // "dir" is an unit vector perpendicular to the bisector of the angle created
439 // by the previous node, this auto node and the next node.
440 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
441 // Handle lengths are equal to 1/3 of the distance from the adjacent node.
442 _back.setRelativePos(-dir * (len_prev / 3));
443 _front.setRelativePos(dir * (len_next / 3));
444 } else {
445 // If any of the adjacent nodes coincides, retract both handles.
446 _front.retract();
447 _back.retract();
448 }
449 }
451 void Node::showHandles(bool v)
452 {
453 _handles_shown = v;
454 if (!_front.isDegenerate()) _front.setVisible(v);
455 if (!_back.isDegenerate()) _back.setVisible(v);
456 }
458 /** Sets the node type and optionally restores the invariants associated with the given type.
459 * @param type The type to set
460 * @param update_handles Whether to restore invariants associated with the given type.
461 * Passing false is useful e.g. wen initially creating the path,
462 * and when making cusp nodes during some node algorithms.
463 * Pass true when used in response to an UI node type button.
464 */
465 void Node::setType(NodeType type, bool update_handles)
466 {
467 if (type == NODE_PICK_BEST) {
468 pickBestType();
469 updateState(); // The size of the control might have changed
470 return;
471 }
473 // if update_handles is true, adjust handle positions to match the node type
474 // handle degenerate handles appropriately
475 if (update_handles) {
476 switch (type) {
477 case NODE_CUSP:
478 // if the existing type is also NODE_CUSP, retract handles
479 if (_type == NODE_CUSP) {
480 _front.retract();
481 _back.retract();
482 }
483 break;
484 case NODE_AUTO:
485 // auto handles make no sense for endnodes
486 if (isEndNode()) return;
487 _updateAutoHandles();
488 break;
489 case NODE_SMOOTH: {
490 // rotate handles to be colinear
491 // for degenerate nodes set positions like auto handles
492 bool prev_line = _is_line_segment(_prev(), this);
493 bool next_line = _is_line_segment(this, _next());
494 if (isDegenerate()) {
495 _updateAutoHandles();
496 } else if (_front.isDegenerate()) {
497 // if the front handle is degenerate and this...next is a line segment,
498 // make back colinear; otherwise pull out the other handle
499 // to 1/3 of distance to prev
500 if (next_line) {
501 _back.setDirection(*_next(), *this);
502 } else if (_prev()) {
503 Geom::Point dir = direction(_back, *this);
504 _front.setRelativePos((_prev()->position() - position()).length() / 3 * dir);
505 }
506 } else if (_back.isDegenerate()) {
507 if (prev_line) {
508 _front.setDirection(*_prev(), *this);
509 } else if (_next()) {
510 Geom::Point dir = direction(_front, *this);
511 _back.setRelativePos((_next()->position() - position()).length() / 3 * dir);
512 }
513 } else {
514 // both handles are extended. make colinear while keeping length
515 // first make back colinear with the vector front ---> back,
516 // then make front colinear with back ---> node
517 // (not back ---> front because back's position was changed in the first call)
518 _back.setDirection(_front, _back);
519 _front.setDirection(_back, *this);
520 }
521 } break;
522 case NODE_SYMMETRIC:
523 if (isEndNode()) return; // symmetric handles make no sense for endnodes
524 if (isDegenerate()) {
525 // similar to auto handles but set the same length for both
526 Geom::Point vec_next = _next()->position() - position();
527 Geom::Point vec_prev = _prev()->position() - position();
528 double len_next = vec_next.length(), len_prev = vec_prev.length();
529 double len = (len_next + len_prev) / 6; // take 1/3 of average
530 if (len == 0) return;
532 Geom::Point dir = Geom::unit_vector((len_prev / len_next) * vec_next - vec_prev);
533 _back.setRelativePos(-dir * len);
534 _front.setRelativePos(dir * len);
535 } else {
536 // Both handles are extended. Compute average length, use direction from
537 // back handle to front handle. This also works correctly for degenerates
538 double len = (_front.length() + _back.length()) / 2;
539 Geom::Point dir = direction(_back, _front);
540 _front.setRelativePos(dir * len);
541 _back.setRelativePos(-dir * len);
542 }
543 break;
544 default: break;
545 }
546 }
547 _type = type;
548 _setShape(_node_type_to_shape(type));
549 updateState();
550 }
552 void Node::pickBestType()
553 {
554 _type = NODE_CUSP;
555 bool front_degen = _front.isDegenerate();
556 bool back_degen = _back.isDegenerate();
557 bool both_degen = front_degen && back_degen;
558 bool neither_degen = !front_degen && !back_degen;
559 do {
560 // if both handles are degenerate, do nothing
561 if (both_degen) break;
562 // if neither are degenerate, check their respective positions
563 if (neither_degen) {
564 Geom::Point front_delta = _front.position() - position();
565 Geom::Point back_delta = _back.position() - position();
566 // for now do not automatically make nodes symmetric, it can be annoying
567 /*if (Geom::are_near(front_delta, -back_delta)) {
568 _type = NODE_SYMMETRIC;
569 break;
570 }*/
571 if (Geom::are_near(Geom::unit_vector(front_delta),
572 Geom::unit_vector(-back_delta)))
573 {
574 _type = NODE_SMOOTH;
575 break;
576 }
577 }
578 // check whether the handle aligns with the previous line segment.
579 // we know that if front is degenerate, back isn't, because
580 // both_degen was false
581 if (front_degen && _next() && _next()->_back.isDegenerate()) {
582 Geom::Point segment_delta = Geom::unit_vector(_next()->position() - position());
583 Geom::Point handle_delta = Geom::unit_vector(_back.position() - position());
584 if (Geom::are_near(segment_delta, -handle_delta)) {
585 _type = NODE_SMOOTH;
586 break;
587 }
588 } else if (back_degen && _prev() && _prev()->_front.isDegenerate()) {
589 Geom::Point segment_delta = Geom::unit_vector(_prev()->position() - position());
590 Geom::Point handle_delta = Geom::unit_vector(_front.position() - position());
591 if (Geom::are_near(segment_delta, -handle_delta)) {
592 _type = NODE_SMOOTH;
593 break;
594 }
595 }
596 } while (false);
597 _setShape(_node_type_to_shape(_type));
598 updateState();
599 }
601 bool Node::isEndNode()
602 {
603 return !_prev() || !_next();
604 }
606 /** Move the node to the bottom of its canvas group. Useful for node break, to ensure that
607 * the selected nodes are above the unselected ones. */
608 void Node::sink()
609 {
610 sp_canvas_item_move_to_z(_canvas_item, 0);
611 }
613 NodeType Node::parse_nodetype(char x)
614 {
615 switch (x) {
616 case 'a': return NODE_AUTO;
617 case 'c': return NODE_CUSP;
618 case 's': return NODE_SMOOTH;
619 case 'z': return NODE_SYMMETRIC;
620 default: return NODE_PICK_BEST;
621 }
622 }
624 bool Node::_eventHandler(GdkEvent *event)
625 {
626 static NodeList::iterator origin;
627 static int dir;
629 switch (event->type)
630 {
631 case GDK_SCROLL:
632 if (event->scroll.direction == GDK_SCROLL_UP) {
633 dir = 1;
634 } else if (event->scroll.direction == GDK_SCROLL_DOWN) {
635 dir = -1;
636 } else break;
637 origin = NodeList::get_iterator(this);
639 if (held_control(event->scroll)) {
640 list()->_list._path_manipulator._multi_path_manipulator.spatialGrow(origin, dir);
641 } else {
642 list()->_list._path_manipulator.linearGrow(origin, dir);
643 }
644 return true;
645 default:
646 break;
647 }
648 return ControlPoint::_eventHandler(event);
649 }
651 void Node::_setState(State state)
652 {
653 // change node size to match type and selection state
654 switch (_type) {
655 case NODE_AUTO:
656 case NODE_CUSP:
657 if (selected()) _setSize(11);
658 else _setSize(9);
659 break;
660 default:
661 if(selected()) _setSize(9);
662 else _setSize(7);
663 break;
664 }
665 SelectableControlPoint::_setState(state);
666 }
668 bool Node::_grabbedHandler(GdkEventMotion *event)
669 {
670 // dragging out handles
671 if (!held_shift(*event)) return false;
673 Handle *h;
674 Geom::Point evp = event_point(*event);
675 Geom::Point rel_evp = evp - _last_click_event_point();
677 // this should work even if dragtolerance is zero and evp coincides with node position
678 double angle_next = HUGE_VAL;
679 double angle_prev = HUGE_VAL;
680 bool has_degenerate = false;
681 // determine which handle to drag out based on degeneration and the direction of drag
682 if (_front.isDegenerate() && _next()) {
683 Geom::Point next_relpos = _desktop->d2w(_next()->position())
684 - _desktop->d2w(position());
685 angle_next = fabs(Geom::angle_between(rel_evp, next_relpos));
686 has_degenerate = true;
687 }
688 if (_back.isDegenerate() && _prev()) {
689 Geom::Point prev_relpos = _desktop->d2w(_prev()->position())
690 - _desktop->d2w(position());
691 angle_prev = fabs(Geom::angle_between(rel_evp, prev_relpos));
692 has_degenerate = true;
693 }
694 if (!has_degenerate) return false;
695 h = angle_next < angle_prev ? &_front : &_back;
697 h->setPosition(_desktop->w2d(evp));
698 h->setVisible(true);
699 h->transferGrab(this, event);
700 Handle::_drag_out = true;
701 return true;
702 }
704 void Node::_draggedHandler(Geom::Point &new_pos, GdkEventMotion *event)
705 {
706 if (held_control(*event)) {
707 if (held_alt(*event)) {
708 // with Ctrl+Alt, constrain to handle lines
709 // project the new position onto a handle line that is closer
710 Geom::Point origin = _last_drag_origin();
711 Geom::Line line_front(origin, origin + _front.relativePos());
712 Geom::Line line_back(origin, origin + _back.relativePos());
713 double dist_front, dist_back;
714 dist_front = Geom::distance(new_pos, line_front);
715 dist_back = Geom::distance(new_pos, line_back);
716 if (dist_front < dist_back) {
717 new_pos = Geom::projection(new_pos, line_front);
718 } else {
719 new_pos = Geom::projection(new_pos, line_back);
720 }
721 } else {
722 // with Ctrl, constrain to axes
723 // TODO maybe add diagonals when the distance from origin is large enough?
724 Geom::Point origin = _last_drag_origin();
725 Geom::Point delta = new_pos - origin;
726 Geom::Dim2 d = (fabs(delta[Geom::X]) < fabs(delta[Geom::Y])) ? Geom::X : Geom::Y;
727 new_pos[d] = origin[d];
728 }
729 } else {
730 // snapping?
731 }
732 }
734 Glib::ustring Node::_getTip(unsigned state)
735 {
736 if (state_held_shift(state)) {
737 if ((_next() && _front.isDegenerate()) || (_prev() && _back.isDegenerate())) {
738 if (state_held_control(state)) {
739 return format_tip(C_("Path node tip",
740 "<b>Shift+Ctrl:</b> drag out a handle and snap its angle "
741 "to %f° increments"), snap_increment_degrees());
742 }
743 return C_("Path node tip",
744 "<b>Shift:</b> drag out a handle, click to toggle selection");
745 }
746 return C_("Path node tip", "<b>Shift:</b> click to toggle selection");
747 }
749 if (state_held_control(state)) {
750 if (state_held_alt(state)) {
751 return C_("Path node tip", "<b>Ctrl+Alt:</b> move along handle lines");
752 }
753 return C_("Path node tip",
754 "<b>Ctrl:</b> move along axes, click to change node type");
755 }
757 // assemble tip from node name
758 char const *nodetype = node_type_to_localized_string(_type);
759 return format_tip(C_("Path node tip",
760 "<b>%s:</b> drag to shape the path, click to select this node"), nodetype);
761 }
763 Glib::ustring Node::_getDragTip(GdkEventMotion *event)
764 {
765 Geom::Point dist = position() - _last_drag_origin();
766 GString *x = SP_PX_TO_METRIC_STRING(dist[Geom::X], _desktop->namedview->getDefaultMetric());
767 GString *y = SP_PX_TO_METRIC_STRING(dist[Geom::Y], _desktop->namedview->getDefaultMetric());
768 Glib::ustring ret = format_tip(C_("Path node tip", "Move by %s, %s"),
769 x->str, y->str);
770 g_string_free(x, TRUE);
771 g_string_free(y, TRUE);
772 return ret;
773 }
775 char const *Node::node_type_to_localized_string(NodeType type)
776 {
777 switch (type) {
778 case NODE_CUSP: return _("Cusp node");
779 case NODE_SMOOTH: return _("Smooth node");
780 case NODE_SYMMETRIC: return _("Symmetric node");
781 case NODE_AUTO: return _("Auto-smooth node");
782 default: return "";
783 }
784 }
786 /** Determine whether two nodes are joined by a linear segment. */
787 bool Node::_is_line_segment(Node *first, Node *second)
788 {
789 if (!first || !second) return false;
790 if (first->_next() == second)
791 return first->_front.isDegenerate() && second->_back.isDegenerate();
792 if (second->_next() == first)
793 return second->_front.isDegenerate() && first->_back.isDegenerate();
794 return false;
795 }
797 SPCtrlShapeType Node::_node_type_to_shape(NodeType type)
798 {
799 switch(type) {
800 case NODE_CUSP: return SP_CTRL_SHAPE_DIAMOND;
801 case NODE_SMOOTH: return SP_CTRL_SHAPE_SQUARE;
802 case NODE_AUTO: return SP_CTRL_SHAPE_CIRCLE;
803 case NODE_SYMMETRIC: return SP_CTRL_SHAPE_SQUARE;
804 default: return SP_CTRL_SHAPE_DIAMOND;
805 }
806 }
809 /**
810 * @class NodeList
811 * @brief An editable list of nodes representing a subpath.
812 *
813 * It can optionally be cyclic to represent a closed path.
814 * The list has iterators that act like plain node iterators, but can also be used
815 * to obtain shared pointers to nodes.
816 *
817 * @todo Manage geometric representation to improve speed
818 */
820 NodeList::NodeList(SubpathList &splist)
821 : _list(splist)
822 , _closed(false)
823 {
824 this->list = this;
825 this->next = this;
826 this->prev = this;
827 }
829 NodeList::~NodeList()
830 {
831 clear();
832 }
834 bool NodeList::empty()
835 {
836 return next == this;
837 }
839 NodeList::size_type NodeList::size()
840 {
841 size_type sz = 0;
842 for (ListNode *ln = next; ln != this; ln = ln->next) ++sz;
843 return sz;
844 }
846 bool NodeList::closed()
847 {
848 return _closed;
849 }
851 /** A subpath is degenerate if it has no segments - either one node in an open path
852 * or no nodes in a closed path */
853 bool NodeList::degenerate()
854 {
855 return closed() ? empty() : ++begin() == end();
856 }
858 NodeList::iterator NodeList::before(double t, double *fracpart)
859 {
860 double intpart;
861 *fracpart = std::modf(t, &intpart);
862 int index = intpart;
864 iterator ret = begin();
865 std::advance(ret, index);
866 return ret;
867 }
869 // insert a node before i
870 NodeList::iterator NodeList::insert(iterator i, Node *x)
871 {
872 ListNode *ins = i._node;
873 x->next = ins;
874 x->prev = ins->prev;
875 ins->prev->next = x;
876 ins->prev = x;
877 x->ListNode::list = this;
878 _list.signal_insert_node.emit(x);
879 return iterator(x);
880 }
882 void NodeList::splice(iterator pos, NodeList &list)
883 {
884 splice(pos, list, list.begin(), list.end());
885 }
887 void NodeList::splice(iterator pos, NodeList &list, iterator i)
888 {
889 NodeList::iterator j = i;
890 ++j;
891 splice(pos, list, i, j);
892 }
894 void NodeList::splice(iterator pos, NodeList &list, iterator first, iterator last)
895 {
896 ListNode *ins_beg = first._node, *ins_end = last._node, *at = pos._node;
897 for (ListNode *ln = ins_beg; ln != ins_end; ln = ln->next) {
898 list._list.signal_remove_node.emit(static_cast<Node*>(ln));
899 ln->list = this;
900 _list.signal_insert_node.emit(static_cast<Node*>(ln));
901 }
902 ins_beg->prev->next = ins_end;
903 ins_end->prev->next = at;
904 at->prev->next = ins_beg;
906 ListNode *atprev = at->prev;
907 at->prev = ins_end->prev;
908 ins_end->prev = ins_beg->prev;
909 ins_beg->prev = atprev;
910 }
912 void NodeList::shift(int n)
913 {
914 // 1. make the list perfectly cyclic
915 next->prev = prev;
916 prev->next = next;
917 // 2. find new begin
918 ListNode *new_begin = next;
919 if (n > 0) {
920 for (; n > 0; --n) new_begin = new_begin->next;
921 } else {
922 for (; n < 0; ++n) new_begin = new_begin->prev;
923 }
924 // 3. relink begin to list
925 next = new_begin;
926 prev = new_begin->prev;
927 new_begin->prev->next = this;
928 new_begin->prev = this;
929 }
931 void NodeList::reverse()
932 {
933 for (ListNode *ln = next; ln != this; ln = ln->prev) {
934 std::swap(ln->next, ln->prev);
935 Node *node = static_cast<Node*>(ln);
936 Geom::Point save_pos = node->front()->position();
937 node->front()->setPosition(node->back()->position());
938 node->back()->setPosition(save_pos);
939 }
940 std::swap(next, prev);
941 }
943 void NodeList::clear()
944 {
945 for (iterator i = begin(); i != end();) erase (i++);
946 }
948 NodeList::iterator NodeList::erase(iterator i)
949 {
950 // some gymnastics are required to ensure that the node is valid when deleted;
951 // otherwise the code that updates handle visibility will break
952 Node *rm = static_cast<Node*>(i._node);
953 ListNode *rmnext = rm->next, *rmprev = rm->prev;
954 ++i;
955 _list.signal_remove_node.emit(rm);
956 delete rm;
957 rmprev->next = rmnext;
958 rmnext->prev = rmprev;
959 return i;
960 }
962 // TODO this method is nasty and ugly!
963 // converting SubpathList to an intrusive list might allow us to get rid of it
964 void NodeList::kill()
965 {
966 for (SubpathList::iterator i = _list.begin(); i != _list.end(); ++i) {
967 if (i->get() == this) {
968 _list.erase(i);
969 return;
970 }
971 }
972 }
974 NodeList &NodeList::get(Node *n) {
975 return *(n->list());
976 }
977 NodeList &NodeList::get(iterator const &i) {
978 return *(i._node->list);
979 }
982 /**
983 * @class SubpathList
984 * @brief Editable path composed of one or more subpaths
985 */
987 } // namespace UI
988 } // namespace Inkscape
990 /*
991 Local Variables:
992 mode:c++
993 c-file-style:"stroustrup"
994 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
995 indent-tabs-mode:nil
996 fill-column:99
997 End:
998 */
999 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :