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 /** Insert new nodes exactly at the positions of selected nodes while preserving shape.
323 * This is equivalent to breaking, except that it doesn't split into subpaths. */
324 void PathManipulator::duplicateNodes()
325 {
326 if (_num_selected == 0) return;
328 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
329 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
330 if (j->selected()) {
331 NodeList::iterator k = j.next();
332 Node *n = new Node(_multi_path_manipulator._path_data.node_data, *j);
334 // Move the new node to the bottom of the Z-order. This way you can drag all
335 // nodes that were selected before this operation without deselecting
336 // everything because there is a new node above.
337 n->sink();
339 n->front()->setPosition(*j->front());
340 j->front()->retract();
341 j->setType(NODE_CUSP, false);
342 (*i)->insert(k, n);
344 // We need to manually call the selection change callback to refresh
345 // the handle display correctly.
346 // This call changes num_selected, but we call this once for a selected node
347 // and once for an unselected node, so in the end the number stays correct.
348 _selectionChanged(j.ptr(), true);
349 _selectionChanged(n, false);
350 }
351 }
352 }
353 }
355 /** Replace contiguous selections of nodes in each subpath with one node. */
356 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
357 {
358 if (_num_selected < 2) return;
359 hideDragPoint();
361 bool pos_valid = preserve_pos;
362 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
363 SubpathPtr sp = *i;
364 unsigned num_selected = 0, num_unselected = 0;
365 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
366 if (j->selected()) ++num_selected;
367 else ++num_unselected;
368 }
369 if (num_selected < 2) continue;
370 if (num_unselected == 0) {
371 // if all nodes in a subpath are selected, the operation doesn't make much sense
372 continue;
373 }
375 // Start from unselected node in closed paths, so that we don't start in the middle
376 // of a selection
377 NodeList::iterator sel_beg = sp->begin(), sel_end;
378 if (sp->closed()) {
379 while (sel_beg->selected()) ++sel_beg;
380 }
382 // Work loop
383 while (num_selected > 0) {
384 // Find selected node
385 while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
386 if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
387 "but there are still nodes to process!");
389 // note: this is initialized to zero, because the loop below counts sel_beg as well
390 // the loop conditions are simpler that way
391 unsigned num_points = 0;
392 bool use_pos = false;
393 Geom::Point back_pos, front_pos;
394 back_pos = *sel_beg->back();
396 for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
397 ++num_points;
398 front_pos = *sel_end->front();
399 if (pos_valid && sel_end == preserve_pos) use_pos = true;
400 }
401 if (num_points > 1) {
402 Geom::Point joined_pos;
403 if (use_pos) {
404 joined_pos = preserve_pos->position();
405 pos_valid = false;
406 } else {
407 joined_pos = Geom::middle_point(back_pos, front_pos);
408 }
409 sel_beg->setType(NODE_CUSP, false);
410 sel_beg->move(joined_pos);
411 // do not move handles if they aren't degenerate
412 if (!sel_beg->back()->isDegenerate()) {
413 sel_beg->back()->setPosition(back_pos);
414 }
415 if (!sel_end.prev()->front()->isDegenerate()) {
416 sel_beg->front()->setPosition(front_pos);
417 }
418 sel_beg = sel_beg.next();
419 while (sel_beg != sel_end) {
420 NodeList::iterator next = sel_beg.next();
421 sp->erase(sel_beg);
422 sel_beg = next;
423 --num_selected;
424 }
425 }
426 --num_selected; // for the joined node or single selected node
427 }
428 }
429 }
431 /** Remove nodes in the middle of selected segments. */
432 void PathManipulator::weldSegments()
433 {
434 if (_num_selected < 2) return;
435 hideDragPoint();
437 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
438 SubpathPtr sp = *i;
439 unsigned num_selected = 0, num_unselected = 0;
440 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
441 if (j->selected()) ++num_selected;
442 else ++num_unselected;
443 }
444 if (num_selected < 3) continue;
445 if (num_unselected == 0 && sp->closed()) {
446 // if all nodes in a closed subpath are selected, the operation doesn't make much sense
447 continue;
448 }
450 // Start from unselected node in closed paths, so that we don't start in the middle
451 // of a selection
452 NodeList::iterator sel_beg = sp->begin(), sel_end;
453 if (sp->closed()) {
454 while (sel_beg->selected()) ++sel_beg;
455 }
457 // Work loop
458 while (num_selected > 0) {
459 // Find selected node
460 while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
461 if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
462 "but there are still nodes to process!");
464 // note: this is initialized to zero, because the loop below counts sel_beg as well
465 // the loop conditions are simpler that way
466 unsigned num_points = 0;
468 // find the end of selected segment
469 for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
470 ++num_points;
471 }
472 if (num_points > 2) {
473 // remove nodes in the middle
474 sel_beg = sel_beg.next();
475 while (sel_beg != sel_end.prev()) {
476 NodeList::iterator next = sel_beg.next();
477 sp->erase(sel_beg);
478 sel_beg = next;
479 }
480 sel_beg = sel_end;
481 }
482 num_selected -= num_points;
483 }
484 }
485 }
487 /** Break the subpath at selected nodes. It also works for single node closed paths. */
488 void PathManipulator::breakNodes()
489 {
490 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
491 SubpathPtr sp = *i;
492 NodeList::iterator cur = sp->begin(), end = sp->end();
493 if (!sp->closed()) {
494 // Each open path must have at least two nodes so no checks are required.
495 // For 2-node open paths, cur == end
496 ++cur;
497 --end;
498 }
499 for (; cur != end; ++cur) {
500 if (!cur->selected()) continue;
501 SubpathPtr ins;
502 bool becomes_open = false;
504 if (sp->closed()) {
505 // Move the node to break at to the beginning of path
506 if (cur != sp->begin())
507 sp->splice(sp->begin(), *sp, cur, sp->end());
508 sp->setClosed(false);
509 ins = sp;
510 becomes_open = true;
511 } else {
512 SubpathPtr new_sp(new NodeList(_subpaths));
513 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
514 _subpaths.insert(i, new_sp);
515 ins = new_sp;
516 }
518 Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
519 ins->insert(ins->end(), n);
520 cur->setType(NODE_CUSP, false);
521 n->back()->setRelativePos(cur->back()->relativePos());
522 cur->back()->retract();
523 n->sink();
525 if (becomes_open) {
526 cur = sp->begin(); // this will be increased to ++sp->begin()
527 end = --sp->end();
528 }
529 }
530 }
531 }
533 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
534 * in a way that attempts to preserve the original shape of the curve. */
535 void PathManipulator::deleteNodes(bool keep_shape)
536 {
537 if (_num_selected == 0) return;
538 hideDragPoint();
540 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
541 SubpathPtr sp = *i;
543 // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
544 // in a closed one, delete entire subpath.
545 unsigned num_unselected = 0, num_selected = 0;
546 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
547 if (j->selected()) ++num_selected;
548 else ++num_unselected;
549 }
550 if (num_selected == 0) {
551 ++i;
552 continue;
553 }
554 if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
555 _subpaths.erase(i++);
556 continue;
557 }
559 // In closed paths, start from an unselected node - otherwise we might start in the middle
560 // of a selected stretch and the resulting bezier fit would be suboptimal
561 NodeList::iterator sel_beg = sp->begin(), sel_end;
562 if (sp->closed()) {
563 while (sel_beg->selected()) ++sel_beg;
564 }
565 sel_end = sel_beg;
567 while (num_selected > 0) {
568 while (sel_beg && !sel_beg->selected()) {
569 sel_beg = sel_beg.next();
570 }
571 sel_end = sel_beg;
573 while (sel_end && sel_end->selected()) {
574 sel_end = sel_end.next();
575 }
577 num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
578 sel_beg = sel_end;
579 }
580 ++i;
581 }
582 }
584 /** @brief Delete nodes between the two iterators.
585 * The given range can cross the beginning of the subpath in closed subpaths.
586 * @param start Beginning of the range to delete
587 * @param end End of the range
588 * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
589 * the shape before deletion
590 * @return Number of deleted nodes */
591 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
592 {
593 unsigned const samples_per_segment = 10;
594 double const t_step = 1.0 / samples_per_segment;
596 unsigned del_len = 0;
597 for (NodeList::iterator i = start; i != end; i = i.next()) {
598 ++del_len;
599 }
600 if (del_len == 0) return 0;
602 // set surrounding node types to cusp if:
603 // 1. keep_shape is on, or
604 // 2. we are deleting at the end or beginning of an open path
605 if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
606 if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
608 if (keep_shape && start.prev() && end) {
609 unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
610 Geom::Point *bezier_data = new Geom::Point[num_samples];
611 Geom::Point result[4];
612 unsigned seg = 0;
614 for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
615 Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
616 for (unsigned s = 0; s < samples_per_segment; ++s) {
617 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
618 }
619 ++seg;
620 }
621 // Fill last point
622 bezier_data[num_samples - 1] = end->position();
623 // Compute replacement bezier curve
624 // TODO the fitting algorithm sucks - rewrite it to be awesome
625 bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
626 delete[] bezier_data;
628 start.prev()->front()->setPosition(result[1]);
629 end->back()->setPosition(result[2]);
630 }
632 // We can't use nl->erase(start, end), because it would break when the stretch
633 // crosses the beginning of a closed subpath
634 NodeList &nl = start->nodeList();
635 while (start != end) {
636 NodeList::iterator next = start.next();
637 nl.erase(start);
638 start = next;
639 }
641 return del_len;
642 }
644 /** Removes selected segments */
645 void PathManipulator::deleteSegments()
646 {
647 if (_num_selected == 0) return;
648 hideDragPoint();
650 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
651 SubpathPtr sp = *i;
652 bool has_unselected = false;
653 unsigned num_selected = 0;
654 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
655 if (j->selected()) {
656 ++num_selected;
657 } else {
658 has_unselected = true;
659 }
660 }
661 if (!has_unselected) {
662 _subpaths.erase(i++);
663 continue;
664 }
666 NodeList::iterator sel_beg = sp->begin();
667 if (sp->closed()) {
668 while (sel_beg && sel_beg->selected()) ++sel_beg;
669 }
670 while (num_selected > 0) {
671 if (!sel_beg->selected()) {
672 sel_beg = sel_beg.next();
673 continue;
674 }
675 NodeList::iterator sel_end = sel_beg;
676 unsigned num_points = 0;
677 while (sel_end && sel_end->selected()) {
678 sel_end = sel_end.next();
679 ++num_points;
680 }
681 if (num_points >= 2) {
682 // Retract end handles
683 sel_end.prev()->setType(NODE_CUSP, false);
684 sel_end.prev()->back()->retract();
685 sel_beg->setType(NODE_CUSP, false);
686 sel_beg->front()->retract();
687 if (sp->closed()) {
688 // In closed paths, relocate the beginning of the path to the last selected
689 // node and then unclose it. Remove the nodes from the first selected node
690 // to the new end of path.
691 if (sel_end.prev() != sp->begin())
692 sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
693 sp->setClosed(false);
694 sp->erase(sel_beg.next(), sp->end());
695 } else {
696 // for open paths:
697 // 1. At end or beginning, delete including the node on the end or beginning
698 // 2. In the middle, delete only inner nodes
699 if (sel_beg == sp->begin()) {
700 sp->erase(sp->begin(), sel_end.prev());
701 } else if (sel_end == sp->end()) {
702 sp->erase(sel_beg.next(), sp->end());
703 } else {
704 SubpathPtr new_sp(new NodeList(_subpaths));
705 new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
706 _subpaths.insert(i, new_sp);
707 if (sel_end.prev())
708 sp->erase(sp->begin(), sel_end.prev());
709 }
710 }
711 }
712 sel_beg = sel_end;
713 num_selected -= num_points;
714 }
715 ++i;
716 }
717 }
719 /** Reverse subpaths of the path.
720 * @param selected_only If true, only paths that have at least one selected node
721 * will be reversed. Otherwise all subpaths will be reversed. */
722 void PathManipulator::reverseSubpaths(bool selected_only)
723 {
724 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
725 if (selected_only) {
726 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
727 if (j->selected()) {
728 (*i)->reverse();
729 break; // continue with the next subpath
730 }
731 }
732 } else {
733 (*i)->reverse();
734 }
735 }
736 }
738 /** Make selected segments curves / lines. */
739 void PathManipulator::setSegmentType(SegmentType type)
740 {
741 if (_num_selected == 0) return;
742 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
743 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
744 NodeList::iterator k = j.next();
745 if (!(k && j->selected() && k->selected())) continue;
746 switch (type) {
747 case SEGMENT_STRAIGHT:
748 if (j->front()->isDegenerate() && k->back()->isDegenerate())
749 break;
750 j->front()->move(*j);
751 k->back()->move(*k);
752 break;
753 case SEGMENT_CUBIC_BEZIER:
754 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
755 break;
756 // move both handles to 1/3 of the line
757 j->front()->move(j->position() + (k->position() - j->position()) / 3);
758 k->back()->move(k->position() + (j->position() - k->position()) / 3);
759 break;
760 }
761 }
762 }
763 }
765 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
766 {
767 if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
768 n->setType(NODE_SMOOTH);
769 }
770 Handle *h = _chooseHandle(n, which);
771 double length_change;
773 if (pixel) {
774 length_change = 1.0 / _desktop->current_zoom() * dir;
775 } else {
776 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
777 length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
778 length_change *= dir;
779 }
781 Geom::Point relpos;
782 if (h->isDegenerate()) {
783 if (dir < 0) return;
784 Node *nh = n->nodeToward(h);
785 if (!nh) return;
786 relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
787 } else {
788 relpos = h->relativePos();
789 double rellen = relpos.length();
790 relpos *= ((rellen + length_change) / rellen);
791 }
792 h->setRelativePos(relpos);
793 update();
795 gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
796 _commit(_("Scale handle"), key);
797 }
799 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
800 {
801 if (n->type() != NODE_CUSP) {
802 n->setType(NODE_CUSP);
803 }
804 Handle *h = _chooseHandle(n, which);
805 if (h->isDegenerate()) return;
807 double angle;
808 if (pixel) {
809 // Rotate by "one pixel"
810 angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
811 } else {
812 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
813 int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
814 angle = M_PI * dir / snaps;
815 }
817 h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
818 update();
819 gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
820 _commit(_("Rotate handle"), key);
821 }
823 Handle *PathManipulator::_chooseHandle(Node *n, int which)
824 {
825 NodeList::iterator i = NodeList::get_iterator(n);
826 Node *prev = i.prev().ptr();
827 Node *next = i.next().ptr();
829 // on an endnode, the remaining handle automatically wins
830 if (!next) return n->back();
831 if (!prev) return n->front();
833 // compare X coord ofline segments
834 Geom::Point npos = next->position();
835 Geom::Point ppos = prev->position();
836 if (which < 0) {
837 // pick left handle.
838 // we just swap the handles and pick the right handle below.
839 std::swap(npos, ppos);
840 }
842 if (npos[Geom::X] >= ppos[Geom::X]) {
843 return n->front();
844 } else {
845 return n->back();
846 }
847 }
849 /** Set the visibility of handles. */
850 void PathManipulator::showHandles(bool show)
851 {
852 if (show == _show_handles) return;
853 if (show) {
854 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
855 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
856 if (!j->selected()) continue;
857 j->showHandles(true);
858 if (j.prev()) j.prev()->showHandles(true);
859 if (j.next()) j.next()->showHandles(true);
860 }
861 }
862 } else {
863 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
864 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
865 j->showHandles(false);
866 }
867 }
868 }
869 _show_handles = show;
870 }
872 /** Set the visibility of outline. */
873 void PathManipulator::showOutline(bool show)
874 {
875 if (show == _show_outline) return;
876 _show_outline = show;
877 _updateOutline();
878 }
880 void PathManipulator::showPathDirection(bool show)
881 {
882 if (show == _show_path_direction) return;
883 _show_path_direction = show;
884 _updateOutline();
885 }
887 void PathManipulator::setLiveOutline(bool set)
888 {
889 _live_outline = set;
890 }
892 void PathManipulator::setLiveObjects(bool set)
893 {
894 _live_objects = set;
895 }
897 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
898 {
899 Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
900 _edit_transform = tnew;
901 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
902 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
903 j->transform(delta);
904 }
905 }
906 _createGeometryFromControlPoints();
907 }
909 /** Hide the curve drag point until the next motion event.
910 * This should be called at the beginning of every method that can delete nodes.
911 * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
912 void PathManipulator::hideDragPoint()
913 {
914 _dragpoint->setVisible(false);
915 _dragpoint->setIterator(NodeList::iterator());
916 }
918 /** Insert a node in the segment beginning with the supplied iterator,
919 * at the given time value */
920 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
921 {
922 if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
923 NodeList &list = NodeList::get(first);
924 NodeList::iterator second = first.next();
925 if (!second) throw std::invalid_argument("Subdivide after last node in open path");
927 // We need to insert the segment after 'first'. We can't simply use 'second'
928 // as the point of insertion, because when 'first' is the last node of closed path,
929 // the new node will be inserted as the first node instead.
930 NodeList::iterator insert_at = first;
931 ++insert_at;
933 NodeList::iterator inserted;
934 if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
935 // for a line segment, insert a cusp node
936 Node *n = new Node(_multi_path_manipulator._path_data.node_data,
937 Geom::lerp(t, first->position(), second->position()));
938 n->setType(NODE_CUSP, false);
939 inserted = list.insert(insert_at, n);
940 } else {
941 // build bezier curve and subdivide
942 Geom::CubicBezier temp(first->position(), first->front()->position(),
943 second->back()->position(), second->position());
944 std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
945 std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
947 // set new handle positions
948 Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
949 n->back()->setPosition(seg1[2]);
950 n->front()->setPosition(seg2[1]);
951 n->setType(NODE_SMOOTH, false);
952 inserted = list.insert(insert_at, n);
954 first->front()->move(seg1[1]);
955 second->back()->move(seg2[2]);
956 }
957 return inserted;
958 }
960 /** Find the node that is closest/farthest from the origin
961 * @param origin Point of reference
962 * @param search_selected Consider selected nodes
963 * @param search_unselected Consider unselected nodes
964 * @param closest If true, return closest node, if false, return farthest
965 * @return The matching node, or an empty iterator if none found
966 */
967 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
968 bool search_unselected, bool closest)
969 {
970 NodeList::iterator match;
971 double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
972 if (_num_selected == 0 && !search_unselected) return match;
974 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
975 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
976 if(j->selected()) {
977 if (!search_selected) continue;
978 } else {
979 if (!search_unselected) continue;
980 }
981 double dist = Geom::distance(*j, *origin);
982 bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
983 if (cond) {
984 match = j;
985 extr_dist = dist;
986 }
987 }
988 }
989 return match;
990 }
992 /** Called by the XML observer when something else than us modifies the path. */
993 void PathManipulator::_externalChange(unsigned type)
994 {
995 hideDragPoint();
997 switch (type) {
998 case PATH_CHANGE_D: {
999 _getGeometry();
1001 // ugly: stored offsets of selected nodes in a vector
1002 // vector<bool> should be specialized so that it takes only 1 bit per value
1003 std::vector<bool> selpos;
1004 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1005 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1006 selpos.push_back(j->selected());
1007 }
1008 }
1009 unsigned size = selpos.size(), curpos = 0;
1011 _createControlPointsFromGeometry();
1013 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1014 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1015 if (curpos >= size) goto end_restore;
1016 if (selpos[curpos]) _selection.insert(j.ptr());
1017 ++curpos;
1018 }
1019 }
1020 end_restore:
1022 _updateOutline();
1023 } break;
1024 case PATH_CHANGE_TRANSFORM: {
1025 Geom::Matrix i2d_change = _d2i_transform;
1026 _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
1027 _d2i_transform = _i2d_transform.inverse();
1028 i2d_change *= _i2d_transform;
1029 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1030 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1031 j->transform(i2d_change);
1032 }
1033 }
1034 _updateOutline();
1035 } break;
1036 default: break;
1037 }
1038 }
1040 /** Create nodes and handles based on the XML of the edited path. */
1041 void PathManipulator::_createControlPointsFromGeometry()
1042 {
1043 clear();
1045 // sanitize pathvector and store it in SPCurve,
1046 // so that _updateDragPoint doesn't crash on paths with naked movetos
1047 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1048 for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1049 // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1050 // When we erase an element, the next one slides into position,
1051 // so we do not increment the iterator even though it is theoretically invalidated.
1052 if (i->empty()) {
1053 pathv.erase(i);
1054 } else {
1055 ++i;
1056 }
1057 }
1058 _spcurve->set_pathvector(pathv);
1060 pathv *= (_edit_transform * _i2d_transform);
1062 // in this loop, we know that there are no zero-segment subpaths
1063 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1064 // prepare new subpath
1065 SubpathPtr subpath(new NodeList(_subpaths));
1066 _subpaths.push_back(subpath);
1068 Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1069 subpath->push_back(previous_node);
1070 Geom::Curve const &cseg = pit->back_closed();
1071 bool fuse_ends = pit->closed()
1072 && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1074 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1075 Geom::Point pos = cit->finalPoint();
1076 Node *current_node;
1077 // if the closing segment is degenerate and the path is closed, we need to move
1078 // the handle of the first node instead of creating a new one
1079 if (fuse_ends && cit == --(pit->end_open())) {
1080 current_node = subpath->begin().get_pointer();
1081 } else {
1082 /* regardless of segment type, create a new node at the end
1083 * of this segment (unless this is the last segment of a closed path
1084 * with a degenerate closing segment */
1085 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1086 subpath->push_back(current_node);
1087 }
1088 // if this is a bezier segment, move handles appropriately
1089 if (Geom::CubicBezier const *cubic_bezier =
1090 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1091 {
1092 std::vector<Geom::Point> points = cubic_bezier->points();
1094 previous_node->front()->setPosition(points[1]);
1095 current_node ->back() ->setPosition(points[2]);
1096 }
1097 previous_node = current_node;
1098 }
1099 // If the path is closed, make the list cyclic
1100 if (pit->closed()) subpath->setClosed(true);
1101 }
1103 // we need to set the nodetypes after all the handles are in place,
1104 // so that pickBestType works correctly
1105 // TODO maybe migrate to inkscape:node-types?
1106 // TODO move this into SPPath - do not manipulate directly
1107 gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
1108 std::string nodetype_string = nts_raw ? nts_raw : "";
1109 /* Calculate the needed length of the nodetype string.
1110 * For closed paths, the entry is duplicated for the starting node,
1111 * so we can just use the count of segments including the closing one
1112 * to include the extra end node. */
1113 std::string::size_type nodetype_len = 0;
1114 for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1115 if (i->empty()) continue;
1116 nodetype_len += i->size_closed();
1117 }
1118 /* pad the string to required length with a bogus value.
1119 * 'b' and any other letter not recognized by the parser causes the best fit to be set
1120 * as the node type */
1121 if (nodetype_len > nodetype_string.size()) {
1122 nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1123 }
1124 std::string::iterator tsi = nodetype_string.begin();
1125 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1126 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1127 j->setType(Node::parse_nodetype(*tsi++), false);
1128 }
1129 if ((*i)->closed()) {
1130 // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1131 // the first one to remain backward compatible.
1132 (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1133 }
1134 }
1135 }
1137 /** Construct the geometric representation of nodes and handles, update the outline
1138 * and display */
1139 void PathManipulator::_createGeometryFromControlPoints()
1140 {
1141 Geom::PathBuilder builder;
1142 for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1143 SubpathPtr subpath = *spi;
1144 if (subpath->empty()) {
1145 _subpaths.erase(spi++);
1146 continue;
1147 }
1148 NodeList::iterator prev = subpath->begin();
1149 builder.moveTo(prev->position());
1151 for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1152 build_segment(builder, prev.ptr(), i.ptr());
1153 prev = i;
1154 }
1155 if (subpath->closed()) {
1156 // Here we link the last and first node if the path is closed.
1157 // If the last segment is Bezier, we add it.
1158 if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1159 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1160 }
1161 // if that segment is linear, we just call closePath().
1162 builder.closePath();
1163 }
1164 ++spi;
1165 }
1166 builder.finish();
1167 _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1168 if (_live_outline)
1169 _updateOutline();
1170 if (_live_objects)
1171 _setGeometry();
1172 }
1174 /** Build one segment of the geometric representation.
1175 * @relates PathManipulator */
1176 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1177 {
1178 if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1179 {
1180 // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1181 // and trying to display a path using them results in funny artifacts.
1182 builder.lineTo(cur_node->position());
1183 } else {
1184 // this is a bezier segment
1185 builder.curveTo(
1186 prev_node->front()->position(),
1187 cur_node->back()->position(),
1188 cur_node->position());
1189 }
1190 }
1192 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1193 std::string PathManipulator::_createTypeString()
1194 {
1195 // precondition: no single-node subpaths
1196 std::stringstream tstr;
1197 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1198 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1199 tstr << j->type();
1200 }
1201 // nodestring format peculiarity: first node is counted twice for closed paths
1202 if ((*i)->closed()) tstr << (*i)->begin()->type();
1203 }
1204 return tstr.str();
1205 }
1207 /** Update the path outline. */
1208 void PathManipulator::_updateOutline()
1209 {
1210 if (!_show_outline) {
1211 sp_canvas_item_hide(_outline);
1212 return;
1213 }
1215 Geom::PathVector pv = _spcurve->get_pathvector();
1216 pv *= (_edit_transform * _i2d_transform);
1217 // This SPCurve thing has to be killed with extreme prejudice
1218 SPCurve *_hc = new SPCurve();
1219 if (_show_path_direction) {
1220 // To show the direction, we append additional subpaths which consist of a single
1221 // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1222 // at an angle 150 degrees from the unit tangent. This creates the appearance
1223 // of little 'harpoons' that show the direction of the subpaths.
1224 Geom::PathVector arrows;
1225 for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1226 Geom::Path &path = *i;
1227 for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1228 Geom::Point at = j->pointAt(0.5);
1229 Geom::Point ut = j->unitTangentAt(0.5);
1230 // rotate the point
1231 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1232 Geom::Point arrow_end = _desktop->w2d(
1233 _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1235 Geom::Path arrow(at);
1236 arrow.appendNew<Geom::LineSegment>(arrow_end);
1237 arrows.push_back(arrow);
1238 }
1239 }
1240 pv.insert(pv.end(), arrows.begin(), arrows.end());
1241 }
1242 _hc->set_pathvector(pv);
1243 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1244 sp_canvas_item_show(_outline);
1245 _hc->unref();
1246 }
1248 /** Retrieve the geometry of the edited object from the object tree */
1249 void PathManipulator::_getGeometry()
1250 {
1251 using namespace Inkscape::LivePathEffect;
1252 if (!_lpe_key.empty()) {
1253 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1254 if (lpe) {
1255 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1256 _spcurve->unref();
1257 _spcurve = new SPCurve(pathparam->get_pathvector());
1258 }
1259 } else {
1260 _spcurve->unref();
1261 _spcurve = sp_path_get_curve_for_edit(_path);
1262 }
1263 }
1265 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1266 void PathManipulator::_setGeometry()
1267 {
1268 using namespace Inkscape::LivePathEffect;
1269 if (empty()) return;
1271 if (!_lpe_key.empty()) {
1272 // copied from nodepath.cpp
1273 // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1274 // a LivePathEffectObject. (mad laughter)
1275 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1276 if (lpe) {
1277 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1278 pathparam->set_new_value(_spcurve->get_pathvector(), false);
1279 LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1280 }
1281 } else {
1282 if (_path->repr->attribute("inkscape:original-d"))
1283 sp_path_set_original_curve(_path, _spcurve, false, false);
1284 else
1285 sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1286 }
1287 }
1289 /** Figure out in what attribute to store the nodetype string. */
1290 Glib::ustring PathManipulator::_nodetypesKey()
1291 {
1292 if (_lpe_key.empty()) return "sodipodi:nodetypes";
1293 return _lpe_key + "-nodetypes";
1294 }
1296 /** Return the XML node we are editing.
1297 * This method is wrong but necessary at the moment. */
1298 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1299 {
1300 if (_lpe_key.empty()) return _path->repr;
1301 return LIVEPATHEFFECT(_path)->repr;
1302 }
1304 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1305 {
1306 if (event->button != 1) return false;
1307 if (held_alt(*event) && held_control(*event)) {
1308 // Ctrl+Alt+click: delete nodes
1309 hideDragPoint();
1310 NodeList::iterator iter = NodeList::get_iterator(n);
1311 NodeList &nl = iter->nodeList();
1313 if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1314 // Removing last node of closed path - delete it
1315 nl.kill();
1316 } else {
1317 // In other cases, delete the node under cursor
1318 _deleteStretch(iter, iter.next(), true);
1319 }
1321 if (!empty()) {
1322 update();
1323 }
1324 // We need to call MPM's method because it could have been our last node
1325 _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1327 return true;
1328 } else if (held_control(*event)) {
1329 // Ctrl+click: cycle between node types
1330 if (!n->isEndNode()) {
1331 n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1332 update();
1333 _commit(_("Cycle node type"));
1334 }
1335 return true;
1336 }
1337 return false;
1338 }
1340 void PathManipulator::_handleGrabbed()
1341 {
1342 _selection.hideTransformHandles();
1343 }
1345 void PathManipulator::_handleUngrabbed()
1346 {
1347 _selection.restoreTransformHandles();
1348 _commit(_("Drag handle"));
1349 }
1351 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1352 {
1353 // retracting by Ctrl+click
1354 if (event->button == 1 && held_control(*event)) {
1355 h->move(h->parent()->position());
1356 update();
1357 _commit(_("Retract handle"));
1358 return true;
1359 }
1360 return false;
1361 }
1363 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1364 {
1365 if (selected) ++_num_selected;
1366 else --_num_selected;
1368 // don't do anything if we do not show handles
1369 if (!_show_handles) return;
1371 // only do something if a node changed selection state
1372 Node *node = dynamic_cast<Node*>(p);
1373 if (!node) return;
1375 // update handle display
1376 NodeList::iterator iters[5];
1377 iters[2] = NodeList::get_iterator(node);
1378 iters[1] = iters[2].prev();
1379 iters[3] = iters[2].next();
1380 if (selected) {
1381 // selection - show handles on this node and adjacent ones
1382 node->showHandles(true);
1383 if (iters[1]) iters[1]->showHandles(true);
1384 if (iters[3]) iters[3]->showHandles(true);
1385 } else {
1386 /* Deselection is more complex.
1387 * The change might affect 3 nodes - this one and two adjacent.
1388 * If the node and both its neighbors are deselected, hide handles.
1389 * Otherwise, leave as is. */
1390 if (iters[1]) iters[0] = iters[1].prev();
1391 if (iters[3]) iters[4] = iters[3].next();
1392 bool nodesel[5];
1393 for (int i = 0; i < 5; ++i) {
1394 nodesel[i] = iters[i] && iters[i]->selected();
1395 }
1396 for (int i = 1; i < 4; ++i) {
1397 if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1398 iters[i]->showHandles(false);
1399 }
1400 }
1401 }
1402 }
1404 /** Removes all nodes belonging to this manipulator from the control pont selection */
1405 void PathManipulator::_removeNodesFromSelection()
1406 {
1407 // remove this manipulator's nodes from selection
1408 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1409 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1410 _selection.erase(j.get_pointer());
1411 }
1412 }
1413 }
1415 /** Update the XML representation and put the specified annotation on the undo stack */
1416 void PathManipulator::_commit(Glib::ustring const &annotation)
1417 {
1418 writeXML();
1419 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1420 }
1422 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1423 {
1424 writeXML();
1425 sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1426 annotation.data());
1427 }
1429 /** Update the position of the curve drag point such that it is over the nearest
1430 * point of the path. */
1431 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1432 {
1433 Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1434 Geom::PathVector pv = _spcurve->get_pathvector();
1435 boost::optional<Geom::PathVectorPosition> pvp
1436 = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1437 if (!pvp) return;
1438 Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1440 double fracpart;
1441 std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1442 for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1443 NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1445 double stroke_tolerance = _getStrokeTolerance();
1446 if (first && first.next() &&
1447 fracpart != 0.0 &&
1448 Geom::distance(evp, nearest_point) < stroke_tolerance)
1449 {
1450 _dragpoint->setVisible(true);
1451 _dragpoint->setPosition(_desktop->w2d(nearest_point));
1452 _dragpoint->setSize(2 * stroke_tolerance);
1453 _dragpoint->setTimeValue(fracpart);
1454 _dragpoint->setIterator(first);
1455 } else {
1456 _dragpoint->setVisible(false);
1457 }
1458 }
1460 /// This is called on zoom change to update the direction arrows
1461 void PathManipulator::_updateOutlineOnZoomChange()
1462 {
1463 if (_show_path_direction) _updateOutline();
1464 }
1466 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1467 * or segment selection, in window coordinates. */
1468 double PathManipulator::_getStrokeTolerance()
1469 {
1470 /* Stroke event tolerance is equal to half the stroke's width plus the global
1471 * drag tolerance setting. */
1472 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1473 double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1474 if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1475 ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1476 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1477 * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1478 }
1479 return ret;
1480 }
1482 } // namespace UI
1483 } // namespace Inkscape
1485 /*
1486 Local Variables:
1487 mode:c++
1488 c-file-style:"stroustrup"
1489 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1490 indent-tabs-mode:nil
1491 fill-column:99
1492 End:
1493 */
1494 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :