956f48a7d8bd2b5d3d19dc711a23343fb6445643
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 switch (type) {
996 case PATH_CHANGE_D: {
997 _getGeometry();
999 // ugly: stored offsets of selected nodes in a vector
1000 // vector<bool> should be specialized so that it takes only 1 bit per value
1001 std::vector<bool> selpos;
1002 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1003 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1004 selpos.push_back(j->selected());
1005 }
1006 }
1007 unsigned size = selpos.size(), curpos = 0;
1009 _createControlPointsFromGeometry();
1011 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1012 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1013 if (curpos >= size) goto end_restore;
1014 if (selpos[curpos]) _selection.insert(j.ptr());
1015 ++curpos;
1016 }
1017 }
1018 end_restore:
1020 _updateOutline();
1021 } break;
1022 case PATH_CHANGE_TRANSFORM: {
1023 Geom::Matrix i2d_change = _d2i_transform;
1024 _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
1025 _d2i_transform = _i2d_transform.inverse();
1026 i2d_change *= _i2d_transform;
1027 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1028 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1029 j->transform(i2d_change);
1030 }
1031 }
1032 _updateOutline();
1033 } break;
1034 default: break;
1035 }
1036 }
1038 /** Create nodes and handles based on the XML of the edited path. */
1039 void PathManipulator::_createControlPointsFromGeometry()
1040 {
1041 clear();
1043 // sanitize pathvector and store it in SPCurve,
1044 // so that _updateDragPoint doesn't crash on paths with naked movetos
1045 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1046 for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1047 // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1048 // When we erase an element, the next one slides into position,
1049 // so we do not increment the iterator even though it is theoretically invalidated.
1050 if (i->empty()) {
1051 pathv.erase(i);
1052 } else {
1053 ++i;
1054 }
1055 }
1056 _spcurve->set_pathvector(pathv);
1058 pathv *= (_edit_transform * _i2d_transform);
1060 // in this loop, we know that there are no zero-segment subpaths
1061 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1062 // prepare new subpath
1063 SubpathPtr subpath(new NodeList(_subpaths));
1064 _subpaths.push_back(subpath);
1066 Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1067 subpath->push_back(previous_node);
1068 Geom::Curve const &cseg = pit->back_closed();
1069 bool fuse_ends = pit->closed()
1070 && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1072 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1073 Geom::Point pos = cit->finalPoint();
1074 Node *current_node;
1075 // if the closing segment is degenerate and the path is closed, we need to move
1076 // the handle of the first node instead of creating a new one
1077 if (fuse_ends && cit == --(pit->end_open())) {
1078 current_node = subpath->begin().get_pointer();
1079 } else {
1080 /* regardless of segment type, create a new node at the end
1081 * of this segment (unless this is the last segment of a closed path
1082 * with a degenerate closing segment */
1083 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1084 subpath->push_back(current_node);
1085 }
1086 // if this is a bezier segment, move handles appropriately
1087 if (Geom::CubicBezier const *cubic_bezier =
1088 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1089 {
1090 std::vector<Geom::Point> points = cubic_bezier->points();
1092 previous_node->front()->setPosition(points[1]);
1093 current_node ->back() ->setPosition(points[2]);
1094 }
1095 previous_node = current_node;
1096 }
1097 // If the path is closed, make the list cyclic
1098 if (pit->closed()) subpath->setClosed(true);
1099 }
1101 // we need to set the nodetypes after all the handles are in place,
1102 // so that pickBestType works correctly
1103 // TODO maybe migrate to inkscape:node-types?
1104 // TODO move this into SPPath - do not manipulate directly
1105 gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
1106 std::string nodetype_string = nts_raw ? nts_raw : "";
1107 /* Calculate the needed length of the nodetype string.
1108 * For closed paths, the entry is duplicated for the starting node,
1109 * so we can just use the count of segments including the closing one
1110 * to include the extra end node. */
1111 std::string::size_type nodetype_len = 0;
1112 for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1113 if (i->empty()) continue;
1114 nodetype_len += i->size_closed();
1115 }
1116 /* pad the string to required length with a bogus value.
1117 * 'b' and any other letter not recognized by the parser causes the best fit to be set
1118 * as the node type */
1119 if (nodetype_len > nodetype_string.size()) {
1120 nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1121 }
1122 std::string::iterator tsi = nodetype_string.begin();
1123 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1124 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1125 j->setType(Node::parse_nodetype(*tsi++), false);
1126 }
1127 if ((*i)->closed()) {
1128 // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1129 // the first one to remain backward compatible.
1130 (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1131 }
1132 }
1133 }
1135 /** Construct the geometric representation of nodes and handles, update the outline
1136 * and display */
1137 void PathManipulator::_createGeometryFromControlPoints()
1138 {
1139 Geom::PathBuilder builder;
1140 for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1141 SubpathPtr subpath = *spi;
1142 if (subpath->empty()) {
1143 _subpaths.erase(spi++);
1144 continue;
1145 }
1146 NodeList::iterator prev = subpath->begin();
1147 builder.moveTo(prev->position());
1149 for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1150 build_segment(builder, prev.ptr(), i.ptr());
1151 prev = i;
1152 }
1153 if (subpath->closed()) {
1154 // Here we link the last and first node if the path is closed.
1155 // If the last segment is Bezier, we add it.
1156 if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1157 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1158 }
1159 // if that segment is linear, we just call closePath().
1160 builder.closePath();
1161 }
1162 ++spi;
1163 }
1164 builder.finish();
1165 _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1166 if (_live_outline)
1167 _updateOutline();
1168 if (_live_objects)
1169 _setGeometry();
1170 }
1172 /** Build one segment of the geometric representation.
1173 * @relates PathManipulator */
1174 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1175 {
1176 if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1177 {
1178 // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1179 // and trying to display a path using them results in funny artifacts.
1180 builder.lineTo(cur_node->position());
1181 } else {
1182 // this is a bezier segment
1183 builder.curveTo(
1184 prev_node->front()->position(),
1185 cur_node->back()->position(),
1186 cur_node->position());
1187 }
1188 }
1190 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1191 std::string PathManipulator::_createTypeString()
1192 {
1193 // precondition: no single-node subpaths
1194 std::stringstream tstr;
1195 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1196 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1197 tstr << j->type();
1198 }
1199 // nodestring format peculiarity: first node is counted twice for closed paths
1200 if ((*i)->closed()) tstr << (*i)->begin()->type();
1201 }
1202 return tstr.str();
1203 }
1205 /** Update the path outline. */
1206 void PathManipulator::_updateOutline()
1207 {
1208 if (!_show_outline) {
1209 sp_canvas_item_hide(_outline);
1210 return;
1211 }
1213 Geom::PathVector pv = _spcurve->get_pathvector();
1214 pv *= (_edit_transform * _i2d_transform);
1215 // This SPCurve thing has to be killed with extreme prejudice
1216 SPCurve *_hc = new SPCurve();
1217 if (_show_path_direction) {
1218 // To show the direction, we append additional subpaths which consist of a single
1219 // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1220 // at an angle 150 degrees from the unit tangent. This creates the appearance
1221 // of little 'harpoons' that show the direction of the subpaths.
1222 Geom::PathVector arrows;
1223 for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1224 Geom::Path &path = *i;
1225 for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1226 Geom::Point at = j->pointAt(0.5);
1227 Geom::Point ut = j->unitTangentAt(0.5);
1228 // rotate the point
1229 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1230 Geom::Point arrow_end = _desktop->w2d(
1231 _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1233 Geom::Path arrow(at);
1234 arrow.appendNew<Geom::LineSegment>(arrow_end);
1235 arrows.push_back(arrow);
1236 }
1237 }
1238 pv.insert(pv.end(), arrows.begin(), arrows.end());
1239 }
1240 _hc->set_pathvector(pv);
1241 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1242 sp_canvas_item_show(_outline);
1243 _hc->unref();
1244 }
1246 /** Retrieve the geometry of the edited object from the object tree */
1247 void PathManipulator::_getGeometry()
1248 {
1249 using namespace Inkscape::LivePathEffect;
1250 if (!_lpe_key.empty()) {
1251 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1252 if (lpe) {
1253 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1254 _spcurve->unref();
1255 _spcurve = new SPCurve(pathparam->get_pathvector());
1256 }
1257 } else {
1258 _spcurve->unref();
1259 _spcurve = sp_path_get_curve_for_edit(_path);
1260 }
1261 }
1263 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1264 void PathManipulator::_setGeometry()
1265 {
1266 using namespace Inkscape::LivePathEffect;
1267 if (empty()) return;
1269 if (!_lpe_key.empty()) {
1270 // copied from nodepath.cpp
1271 // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1272 // a LivePathEffectObject. (mad laughter)
1273 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1274 if (lpe) {
1275 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1276 pathparam->set_new_value(_spcurve->get_pathvector(), false);
1277 LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1278 }
1279 } else {
1280 if (_path->repr->attribute("inkscape:original-d"))
1281 sp_path_set_original_curve(_path, _spcurve, false, false);
1282 else
1283 sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1284 }
1285 }
1287 /** Figure out in what attribute to store the nodetype string. */
1288 Glib::ustring PathManipulator::_nodetypesKey()
1289 {
1290 if (_lpe_key.empty()) return "sodipodi:nodetypes";
1291 return _lpe_key + "-nodetypes";
1292 }
1294 /** Return the XML node we are editing.
1295 * This method is wrong but necessary at the moment. */
1296 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1297 {
1298 if (_lpe_key.empty()) return _path->repr;
1299 return LIVEPATHEFFECT(_path)->repr;
1300 }
1302 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1303 {
1304 if (event->button != 1) return false;
1305 if (held_alt(*event) && held_control(*event)) {
1306 // Ctrl+Alt+click: delete nodes
1307 hideDragPoint();
1308 NodeList::iterator iter = NodeList::get_iterator(n);
1309 NodeList &nl = iter->nodeList();
1311 if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1312 // Removing last node of closed path - delete it
1313 nl.kill();
1314 } else {
1315 // In other cases, delete the node under cursor
1316 _deleteStretch(iter, iter.next(), true);
1317 }
1319 if (!empty()) {
1320 update();
1321 }
1322 // We need to call MPM's method because it could have been our last node
1323 _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1325 return true;
1326 } else if (held_control(*event)) {
1327 // Ctrl+click: cycle between node types
1328 if (!n->isEndNode()) {
1329 n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1330 update();
1331 _commit(_("Cycle node type"));
1332 }
1333 return true;
1334 }
1335 return false;
1336 }
1338 void PathManipulator::_handleGrabbed()
1339 {
1340 _selection.hideTransformHandles();
1341 }
1343 void PathManipulator::_handleUngrabbed()
1344 {
1345 _selection.restoreTransformHandles();
1346 _commit(_("Drag handle"));
1347 }
1349 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1350 {
1351 // retracting by Ctrl+click
1352 if (event->button == 1 && held_control(*event)) {
1353 h->move(h->parent()->position());
1354 update();
1355 _commit(_("Retract handle"));
1356 return true;
1357 }
1358 return false;
1359 }
1361 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1362 {
1363 if (selected) ++_num_selected;
1364 else --_num_selected;
1366 // don't do anything if we do not show handles
1367 if (!_show_handles) return;
1369 // only do something if a node changed selection state
1370 Node *node = dynamic_cast<Node*>(p);
1371 if (!node) return;
1373 // update handle display
1374 NodeList::iterator iters[5];
1375 iters[2] = NodeList::get_iterator(node);
1376 iters[1] = iters[2].prev();
1377 iters[3] = iters[2].next();
1378 if (selected) {
1379 // selection - show handles on this node and adjacent ones
1380 node->showHandles(true);
1381 if (iters[1]) iters[1]->showHandles(true);
1382 if (iters[3]) iters[3]->showHandles(true);
1383 } else {
1384 /* Deselection is more complex.
1385 * The change might affect 3 nodes - this one and two adjacent.
1386 * If the node and both its neighbors are deselected, hide handles.
1387 * Otherwise, leave as is. */
1388 if (iters[1]) iters[0] = iters[1].prev();
1389 if (iters[3]) iters[4] = iters[3].next();
1390 bool nodesel[5];
1391 for (int i = 0; i < 5; ++i) {
1392 nodesel[i] = iters[i] && iters[i]->selected();
1393 }
1394 for (int i = 1; i < 4; ++i) {
1395 if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1396 iters[i]->showHandles(false);
1397 }
1398 }
1399 }
1400 }
1402 /** Removes all nodes belonging to this manipulator from the control pont selection */
1403 void PathManipulator::_removeNodesFromSelection()
1404 {
1405 // remove this manipulator's nodes from selection
1406 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1407 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1408 _selection.erase(j.get_pointer());
1409 }
1410 }
1411 }
1413 /** Update the XML representation and put the specified annotation on the undo stack */
1414 void PathManipulator::_commit(Glib::ustring const &annotation)
1415 {
1416 writeXML();
1417 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1418 }
1420 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1421 {
1422 writeXML();
1423 sp_document_maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1424 annotation.data());
1425 }
1427 /** Update the position of the curve drag point such that it is over the nearest
1428 * point of the path. */
1429 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1430 {
1431 Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1432 Geom::PathVector pv = _spcurve->get_pathvector();
1433 boost::optional<Geom::PathVectorPosition> pvp
1434 = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1435 if (!pvp) return;
1436 Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1438 double fracpart;
1439 std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1440 for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1441 NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1443 double stroke_tolerance = _getStrokeTolerance();
1444 if (first && first.next() &&
1445 fracpart != 0.0 &&
1446 Geom::distance(evp, nearest_point) < stroke_tolerance)
1447 {
1448 _dragpoint->setVisible(true);
1449 _dragpoint->setPosition(_desktop->w2d(nearest_point));
1450 _dragpoint->setSize(2 * stroke_tolerance);
1451 _dragpoint->setTimeValue(fracpart);
1452 _dragpoint->setIterator(first);
1453 } else {
1454 _dragpoint->setVisible(false);
1455 }
1456 }
1458 /// This is called on zoom change to update the direction arrows
1459 void PathManipulator::_updateOutlineOnZoomChange()
1460 {
1461 if (_show_path_direction) _updateOutline();
1462 }
1464 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1465 * or segment selection, in window coordinates. */
1466 double PathManipulator::_getStrokeTolerance()
1467 {
1468 /* Stroke event tolerance is equal to half the stroke's width plus the global
1469 * drag tolerance setting. */
1470 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1471 double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1472 if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1473 ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1474 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1475 * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1476 }
1477 return ret;
1478 }
1480 } // namespace UI
1481 } // namespace Inkscape
1483 /*
1484 Local Variables:
1485 mode:c++
1486 c-file-style:"stroustrup"
1487 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1488 indent-tabs-mode:nil
1489 fill-column:99
1490 End:
1491 */
1492 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :