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