1 /** @file
2 * Path manipulator - implementation
3 */
4 /* Authors:
5 * Krzysztof KosiĆski <tweenk.pl@gmail.com>
6 * Abhishek Sharma
7 *
8 * Copyright (C) 2009 Authors
9 * Released under GNU GPL, read the file 'COPYING' for more information
10 */
12 #include <string>
13 #include <sstream>
14 #include <deque>
15 #include <stdexcept>
16 #include <boost/shared_ptr.hpp>
17 #include <2geom/bezier-curve.h>
18 #include <2geom/bezier-utils.h>
19 #include <2geom/svg-path.h>
20 #include <glibmm.h>
21 #include <glibmm/i18n.h>
22 #include "ui/tool/path-manipulator.h"
23 #include "desktop.h"
24 #include "desktop-handles.h"
25 #include "display/sp-canvas.h"
26 #include "display/sp-canvas-util.h"
27 #include "display/curve.h"
28 #include "display/canvas-bpath.h"
29 #include "document.h"
30 #include "live_effects/effect.h"
31 #include "live_effects/lpeobject.h"
32 #include "live_effects/parameter/path.h"
33 #include "sp-path.h"
34 #include "helper/geom.h"
35 #include "preferences.h"
36 #include "style.h"
37 #include "ui/tool/control-point-selection.h"
38 #include "ui/tool/curve-drag-point.h"
39 #include "ui/tool/event-utils.h"
40 #include "ui/tool/multi-path-manipulator.h"
41 #include "xml/node.h"
42 #include "xml/node-observer.h"
44 namespace Inkscape {
45 namespace UI {
47 namespace {
48 /// Types of path changes that we must react to.
49 enum PathChange {
50 PATH_CHANGE_D,
51 PATH_CHANGE_TRANSFORM
52 };
54 } // anonymous namespace
56 /**
57 * Notifies the path manipulator when something changes the path being edited
58 * (e.g. undo / redo)
59 */
60 class PathManipulatorObserver : public Inkscape::XML::NodeObserver {
61 public:
62 PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node)
63 : _pm(p)
64 , _node(node)
65 , _blocked(false)
66 {
67 Inkscape::GC::anchor(_node);
68 _node->addObserver(*this);
69 }
71 ~PathManipulatorObserver() {
72 _node->removeObserver(*this);
73 Inkscape::GC::release(_node);
74 }
76 virtual void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr,
77 Util::ptr_shared<char>, Util::ptr_shared<char>)
78 {
79 // do nothing if blocked
80 if (_blocked) return;
82 GQuark path_d = g_quark_from_static_string("d");
83 GQuark path_transform = g_quark_from_static_string("transform");
84 GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
86 // only react to "d" (path data) and "transform" attribute changes
87 if (attr == lpe_quark || attr == path_d) {
88 _pm->_externalChange(PATH_CHANGE_D);
89 } else if (attr == path_transform) {
90 _pm->_externalChange(PATH_CHANGE_TRANSFORM);
91 }
92 }
94 void block() { _blocked = true; }
95 void unblock() { _blocked = false; }
96 private:
97 PathManipulator *_pm;
98 Inkscape::XML::Node *_node;
99 bool _blocked;
100 };
102 void build_segment(Geom::PathBuilder &, Node *, Node *);
104 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
105 Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
106 : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
107 , _subpaths(*this)
108 , _multi_path_manipulator(mpm)
109 , _path(path)
110 , _spcurve(new SPCurve())
111 , _dragpoint(new CurveDragPoint(*this))
112 , /* XML Tree being used here directly while it shouldn't be*/_observer(new PathManipulatorObserver(this, SP_OBJECT(path)->getRepr()))
113 , _edit_transform(et)
114 , _num_selected(0)
115 , _show_handles(true)
116 , _show_outline(false)
117 , _show_path_direction(false)
118 , _live_outline(true)
119 , _live_objects(true)
120 , _lpe_key(lpe_key)
121 {
122 if (_lpe_key.empty()) {
123 _i2d_transform = SP_ITEM(path)->i2d_affine();
124 } else {
125 _i2d_transform = Geom::identity();
126 }
127 _d2i_transform = _i2d_transform.inverse();
128 _dragpoint->setVisible(false);
130 _getGeometry();
132 _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
133 sp_canvas_item_hide(_outline);
134 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
135 SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
136 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
138 _selection.signal_update.connect(
139 sigc::mem_fun(*this, &PathManipulator::update));
140 _selection.signal_point_changed.connect(
141 sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
142 _desktop->signal_zoom_changed.connect(
143 sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
145 _createControlPointsFromGeometry();
146 }
148 PathManipulator::~PathManipulator()
149 {
150 delete _dragpoint;
151 delete _observer;
152 gtk_object_destroy(_outline);
153 _spcurve->unref();
154 clear();
155 }
157 /** Handle motion events to update the position of the curve drag point. */
158 bool PathManipulator::event(GdkEvent *event)
159 {
160 if (empty()) return false;
162 switch (event->type)
163 {
164 case GDK_MOTION_NOTIFY:
165 _updateDragPoint(event_point(event->motion));
166 break;
167 default: break;
168 }
169 return false;
170 }
172 /** Check whether the manipulator has any nodes. */
173 bool PathManipulator::empty() {
174 return !_path || _subpaths.empty();
175 }
177 /** Update the display and the outline of the path. */
178 void PathManipulator::update()
179 {
180 _createGeometryFromControlPoints();
181 }
183 /** Store the changes to the path in XML. */
184 void PathManipulator::writeXML()
185 {
186 if (!_live_outline)
187 _updateOutline();
188 if (!_live_objects)
189 _setGeometry();
191 if (!_path) return;
192 _observer->block();
193 if (!empty()) {
194 SP_OBJECT(_path)->updateRepr();
195 _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
196 } else {
197 // this manipulator will have to be destroyed right after this call
198 _getXMLNode()->removeObserver(*_observer);
199 sp_object_ref(_path);
200 _path->deleteObject(true, true);
201 sp_object_unref(_path);
202 _path = 0;
203 }
204 _observer->unblock();
205 }
207 /** Remove all nodes from the path. */
208 void PathManipulator::clear()
209 {
210 // no longer necessary since nodes remove themselves from selection on destruction
211 //_removeNodesFromSelection();
212 _subpaths.clear();
213 }
215 /** Select all nodes in subpaths that have something selected. */
216 void PathManipulator::selectSubpaths()
217 {
218 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
219 NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
220 for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
221 if (j->selected()) {
222 // if at least one of the nodes from this subpath is selected,
223 // select all nodes from this subpath
224 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
225 _selection.insert(ins.ptr());
226 continue;
227 }
228 }
229 }
230 }
232 /** Invert selection in the selected subpaths. */
233 void PathManipulator::invertSelectionInSubpaths()
234 {
235 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
236 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
237 if (j->selected()) {
238 // found selected node - invert selection in this subpath
239 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
240 if (k->selected()) _selection.erase(k.ptr());
241 else _selection.insert(k.ptr());
242 }
243 // next subpath
244 break;
245 }
246 }
247 }
248 }
250 /** Insert a new node in the middle of each selected segment. */
251 void PathManipulator::insertNodes()
252 {
253 if (_num_selected < 2) return;
255 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
256 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
257 NodeList::iterator k = j.next();
258 if (k && j->selected() && k->selected()) {
259 j = subdivideSegment(j, 0.5);
260 _selection.insert(j.ptr());
261 }
262 }
263 }
264 }
266 /** Insert new nodes exactly at the positions of selected nodes while preserving shape.
267 * This is equivalent to breaking, except that it doesn't split into subpaths. */
268 void PathManipulator::duplicateNodes()
269 {
270 if (_num_selected == 0) return;
272 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
273 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
274 if (j->selected()) {
275 NodeList::iterator k = j.next();
276 Node *n = new Node(_multi_path_manipulator._path_data.node_data, *j);
278 if (k) {
279 // Move the new node to the bottom of the Z-order. This way you can drag all
280 // nodes that were selected before this operation without deselecting
281 // everything because there is a new node above.
282 n->sink();
283 }
285 n->front()->setPosition(*j->front());
286 j->front()->retract();
287 j->setType(NODE_CUSP, false);
288 (*i)->insert(k, n);
290 if (k) {
291 // We need to manually call the selection change callback to refresh
292 // the handle display correctly.
293 // This call changes num_selected, but we call this once for a selected node
294 // and once for an unselected node, so in the end the number stays correct.
295 _selectionChanged(j.ptr(), true);
296 _selectionChanged(n, false);
297 } else {
298 // select the new end node instead of the node just before it
299 _selection.erase(j.ptr());
300 _selection.insert(n);
301 break; // this was the end node, nothing more to do
302 }
303 }
304 }
305 }
306 }
308 /** Replace contiguous selections of nodes in each subpath with one node. */
309 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
310 {
311 if (_num_selected < 2) return;
312 hideDragPoint();
314 bool pos_valid = preserve_pos;
315 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
316 SubpathPtr sp = *i;
317 unsigned num_selected = 0, num_unselected = 0;
318 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
319 if (j->selected()) ++num_selected;
320 else ++num_unselected;
321 }
322 if (num_selected < 2) continue;
323 if (num_unselected == 0) {
324 // if all nodes in a subpath are selected, the operation doesn't make much sense
325 continue;
326 }
328 // Start from unselected node in closed paths, so that we don't start in the middle
329 // of a selection
330 NodeList::iterator sel_beg = sp->begin(), sel_end;
331 if (sp->closed()) {
332 while (sel_beg->selected()) ++sel_beg;
333 }
335 // Work loop
336 while (num_selected > 0) {
337 // Find selected node
338 while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
339 if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
340 "but there are still nodes to process!");
342 // note: this is initialized to zero, because the loop below counts sel_beg as well
343 // the loop conditions are simpler that way
344 unsigned num_points = 0;
345 bool use_pos = false;
346 Geom::Point back_pos, front_pos;
347 back_pos = *sel_beg->back();
349 for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
350 ++num_points;
351 front_pos = *sel_end->front();
352 if (pos_valid && sel_end == preserve_pos) use_pos = true;
353 }
354 if (num_points > 1) {
355 Geom::Point joined_pos;
356 if (use_pos) {
357 joined_pos = preserve_pos->position();
358 pos_valid = false;
359 } else {
360 joined_pos = Geom::middle_point(back_pos, front_pos);
361 }
362 sel_beg->setType(NODE_CUSP, false);
363 sel_beg->move(joined_pos);
364 // do not move handles if they aren't degenerate
365 if (!sel_beg->back()->isDegenerate()) {
366 sel_beg->back()->setPosition(back_pos);
367 }
368 if (!sel_end.prev()->front()->isDegenerate()) {
369 sel_beg->front()->setPosition(front_pos);
370 }
371 sel_beg = sel_beg.next();
372 while (sel_beg != sel_end) {
373 NodeList::iterator next = sel_beg.next();
374 sp->erase(sel_beg);
375 sel_beg = next;
376 --num_selected;
377 }
378 }
379 --num_selected; // for the joined node or single selected node
380 }
381 }
382 }
384 /** Remove nodes in the middle of selected segments. */
385 void PathManipulator::weldSegments()
386 {
387 if (_num_selected < 2) return;
388 hideDragPoint();
390 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
391 SubpathPtr sp = *i;
392 unsigned num_selected = 0, num_unselected = 0;
393 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
394 if (j->selected()) ++num_selected;
395 else ++num_unselected;
396 }
397 if (num_selected < 3) continue;
398 if (num_unselected == 0 && sp->closed()) {
399 // if all nodes in a closed subpath are selected, the operation doesn't make much sense
400 continue;
401 }
403 // Start from unselected node in closed paths, so that we don't start in the middle
404 // of a selection
405 NodeList::iterator sel_beg = sp->begin(), sel_end;
406 if (sp->closed()) {
407 while (sel_beg->selected()) ++sel_beg;
408 }
410 // Work loop
411 while (num_selected > 0) {
412 // Find selected node
413 while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
414 if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
415 "but there are still nodes to process!");
417 // note: this is initialized to zero, because the loop below counts sel_beg as well
418 // the loop conditions are simpler that way
419 unsigned num_points = 0;
421 // find the end of selected segment
422 for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
423 ++num_points;
424 }
425 if (num_points > 2) {
426 // remove nodes in the middle
427 sel_beg = sel_beg.next();
428 while (sel_beg != sel_end.prev()) {
429 NodeList::iterator next = sel_beg.next();
430 sp->erase(sel_beg);
431 sel_beg = next;
432 }
433 sel_beg = sel_end;
434 }
435 num_selected -= num_points;
436 }
437 }
438 }
440 /** Break the subpath at selected nodes. It also works for single node closed paths. */
441 void PathManipulator::breakNodes()
442 {
443 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
444 SubpathPtr sp = *i;
445 NodeList::iterator cur = sp->begin(), end = sp->end();
446 if (!sp->closed()) {
447 // Each open path must have at least two nodes so no checks are required.
448 // For 2-node open paths, cur == end
449 ++cur;
450 --end;
451 }
452 for (; cur != end; ++cur) {
453 if (!cur->selected()) continue;
454 SubpathPtr ins;
455 bool becomes_open = false;
457 if (sp->closed()) {
458 // Move the node to break at to the beginning of path
459 if (cur != sp->begin())
460 sp->splice(sp->begin(), *sp, cur, sp->end());
461 sp->setClosed(false);
462 ins = sp;
463 becomes_open = true;
464 } else {
465 SubpathPtr new_sp(new NodeList(_subpaths));
466 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
467 _subpaths.insert(i, new_sp);
468 ins = new_sp;
469 }
471 Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
472 ins->insert(ins->end(), n);
473 cur->setType(NODE_CUSP, false);
474 n->back()->setRelativePos(cur->back()->relativePos());
475 cur->back()->retract();
476 n->sink();
478 if (becomes_open) {
479 cur = sp->begin(); // this will be increased to ++sp->begin()
480 end = --sp->end();
481 }
482 }
483 }
484 }
486 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
487 * in a way that attempts to preserve the original shape of the curve. */
488 void PathManipulator::deleteNodes(bool keep_shape)
489 {
490 if (_num_selected == 0) return;
491 hideDragPoint();
493 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
494 SubpathPtr sp = *i;
496 // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
497 // in a closed one, delete entire subpath.
498 unsigned num_unselected = 0, num_selected = 0;
499 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
500 if (j->selected()) ++num_selected;
501 else ++num_unselected;
502 }
503 if (num_selected == 0) {
504 ++i;
505 continue;
506 }
507 if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
508 _subpaths.erase(i++);
509 continue;
510 }
512 // In closed paths, start from an unselected node - otherwise we might start in the middle
513 // of a selected stretch and the resulting bezier fit would be suboptimal
514 NodeList::iterator sel_beg = sp->begin(), sel_end;
515 if (sp->closed()) {
516 while (sel_beg->selected()) ++sel_beg;
517 }
518 sel_end = sel_beg;
520 while (num_selected > 0) {
521 while (sel_beg && !sel_beg->selected()) {
522 sel_beg = sel_beg.next();
523 }
524 sel_end = sel_beg;
526 while (sel_end && sel_end->selected()) {
527 sel_end = sel_end.next();
528 }
530 num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
531 sel_beg = sel_end;
532 }
533 ++i;
534 }
535 }
537 /** @brief Delete nodes between the two iterators.
538 * The given range can cross the beginning of the subpath in closed subpaths.
539 * @param start Beginning of the range to delete
540 * @param end End of the range
541 * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
542 * the shape before deletion
543 * @return Number of deleted nodes */
544 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
545 {
546 unsigned const samples_per_segment = 10;
547 double const t_step = 1.0 / samples_per_segment;
549 unsigned del_len = 0;
550 for (NodeList::iterator i = start; i != end; i = i.next()) {
551 ++del_len;
552 }
553 if (del_len == 0) return 0;
555 // set surrounding node types to cusp if:
556 // 1. keep_shape is on, or
557 // 2. we are deleting at the end or beginning of an open path
558 if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
559 if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
561 if (keep_shape && start.prev() && end) {
562 unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
563 Geom::Point *bezier_data = new Geom::Point[num_samples];
564 Geom::Point result[4];
565 unsigned seg = 0;
567 for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
568 Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
569 for (unsigned s = 0; s < samples_per_segment; ++s) {
570 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
571 }
572 ++seg;
573 }
574 // Fill last point
575 bezier_data[num_samples - 1] = end->position();
576 // Compute replacement bezier curve
577 // TODO the fitting algorithm sucks - rewrite it to be awesome
578 bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
579 delete[] bezier_data;
581 start.prev()->front()->setPosition(result[1]);
582 end->back()->setPosition(result[2]);
583 }
585 // We can't use nl->erase(start, end), because it would break when the stretch
586 // crosses the beginning of a closed subpath
587 NodeList &nl = start->nodeList();
588 while (start != end) {
589 NodeList::iterator next = start.next();
590 nl.erase(start);
591 start = next;
592 }
594 return del_len;
595 }
597 /** Removes selected segments */
598 void PathManipulator::deleteSegments()
599 {
600 if (_num_selected == 0) return;
601 hideDragPoint();
603 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
604 SubpathPtr sp = *i;
605 bool has_unselected = false;
606 unsigned num_selected = 0;
607 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
608 if (j->selected()) {
609 ++num_selected;
610 } else {
611 has_unselected = true;
612 }
613 }
614 if (!has_unselected) {
615 _subpaths.erase(i++);
616 continue;
617 }
619 NodeList::iterator sel_beg = sp->begin();
620 if (sp->closed()) {
621 while (sel_beg && sel_beg->selected()) ++sel_beg;
622 }
623 while (num_selected > 0) {
624 if (!sel_beg->selected()) {
625 sel_beg = sel_beg.next();
626 continue;
627 }
628 NodeList::iterator sel_end = sel_beg;
629 unsigned num_points = 0;
630 while (sel_end && sel_end->selected()) {
631 sel_end = sel_end.next();
632 ++num_points;
633 }
634 if (num_points >= 2) {
635 // Retract end handles
636 sel_end.prev()->setType(NODE_CUSP, false);
637 sel_end.prev()->back()->retract();
638 sel_beg->setType(NODE_CUSP, false);
639 sel_beg->front()->retract();
640 if (sp->closed()) {
641 // In closed paths, relocate the beginning of the path to the last selected
642 // node and then unclose it. Remove the nodes from the first selected node
643 // to the new end of path.
644 if (sel_end.prev() != sp->begin())
645 sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
646 sp->setClosed(false);
647 sp->erase(sel_beg.next(), sp->end());
648 } else {
649 // for open paths:
650 // 1. At end or beginning, delete including the node on the end or beginning
651 // 2. In the middle, delete only inner nodes
652 if (sel_beg == sp->begin()) {
653 sp->erase(sp->begin(), sel_end.prev());
654 } else if (sel_end == sp->end()) {
655 sp->erase(sel_beg.next(), sp->end());
656 } else {
657 SubpathPtr new_sp(new NodeList(_subpaths));
658 new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
659 _subpaths.insert(i, new_sp);
660 if (sel_end.prev())
661 sp->erase(sp->begin(), sel_end.prev());
662 }
663 }
664 }
665 sel_beg = sel_end;
666 num_selected -= num_points;
667 }
668 ++i;
669 }
670 }
672 /** Reverse subpaths of the path.
673 * @param selected_only If true, only paths that have at least one selected node
674 * will be reversed. Otherwise all subpaths will be reversed. */
675 void PathManipulator::reverseSubpaths(bool selected_only)
676 {
677 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
678 if (selected_only) {
679 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
680 if (j->selected()) {
681 (*i)->reverse();
682 break; // continue with the next subpath
683 }
684 }
685 } else {
686 (*i)->reverse();
687 }
688 }
689 }
691 /** Make selected segments curves / lines. */
692 void PathManipulator::setSegmentType(SegmentType type)
693 {
694 if (_num_selected == 0) return;
695 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
696 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
697 NodeList::iterator k = j.next();
698 if (!(k && j->selected() && k->selected())) continue;
699 switch (type) {
700 case SEGMENT_STRAIGHT:
701 if (j->front()->isDegenerate() && k->back()->isDegenerate())
702 break;
703 j->front()->move(*j);
704 k->back()->move(*k);
705 break;
706 case SEGMENT_CUBIC_BEZIER:
707 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
708 break;
709 // move both handles to 1/3 of the line
710 j->front()->move(j->position() + (k->position() - j->position()) / 3);
711 k->back()->move(k->position() + (j->position() - k->position()) / 3);
712 break;
713 }
714 }
715 }
716 }
718 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
719 {
720 if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
721 n->setType(NODE_SMOOTH);
722 }
723 Handle *h = _chooseHandle(n, which);
724 double length_change;
726 if (pixel) {
727 length_change = 1.0 / _desktop->current_zoom() * dir;
728 } else {
729 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
730 length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
731 length_change *= dir;
732 }
734 Geom::Point relpos;
735 if (h->isDegenerate()) {
736 if (dir < 0) return;
737 Node *nh = n->nodeToward(h);
738 if (!nh) return;
739 relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
740 } else {
741 relpos = h->relativePos();
742 double rellen = relpos.length();
743 relpos *= ((rellen + length_change) / rellen);
744 }
745 h->setRelativePos(relpos);
746 update();
748 gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
749 _commit(_("Scale handle"), key);
750 }
752 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
753 {
754 if (n->type() != NODE_CUSP) {
755 n->setType(NODE_CUSP);
756 }
757 Handle *h = _chooseHandle(n, which);
758 if (h->isDegenerate()) return;
760 double angle;
761 if (pixel) {
762 // Rotate by "one pixel"
763 angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
764 } else {
765 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
766 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
767 angle = M_PI * dir / snaps;
768 }
770 h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
771 update();
772 gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
773 _commit(_("Rotate handle"), key);
774 }
776 Handle *PathManipulator::_chooseHandle(Node *n, int which)
777 {
778 NodeList::iterator i = NodeList::get_iterator(n);
779 Node *prev = i.prev().ptr();
780 Node *next = i.next().ptr();
782 // on an endnode, the remaining handle automatically wins
783 if (!next) return n->back();
784 if (!prev) return n->front();
786 // compare X coord ofline segments
787 Geom::Point npos = next->position();
788 Geom::Point ppos = prev->position();
789 if (which < 0) {
790 // pick left handle.
791 // we just swap the handles and pick the right handle below.
792 std::swap(npos, ppos);
793 }
795 if (npos[Geom::X] >= ppos[Geom::X]) {
796 return n->front();
797 } else {
798 return n->back();
799 }
800 }
802 /** Set the visibility of handles. */
803 void PathManipulator::showHandles(bool show)
804 {
805 if (show == _show_handles) return;
806 if (show) {
807 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
808 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
809 if (!j->selected()) continue;
810 j->showHandles(true);
811 if (j.prev()) j.prev()->showHandles(true);
812 if (j.next()) j.next()->showHandles(true);
813 }
814 }
815 } else {
816 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
817 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
818 j->showHandles(false);
819 }
820 }
821 }
822 _show_handles = show;
823 }
825 /** Set the visibility of outline. */
826 void PathManipulator::showOutline(bool show)
827 {
828 if (show == _show_outline) return;
829 _show_outline = show;
830 _updateOutline();
831 }
833 void PathManipulator::showPathDirection(bool show)
834 {
835 if (show == _show_path_direction) return;
836 _show_path_direction = show;
837 _updateOutline();
838 }
840 void PathManipulator::setLiveOutline(bool set)
841 {
842 _live_outline = set;
843 }
845 void PathManipulator::setLiveObjects(bool set)
846 {
847 _live_objects = set;
848 }
850 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
851 {
852 Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
853 _edit_transform = tnew;
854 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
855 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
856 j->transform(delta);
857 }
858 }
859 _createGeometryFromControlPoints();
860 }
862 /** Hide the curve drag point until the next motion event.
863 * This should be called at the beginning of every method that can delete nodes.
864 * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
865 void PathManipulator::hideDragPoint()
866 {
867 _dragpoint->setVisible(false);
868 _dragpoint->setIterator(NodeList::iterator());
869 }
871 /** Insert a node in the segment beginning with the supplied iterator,
872 * at the given time value */
873 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
874 {
875 if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
876 NodeList &list = NodeList::get(first);
877 NodeList::iterator second = first.next();
878 if (!second) throw std::invalid_argument("Subdivide after last node in open path");
880 // We need to insert the segment after 'first'. We can't simply use 'second'
881 // as the point of insertion, because when 'first' is the last node of closed path,
882 // the new node will be inserted as the first node instead.
883 NodeList::iterator insert_at = first;
884 ++insert_at;
886 NodeList::iterator inserted;
887 if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
888 // for a line segment, insert a cusp node
889 Node *n = new Node(_multi_path_manipulator._path_data.node_data,
890 Geom::lerp(t, first->position(), second->position()));
891 n->setType(NODE_CUSP, false);
892 inserted = list.insert(insert_at, n);
893 } else {
894 // build bezier curve and subdivide
895 Geom::CubicBezier temp(first->position(), first->front()->position(),
896 second->back()->position(), second->position());
897 std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
898 std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
900 // set new handle positions
901 Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
902 n->back()->setPosition(seg1[2]);
903 n->front()->setPosition(seg2[1]);
904 n->setType(NODE_SMOOTH, false);
905 inserted = list.insert(insert_at, n);
907 first->front()->move(seg1[1]);
908 second->back()->move(seg2[2]);
909 }
910 return inserted;
911 }
913 /** Find the node that is closest/farthest from the origin
914 * @param origin Point of reference
915 * @param search_selected Consider selected nodes
916 * @param search_unselected Consider unselected nodes
917 * @param closest If true, return closest node, if false, return farthest
918 * @return The matching node, or an empty iterator if none found
919 */
920 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
921 bool search_unselected, bool closest)
922 {
923 NodeList::iterator match;
924 double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
925 if (_num_selected == 0 && !search_unselected) return match;
927 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
928 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
929 if(j->selected()) {
930 if (!search_selected) continue;
931 } else {
932 if (!search_unselected) continue;
933 }
934 double dist = Geom::distance(*j, *origin);
935 bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
936 if (cond) {
937 match = j;
938 extr_dist = dist;
939 }
940 }
941 }
942 return match;
943 }
945 /** Called by the XML observer when something else than us modifies the path. */
946 void PathManipulator::_externalChange(unsigned type)
947 {
948 hideDragPoint();
950 switch (type) {
951 case PATH_CHANGE_D: {
952 _getGeometry();
954 // ugly: stored offsets of selected nodes in a vector
955 // vector<bool> should be specialized so that it takes only 1 bit per value
956 std::vector<bool> selpos;
957 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
958 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
959 selpos.push_back(j->selected());
960 }
961 }
962 unsigned size = selpos.size(), curpos = 0;
964 _createControlPointsFromGeometry();
966 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
967 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
968 if (curpos >= size) goto end_restore;
969 if (selpos[curpos]) _selection.insert(j.ptr());
970 ++curpos;
971 }
972 }
973 end_restore:
975 _updateOutline();
976 } break;
977 case PATH_CHANGE_TRANSFORM: {
978 Geom::Matrix i2d_change = _d2i_transform;
979 _i2d_transform = SP_ITEM(_path)->i2d_affine();
980 _d2i_transform = _i2d_transform.inverse();
981 i2d_change *= _i2d_transform;
982 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
983 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
984 j->transform(i2d_change);
985 }
986 }
987 _updateOutline();
988 } break;
989 default: break;
990 }
991 }
993 /** Create nodes and handles based on the XML of the edited path. */
994 void PathManipulator::_createControlPointsFromGeometry()
995 {
996 clear();
998 // sanitize pathvector and store it in SPCurve,
999 // so that _updateDragPoint doesn't crash on paths with naked movetos
1000 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1001 for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1002 // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1003 // When we erase an element, the next one slides into position,
1004 // so we do not increment the iterator even though it is theoretically invalidated.
1005 if (i->empty()) {
1006 pathv.erase(i);
1007 } else {
1008 ++i;
1009 }
1010 }
1011 _spcurve->set_pathvector(pathv);
1013 pathv *= (_edit_transform * _i2d_transform);
1015 // in this loop, we know that there are no zero-segment subpaths
1016 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1017 // prepare new subpath
1018 SubpathPtr subpath(new NodeList(_subpaths));
1019 _subpaths.push_back(subpath);
1021 Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1022 subpath->push_back(previous_node);
1023 Geom::Curve const &cseg = pit->back_closed();
1024 bool fuse_ends = pit->closed()
1025 && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1027 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1028 Geom::Point pos = cit->finalPoint();
1029 Node *current_node;
1030 // if the closing segment is degenerate and the path is closed, we need to move
1031 // the handle of the first node instead of creating a new one
1032 if (fuse_ends && cit == --(pit->end_open())) {
1033 current_node = subpath->begin().get_pointer();
1034 } else {
1035 /* regardless of segment type, create a new node at the end
1036 * of this segment (unless this is the last segment of a closed path
1037 * with a degenerate closing segment */
1038 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1039 subpath->push_back(current_node);
1040 }
1041 // if this is a bezier segment, move handles appropriately
1042 if (Geom::CubicBezier const *cubic_bezier =
1043 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1044 {
1045 std::vector<Geom::Point> points = cubic_bezier->points();
1047 previous_node->front()->setPosition(points[1]);
1048 current_node ->back() ->setPosition(points[2]);
1049 }
1050 previous_node = current_node;
1051 }
1052 // If the path is closed, make the list cyclic
1053 if (pit->closed()) subpath->setClosed(true);
1054 }
1056 // we need to set the nodetypes after all the handles are in place,
1057 // so that pickBestType works correctly
1058 // TODO maybe migrate to inkscape:node-types?
1059 // TODO move this into SPPath - do not manipulate directly
1061 //XML Tree being used here directly while it shouldn't be.
1062 gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : 0;
1063 std::string nodetype_string = nts_raw ? nts_raw : "";
1064 /* Calculate the needed length of the nodetype string.
1065 * For closed paths, the entry is duplicated for the starting node,
1066 * so we can just use the count of segments including the closing one
1067 * to include the extra end node. */
1068 std::string::size_type nodetype_len = 0;
1069 for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1070 if (i->empty()) continue;
1071 nodetype_len += i->size_closed();
1072 }
1073 /* pad the string to required length with a bogus value.
1074 * 'b' and any other letter not recognized by the parser causes the best fit to be set
1075 * as the node type */
1076 if (nodetype_len > nodetype_string.size()) {
1077 nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1078 }
1079 std::string::iterator tsi = nodetype_string.begin();
1080 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1081 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1082 j->setType(Node::parse_nodetype(*tsi++), false);
1083 }
1084 if ((*i)->closed()) {
1085 // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1086 // the first one to remain backward compatible.
1087 (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1088 }
1089 }
1090 }
1092 /** Construct the geometric representation of nodes and handles, update the outline
1093 * and display */
1094 void PathManipulator::_createGeometryFromControlPoints()
1095 {
1096 Geom::PathBuilder builder;
1097 for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1098 SubpathPtr subpath = *spi;
1099 if (subpath->empty()) {
1100 _subpaths.erase(spi++);
1101 continue;
1102 }
1103 NodeList::iterator prev = subpath->begin();
1104 builder.moveTo(prev->position());
1106 for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1107 build_segment(builder, prev.ptr(), i.ptr());
1108 prev = i;
1109 }
1110 if (subpath->closed()) {
1111 // Here we link the last and first node if the path is closed.
1112 // If the last segment is Bezier, we add it.
1113 if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1114 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1115 }
1116 // if that segment is linear, we just call closePath().
1117 builder.closePath();
1118 }
1119 ++spi;
1120 }
1121 builder.finish();
1122 _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1123 if (_live_outline)
1124 _updateOutline();
1125 if (_live_objects)
1126 _setGeometry();
1127 }
1129 /** Build one segment of the geometric representation.
1130 * @relates PathManipulator */
1131 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1132 {
1133 if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1134 {
1135 // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1136 // and trying to display a path using them results in funny artifacts.
1137 builder.lineTo(cur_node->position());
1138 } else {
1139 // this is a bezier segment
1140 builder.curveTo(
1141 prev_node->front()->position(),
1142 cur_node->back()->position(),
1143 cur_node->position());
1144 }
1145 }
1147 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1148 std::string PathManipulator::_createTypeString()
1149 {
1150 // precondition: no single-node subpaths
1151 std::stringstream tstr;
1152 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1153 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1154 tstr << j->type();
1155 }
1156 // nodestring format peculiarity: first node is counted twice for closed paths
1157 if ((*i)->closed()) tstr << (*i)->begin()->type();
1158 }
1159 return tstr.str();
1160 }
1162 /** Update the path outline. */
1163 void PathManipulator::_updateOutline()
1164 {
1165 if (!_show_outline) {
1166 sp_canvas_item_hide(_outline);
1167 return;
1168 }
1170 Geom::PathVector pv = _spcurve->get_pathvector();
1171 pv *= (_edit_transform * _i2d_transform);
1172 // This SPCurve thing has to be killed with extreme prejudice
1173 SPCurve *_hc = new SPCurve();
1174 if (_show_path_direction) {
1175 // To show the direction, we append additional subpaths which consist of a single
1176 // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1177 // at an angle 150 degrees from the unit tangent. This creates the appearance
1178 // of little 'harpoons' that show the direction of the subpaths.
1179 Geom::PathVector arrows;
1180 for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1181 Geom::Path &path = *i;
1182 for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1183 Geom::Point at = j->pointAt(0.5);
1184 Geom::Point ut = j->unitTangentAt(0.5);
1185 // rotate the point
1186 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1187 Geom::Point arrow_end = _desktop->w2d(
1188 _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1190 Geom::Path arrow(at);
1191 arrow.appendNew<Geom::LineSegment>(arrow_end);
1192 arrows.push_back(arrow);
1193 }
1194 }
1195 pv.insert(pv.end(), arrows.begin(), arrows.end());
1196 }
1197 _hc->set_pathvector(pv);
1198 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1199 sp_canvas_item_show(_outline);
1200 _hc->unref();
1201 }
1203 /** Retrieve the geometry of the edited object from the object tree */
1204 void PathManipulator::_getGeometry()
1205 {
1206 using namespace Inkscape::LivePathEffect;
1207 if (!_lpe_key.empty()) {
1208 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1209 if (lpe) {
1210 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1211 _spcurve->unref();
1212 _spcurve = new SPCurve(pathparam->get_pathvector());
1213 }
1214 } else {
1215 _spcurve->unref();
1216 _spcurve = sp_path_get_curve_for_edit(_path);
1217 }
1218 }
1220 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1221 void PathManipulator::_setGeometry()
1222 {
1223 using namespace Inkscape::LivePathEffect;
1224 if (empty()) return;
1226 if (!_lpe_key.empty()) {
1227 // copied from nodepath.cpp
1228 // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1229 // a LivePathEffectObject. (mad laughter)
1230 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1231 if (lpe) {
1232 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1233 pathparam->set_new_value(_spcurve->get_pathvector(), false);
1234 LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1235 }
1236 } else {
1237 //XML Tree being used here directly while it shouldn't be.
1238 if (_path->getRepr()->attribute("inkscape:original-d"))
1239 sp_path_set_original_curve(_path, _spcurve, false, false);
1240 else
1241 SP_SHAPE(_path)->setCurve(_spcurve, false);
1242 }
1243 }
1245 /** Figure out in what attribute to store the nodetype string. */
1246 Glib::ustring PathManipulator::_nodetypesKey()
1247 {
1248 if (_lpe_key.empty()) return "sodipodi:nodetypes";
1249 return _lpe_key + "-nodetypes";
1250 }
1252 /** Return the XML node we are editing.
1253 * This method is wrong but necessary at the moment. */
1254 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1255 {
1256 //XML Tree being used here directly while it shouldn't be.
1257 if (_lpe_key.empty()) return _path->getRepr();
1258 //XML Tree being used here directly while it shouldn't be.
1259 return LIVEPATHEFFECT(_path)->getRepr();
1260 }
1262 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1263 {
1264 if (event->button != 1) return false;
1265 if (held_alt(*event) && held_control(*event)) {
1266 // Ctrl+Alt+click: delete nodes
1267 hideDragPoint();
1268 NodeList::iterator iter = NodeList::get_iterator(n);
1269 NodeList &nl = iter->nodeList();
1271 if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1272 // Removing last node of closed path - delete it
1273 nl.kill();
1274 } else {
1275 // In other cases, delete the node under cursor
1276 _deleteStretch(iter, iter.next(), true);
1277 }
1279 if (!empty()) {
1280 update();
1281 }
1282 // We need to call MPM's method because it could have been our last node
1283 _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1285 return true;
1286 } else if (held_control(*event)) {
1287 // Ctrl+click: cycle between node types
1288 if (!n->isEndNode()) {
1289 n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1290 update();
1291 _commit(_("Cycle node type"));
1292 }
1293 return true;
1294 }
1295 return false;
1296 }
1298 void PathManipulator::_handleGrabbed()
1299 {
1300 _selection.hideTransformHandles();
1301 }
1303 void PathManipulator::_handleUngrabbed()
1304 {
1305 _selection.restoreTransformHandles();
1306 _commit(_("Drag handle"));
1307 }
1309 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1310 {
1311 // retracting by Ctrl+click
1312 if (event->button == 1 && held_control(*event)) {
1313 h->move(h->parent()->position());
1314 update();
1315 _commit(_("Retract handle"));
1316 return true;
1317 }
1318 return false;
1319 }
1321 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1322 {
1323 if (selected) ++_num_selected;
1324 else --_num_selected;
1326 // don't do anything if we do not show handles
1327 if (!_show_handles) return;
1329 // only do something if a node changed selection state
1330 Node *node = dynamic_cast<Node*>(p);
1331 if (!node) return;
1333 // update handle display
1334 NodeList::iterator iters[5];
1335 iters[2] = NodeList::get_iterator(node);
1336 iters[1] = iters[2].prev();
1337 iters[3] = iters[2].next();
1338 if (selected) {
1339 // selection - show handles on this node and adjacent ones
1340 node->showHandles(true);
1341 if (iters[1]) iters[1]->showHandles(true);
1342 if (iters[3]) iters[3]->showHandles(true);
1343 } else {
1344 /* Deselection is more complex.
1345 * The change might affect 3 nodes - this one and two adjacent.
1346 * If the node and both its neighbors are deselected, hide handles.
1347 * Otherwise, leave as is. */
1348 if (iters[1]) iters[0] = iters[1].prev();
1349 if (iters[3]) iters[4] = iters[3].next();
1350 bool nodesel[5];
1351 for (int i = 0; i < 5; ++i) {
1352 nodesel[i] = iters[i] && iters[i]->selected();
1353 }
1354 for (int i = 1; i < 4; ++i) {
1355 if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1356 iters[i]->showHandles(false);
1357 }
1358 }
1359 }
1360 }
1362 /** Removes all nodes belonging to this manipulator from the control pont selection */
1363 void PathManipulator::_removeNodesFromSelection()
1364 {
1365 // remove this manipulator's nodes from selection
1366 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1367 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1368 _selection.erase(j.get_pointer());
1369 }
1370 }
1371 }
1373 /** Update the XML representation and put the specified annotation on the undo stack */
1374 void PathManipulator::_commit(Glib::ustring const &annotation)
1375 {
1376 writeXML();
1377 DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1378 }
1380 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1381 {
1382 writeXML();
1383 DocumentUndo::maybeDone(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1384 annotation.data());
1385 }
1387 /** Update the position of the curve drag point such that it is over the nearest
1388 * point of the path. */
1389 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1390 {
1391 Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1392 Geom::PathVector pv = _spcurve->get_pathvector();
1393 boost::optional<Geom::PathVectorPosition> pvp
1394 = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1395 if (!pvp) return;
1396 Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1398 double fracpart;
1399 std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1400 for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1401 NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1403 double stroke_tolerance = _getStrokeTolerance();
1404 if (first && first.next() &&
1405 fracpart != 0.0 &&
1406 Geom::distance(evp, nearest_point) < stroke_tolerance)
1407 {
1408 _dragpoint->setVisible(true);
1409 _dragpoint->setPosition(_desktop->w2d(nearest_point));
1410 _dragpoint->setSize(2 * stroke_tolerance);
1411 _dragpoint->setTimeValue(fracpart);
1412 _dragpoint->setIterator(first);
1413 } else {
1414 _dragpoint->setVisible(false);
1415 }
1416 }
1418 /// This is called on zoom change to update the direction arrows
1419 void PathManipulator::_updateOutlineOnZoomChange()
1420 {
1421 if (_show_path_direction) _updateOutline();
1422 }
1424 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1425 * or segment selection, in window coordinates. */
1426 double PathManipulator::_getStrokeTolerance()
1427 {
1428 /* Stroke event tolerance is equal to half the stroke's width plus the global
1429 * drag tolerance setting. */
1430 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1431 double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1432 if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1433 ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1434 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1435 * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1436 }
1437 return ret;
1438 }
1440 } // namespace UI
1441 } // namespace Inkscape
1443 /*
1444 Local Variables:
1445 mode:c++
1446 c-file-style:"stroustrup"
1447 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1448 indent-tabs-mode:nil
1449 fill-column:99
1450 End:
1451 */
1452 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :