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