f5c27e1d6ea80ac1ea2db289aedcd257a93f135c
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 // move both handles to 1/3 of the line
724 j->front()->move(j->position() + (k->position() - j->position()) / 3);
725 k->back()->move(k->position() + (j->position() - k->position()) / 3);
726 break;
727 }
728 }
729 }
730 }
732 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
733 {
734 if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
735 n->setType(NODE_SMOOTH);
736 }
737 Handle *h = _chooseHandle(n, which);
738 double length_change;
740 if (pixel) {
741 length_change = 1.0 / _desktop->current_zoom() * dir;
742 } else {
743 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
744 length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
745 length_change *= dir;
746 }
748 Geom::Point relpos;
749 if (h->isDegenerate()) {
750 if (dir < 0) return;
751 Node *nh = n->nodeToward(h);
752 if (!nh) return;
753 relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
754 } else {
755 relpos = h->relativePos();
756 double rellen = relpos.length();
757 relpos *= ((rellen + length_change) / rellen);
758 }
759 h->setRelativePos(relpos);
760 update();
762 gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
763 _commit(_("Scale handle"), key);
764 }
766 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
767 {
768 if (n->type() != NODE_CUSP) {
769 n->setType(NODE_CUSP);
770 }
771 Handle *h = _chooseHandle(n, which);
772 if (h->isDegenerate()) return;
774 double angle;
775 if (pixel) {
776 // Rotate by "one pixel"
777 angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
778 } else {
779 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
780 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
781 angle = M_PI * dir / snaps;
782 }
784 h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
785 update();
786 gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
787 _commit(_("Rotate handle"), key);
788 }
790 Handle *PathManipulator::_chooseHandle(Node *n, int which)
791 {
792 NodeList::iterator i = NodeList::get_iterator(n);
793 Node *prev = i.prev().ptr();
794 Node *next = i.next().ptr();
796 // on an endnode, the remaining handle automatically wins
797 if (!next) return n->back();
798 if (!prev) return n->front();
800 // compare X coord ofline segments
801 Geom::Point npos = next->position();
802 Geom::Point ppos = prev->position();
803 if (which < 0) {
804 // pick left handle.
805 // we just swap the handles and pick the right handle below.
806 std::swap(npos, ppos);
807 }
809 if (npos[Geom::X] >= ppos[Geom::X]) {
810 return n->front();
811 } else {
812 return n->back();
813 }
814 }
816 /** Set the visibility of handles. */
817 void PathManipulator::showHandles(bool show)
818 {
819 if (show == _show_handles) return;
820 if (show) {
821 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
822 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
823 if (!j->selected()) continue;
824 j->showHandles(true);
825 if (j.prev()) j.prev()->showHandles(true);
826 if (j.next()) j.next()->showHandles(true);
827 }
828 }
829 } else {
830 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
831 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
832 j->showHandles(false);
833 }
834 }
835 }
836 _show_handles = show;
837 }
839 /** Set the visibility of outline. */
840 void PathManipulator::showOutline(bool show)
841 {
842 if (show == _show_outline) return;
843 _show_outline = show;
844 _updateOutline();
845 }
847 void PathManipulator::showPathDirection(bool show)
848 {
849 if (show == _show_path_direction) return;
850 _show_path_direction = show;
851 _updateOutline();
852 }
854 void PathManipulator::setLiveOutline(bool set)
855 {
856 _live_outline = set;
857 }
859 void PathManipulator::setLiveObjects(bool set)
860 {
861 _live_objects = set;
862 }
864 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
865 {
866 Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
867 _edit_transform = tnew;
868 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
869 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
870 j->transform(delta);
871 }
872 }
873 _createGeometryFromControlPoints();
874 }
876 /** Hide the curve drag point until the next motion event.
877 * This should be called at the beginning of every method that can delete nodes.
878 * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
879 void PathManipulator::hideDragPoint()
880 {
881 _dragpoint->setVisible(false);
882 _dragpoint->setIterator(NodeList::iterator());
883 }
885 /** Insert a node in the segment beginning with the supplied iterator,
886 * at the given time value */
887 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
888 {
889 if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
890 NodeList &list = NodeList::get(first);
891 NodeList::iterator second = first.next();
892 if (!second) throw std::invalid_argument("Subdivide after last node in open path");
894 // We need to insert the segment after 'first'. We can't simply use 'second'
895 // as the point of insertion, because when 'first' is the last node of closed path,
896 // the new node will be inserted as the first node instead.
897 NodeList::iterator insert_at = first;
898 ++insert_at;
900 NodeList::iterator inserted;
901 if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
902 // for a line segment, insert a cusp node
903 Node *n = new Node(_multi_path_manipulator._path_data.node_data,
904 Geom::lerp(t, first->position(), second->position()));
905 n->setType(NODE_CUSP, false);
906 inserted = list.insert(insert_at, n);
907 } else {
908 // build bezier curve and subdivide
909 Geom::CubicBezier temp(first->position(), first->front()->position(),
910 second->back()->position(), second->position());
911 std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
912 std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
914 // set new handle positions
915 Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
916 n->back()->setPosition(seg1[2]);
917 n->front()->setPosition(seg2[1]);
918 n->setType(NODE_SMOOTH, false);
919 inserted = list.insert(insert_at, n);
921 first->front()->move(seg1[1]);
922 second->back()->move(seg2[2]);
923 }
924 return inserted;
925 }
927 /** Find the node that is closest/farthest from the origin
928 * @param origin Point of reference
929 * @param search_selected Consider selected nodes
930 * @param search_unselected Consider unselected nodes
931 * @param closest If true, return closest node, if false, return farthest
932 * @return The matching node, or an empty iterator if none found
933 */
934 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
935 bool search_unselected, bool closest)
936 {
937 NodeList::iterator match;
938 double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
939 if (_num_selected == 0 && !search_unselected) return match;
941 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
942 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
943 if(j->selected()) {
944 if (!search_selected) continue;
945 } else {
946 if (!search_unselected) continue;
947 }
948 double dist = Geom::distance(*j, *origin);
949 bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
950 if (cond) {
951 match = j;
952 extr_dist = dist;
953 }
954 }
955 }
956 return match;
957 }
959 /** Called by the XML observer when something else than us modifies the path. */
960 void PathManipulator::_externalChange(unsigned type)
961 {
962 switch (type) {
963 case PATH_CHANGE_D: {
964 _getGeometry();
966 // ugly: stored offsets of selected nodes in a vector
967 // vector<bool> should be specialized so that it takes only 1 bit per value
968 std::vector<bool> selpos;
969 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
970 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
971 selpos.push_back(j->selected());
972 }
973 }
974 unsigned size = selpos.size(), curpos = 0;
976 _createControlPointsFromGeometry();
978 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
979 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
980 if (curpos >= size) goto end_restore;
981 if (selpos[curpos]) _selection.insert(j.ptr());
982 ++curpos;
983 }
984 }
985 end_restore:
987 _updateOutline();
988 } break;
989 case PATH_CHANGE_TRANSFORM: {
990 Geom::Matrix i2d_change = _d2i_transform;
991 _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
992 _d2i_transform = _i2d_transform.inverse();
993 i2d_change *= _i2d_transform;
994 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
995 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
996 j->transform(i2d_change);
997 }
998 }
999 _updateOutline();
1000 } break;
1001 default: break;
1002 }
1003 }
1005 /** Create nodes and handles based on the XML of the edited path. */
1006 void PathManipulator::_createControlPointsFromGeometry()
1007 {
1008 clear();
1010 // sanitize pathvector and store it in SPCurve,
1011 // so that _updateDragPoint doesn't crash on paths with naked movetos
1012 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1013 for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1014 // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1015 // When we erase an element, the next one slides into position,
1016 // so we do not increment the iterator even though it is theoretically invalidated.
1017 if (i->empty()) {
1018 pathv.erase(i);
1019 } else {
1020 ++i;
1021 }
1022 }
1023 _spcurve->set_pathvector(pathv);
1025 pathv *= (_edit_transform * _i2d_transform);
1027 // in this loop, we know that there are no zero-segment subpaths
1028 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1029 // prepare new subpath
1030 SubpathPtr subpath(new NodeList(_subpaths));
1031 _subpaths.push_back(subpath);
1033 Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1034 subpath->push_back(previous_node);
1035 Geom::Curve const &cseg = pit->back_closed();
1036 bool fuse_ends = pit->closed()
1037 && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1039 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1040 Geom::Point pos = cit->finalPoint();
1041 Node *current_node;
1042 // if the closing segment is degenerate and the path is closed, we need to move
1043 // the handle of the first node instead of creating a new one
1044 if (fuse_ends && cit == --(pit->end_open())) {
1045 current_node = subpath->begin().get_pointer();
1046 } else {
1047 /* regardless of segment type, create a new node at the end
1048 * of this segment (unless this is the last segment of a closed path
1049 * with a degenerate closing segment */
1050 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1051 subpath->push_back(current_node);
1052 }
1053 // if this is a bezier segment, move handles appropriately
1054 if (Geom::CubicBezier const *cubic_bezier =
1055 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1056 {
1057 std::vector<Geom::Point> points = cubic_bezier->points();
1059 previous_node->front()->setPosition(points[1]);
1060 current_node ->back() ->setPosition(points[2]);
1061 }
1062 previous_node = current_node;
1063 }
1064 // If the path is closed, make the list cyclic
1065 if (pit->closed()) subpath->setClosed(true);
1066 }
1068 // we need to set the nodetypes after all the handles are in place,
1069 // so that pickBestType works correctly
1070 // TODO maybe migrate to inkscape:node-types?
1071 // TODO move this into SPPath - do not manipulate directly
1072 gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
1073 std::string nodetype_string = nts_raw ? nts_raw : "";
1074 /* Calculate the needed length of the nodetype string.
1075 * For closed paths, the entry is duplicated for the starting node,
1076 * so we can just use the count of segments including the closing one
1077 * to include the extra end node. */
1078 std::string::size_type nodetype_len = 0;
1079 for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1080 if (i->empty()) continue;
1081 nodetype_len += i->size_closed();
1082 }
1083 /* pad the string to required length with a bogus value.
1084 * 'b' and any other letter not recognized by the parser causes the best fit to be set
1085 * as the node type */
1086 if (nodetype_len > nodetype_string.size()) {
1087 nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1088 }
1089 std::string::iterator tsi = nodetype_string.begin();
1090 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1091 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1092 j->setType(Node::parse_nodetype(*tsi++), false);
1093 }
1094 if ((*i)->closed()) {
1095 // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1096 // the first one to remain backward compatible.
1097 (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1098 }
1099 }
1100 }
1102 /** Construct the geometric representation of nodes and handles, update the outline
1103 * and display */
1104 void PathManipulator::_createGeometryFromControlPoints()
1105 {
1106 Geom::PathBuilder builder;
1107 for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1108 SubpathPtr subpath = *spi;
1109 if (subpath->empty()) {
1110 _subpaths.erase(spi++);
1111 continue;
1112 }
1113 NodeList::iterator prev = subpath->begin();
1114 builder.moveTo(prev->position());
1116 for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1117 build_segment(builder, prev.ptr(), i.ptr());
1118 prev = i;
1119 }
1120 if (subpath->closed()) {
1121 // Here we link the last and first node if the path is closed.
1122 // If the last segment is Bezier, we add it.
1123 if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1124 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1125 }
1126 // if that segment is linear, we just call closePath().
1127 builder.closePath();
1128 }
1129 ++spi;
1130 }
1131 builder.finish();
1132 _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1133 if (_live_outline)
1134 _updateOutline();
1135 if (_live_objects)
1136 _setGeometry();
1137 }
1139 /** Build one segment of the geometric representation.
1140 * @relates PathManipulator */
1141 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1142 {
1143 if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1144 {
1145 // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1146 // and trying to display a path using them results in funny artifacts.
1147 builder.lineTo(cur_node->position());
1148 } else {
1149 // this is a bezier segment
1150 builder.curveTo(
1151 prev_node->front()->position(),
1152 cur_node->back()->position(),
1153 cur_node->position());
1154 }
1155 }
1157 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1158 std::string PathManipulator::_createTypeString()
1159 {
1160 // precondition: no single-node subpaths
1161 std::stringstream tstr;
1162 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1163 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1164 tstr << j->type();
1165 }
1166 // nodestring format peculiarity: first node is counted twice for closed paths
1167 if ((*i)->closed()) tstr << (*i)->begin()->type();
1168 }
1169 return tstr.str();
1170 }
1172 /** Update the path outline. */
1173 void PathManipulator::_updateOutline()
1174 {
1175 if (!_show_outline) {
1176 sp_canvas_item_hide(_outline);
1177 return;
1178 }
1180 Geom::PathVector pv = _spcurve->get_pathvector();
1181 pv *= (_edit_transform * _i2d_transform);
1182 // This SPCurve thing has to be killed with extreme prejudice
1183 SPCurve *_hc = new SPCurve();
1184 if (_show_path_direction) {
1185 // To show the direction, we append additional subpaths which consist of a single
1186 // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1187 // at an angle 150 degrees from the unit tangent. This creates the appearance
1188 // of little 'harpoons' that show the direction of the subpaths.
1189 Geom::PathVector arrows;
1190 for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1191 Geom::Path &path = *i;
1192 for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1193 Geom::Point at = j->pointAt(0.5);
1194 Geom::Point ut = j->unitTangentAt(0.5);
1195 // rotate the point
1196 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1197 Geom::Point arrow_end = _desktop->w2d(
1198 _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1200 Geom::Path arrow(at);
1201 arrow.appendNew<Geom::LineSegment>(arrow_end);
1202 arrows.push_back(arrow);
1203 }
1204 }
1205 pv.insert(pv.end(), arrows.begin(), arrows.end());
1206 }
1207 _hc->set_pathvector(pv);
1208 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1209 sp_canvas_item_show(_outline);
1210 _hc->unref();
1211 }
1213 /** Retrieve the geometry of the edited object from the object tree */
1214 void PathManipulator::_getGeometry()
1215 {
1216 using namespace Inkscape::LivePathEffect;
1217 if (!_lpe_key.empty()) {
1218 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1219 if (lpe) {
1220 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1221 _spcurve->unref();
1222 _spcurve = new SPCurve(pathparam->get_pathvector());
1223 }
1224 } else {
1225 _spcurve->unref();
1226 _spcurve = sp_path_get_curve_for_edit(_path);
1227 }
1228 }
1230 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1231 void PathManipulator::_setGeometry()
1232 {
1233 using namespace Inkscape::LivePathEffect;
1234 if (empty()) return;
1236 if (!_lpe_key.empty()) {
1237 // copied from nodepath.cpp
1238 // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1239 // a LivePathEffectObject. (mad laughter)
1240 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1241 if (lpe) {
1242 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1243 pathparam->set_new_value(_spcurve->get_pathvector(), false);
1244 LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1245 }
1246 } else {
1247 if (_path->repr->attribute("inkscape:original-d"))
1248 sp_path_set_original_curve(_path, _spcurve, false, false);
1249 else
1250 sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1251 }
1252 }
1254 /** Figure out in what attribute to store the nodetype string. */
1255 Glib::ustring PathManipulator::_nodetypesKey()
1256 {
1257 if (_lpe_key.empty()) return "sodipodi:nodetypes";
1258 return _lpe_key + "-nodetypes";
1259 }
1261 /** Return the XML node we are editing.
1262 * This method is wrong but necessary at the moment. */
1263 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1264 {
1265 if (_lpe_key.empty()) return _path->repr;
1266 return LIVEPATHEFFECT(_path)->repr;
1267 }
1269 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1270 {
1271 if (event->button != 1) return false;
1272 if (held_alt(*event) && held_control(*event)) {
1273 // Ctrl+Alt+click: delete nodes
1274 hideDragPoint();
1275 NodeList::iterator iter = NodeList::get_iterator(n);
1276 NodeList &nl = iter->nodeList();
1278 if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1279 // Removing last node of closed path - delete it
1280 nl.kill();
1281 } else {
1282 // In other cases, delete the node under cursor
1283 _deleteStretch(iter, iter.next(), true);
1284 }
1286 if (!empty()) {
1287 update();
1288 }
1289 // We need to call MPM's method because it could have been our last node
1290 _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1292 return true;
1293 } else if (held_control(*event)) {
1294 // Ctrl+click: cycle between node types
1295 if (n->isEndNode()) {
1296 if (n->type() == NODE_CUSP) {
1297 n->setType(NODE_SMOOTH);
1298 } else {
1299 n->setType(NODE_CUSP);
1300 }
1301 } else {
1302 n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1303 }
1304 update();
1305 _commit(_("Cycle node type"));
1306 return true;
1307 }
1308 return false;
1309 }
1311 void PathManipulator::_handleGrabbed()
1312 {
1313 _selection.hideTransformHandles();
1314 }
1316 void PathManipulator::_handleUngrabbed()
1317 {
1318 _selection.restoreTransformHandles();
1319 _commit(_("Drag handle"));
1320 }
1322 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1323 {
1324 // retracting by Ctrl+click
1325 if (event->button == 1 && held_control(*event)) {
1326 h->move(h->parent()->position());
1327 update();
1328 _commit(_("Retract handle"));
1329 return true;
1330 }
1331 return false;
1332 }
1334 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1335 {
1336 if (selected) ++_num_selected;
1337 else --_num_selected;
1339 // don't do anything if we do not show handles
1340 if (!_show_handles) return;
1342 // only do something if a node changed selection state
1343 Node *node = dynamic_cast<Node*>(p);
1344 if (!node) return;
1346 // update handle display
1347 NodeList::iterator iters[5];
1348 iters[2] = NodeList::get_iterator(node);
1349 iters[1] = iters[2].prev();
1350 iters[3] = iters[2].next();
1351 if (selected) {
1352 // selection - show handles on this node and adjacent ones
1353 node->showHandles(true);
1354 if (iters[1]) iters[1]->showHandles(true);
1355 if (iters[3]) iters[3]->showHandles(true);
1356 } else {
1357 /* Deselection is more complex.
1358 * The change might affect 3 nodes - this one and two adjacent.
1359 * If the node and both its neighbors are deselected, hide handles.
1360 * Otherwise, leave as is. */
1361 if (iters[1]) iters[0] = iters[1].prev();
1362 if (iters[3]) iters[4] = iters[3].next();
1363 bool nodesel[5];
1364 for (int i = 0; i < 5; ++i) {
1365 nodesel[i] = iters[i] && iters[i]->selected();
1366 }
1367 for (int i = 1; i < 4; ++i) {
1368 if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1369 iters[i]->showHandles(false);
1370 }
1371 }
1372 }
1373 }
1375 /** Removes all nodes belonging to this manipulator from the control pont selection */
1376 void PathManipulator::_removeNodesFromSelection()
1377 {
1378 // remove this manipulator's nodes from selection
1379 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1380 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1381 _selection.erase(j.get_pointer());
1382 }
1383 }
1384 }
1386 /** Update the XML representation and put the specified annotation on the undo stack */
1387 void PathManipulator::_commit(Glib::ustring const &annotation)
1388 {
1389 writeXML();
1390 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1391 }
1393 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1394 {
1395 writeXML();
1396 sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1397 annotation.data());
1398 }
1400 /** Update the position of the curve drag point such that it is over the nearest
1401 * point of the path. */
1402 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1403 {
1404 Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1405 Geom::PathVector pv = _spcurve->get_pathvector();
1406 boost::optional<Geom::PathVectorPosition> pvp
1407 = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1408 if (!pvp) return;
1409 Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1411 double fracpart;
1412 std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1413 for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1414 NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1416 double stroke_tolerance = _getStrokeTolerance();
1417 if (first && first.next() &&
1418 fracpart != 0.0 &&
1419 Geom::distance(evp, nearest_point) < stroke_tolerance)
1420 {
1421 _dragpoint->setVisible(true);
1422 _dragpoint->setPosition(_desktop->w2d(nearest_point));
1423 _dragpoint->setSize(2 * stroke_tolerance);
1424 _dragpoint->setTimeValue(fracpart);
1425 _dragpoint->setIterator(first);
1426 } else {
1427 _dragpoint->setVisible(false);
1428 }
1429 }
1431 /// This is called on zoom change to update the direction arrows
1432 void PathManipulator::_updateOutlineOnZoomChange()
1433 {
1434 if (_show_path_direction) _updateOutline();
1435 }
1437 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1438 * or segment selection, in window coordinates. */
1439 double PathManipulator::_getStrokeTolerance()
1440 {
1441 /* Stroke event tolerance is equal to half the stroke's width plus the global
1442 * drag tolerance setting. */
1443 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1444 double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1445 if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1446 ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1447 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1448 * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1449 }
1450 return ret;
1451 }
1453 } // namespace UI
1454 } // namespace Inkscape
1456 /*
1457 Local Variables:
1458 mode:c++
1459 c-file-style:"stroustrup"
1460 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1461 indent-tabs-mode:nil
1462 fill-column:99
1463 End:
1464 */
1465 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :