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) : _pm(p), _blocked(false) {}
62 virtual void notifyAttributeChanged(Inkscape::XML::Node &, GQuark attr,
63 Util::ptr_shared<char>, Util::ptr_shared<char>)
64 {
65 // do nothing if blocked
66 if (_blocked) return;
68 GQuark path_d = g_quark_from_static_string("d");
69 GQuark path_transform = g_quark_from_static_string("transform");
70 GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
72 // only react to "d" (path data) and "transform" attribute changes
73 if (attr == lpe_quark || attr == path_d) {
74 _pm->_externalChange(PATH_CHANGE_D);
75 } else if (attr == path_transform) {
76 _pm->_externalChange(PATH_CHANGE_TRANSFORM);
77 }
78 }
79 void block() { _blocked = true; }
80 void unblock() { _blocked = false; }
81 private:
82 PathManipulator *_pm;
83 bool _blocked;
84 };
86 void build_segment(Geom::PathBuilder &, Node *, Node *);
88 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
89 Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
90 : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
91 , _subpaths(*this)
92 , _multi_path_manipulator(mpm)
93 , _path(path)
94 , _spcurve(NULL)
95 , _dragpoint(new CurveDragPoint(*this))
96 , _observer(new PathManipulatorObserver(this))
97 , _edit_transform(et)
98 , _show_handles(true)
99 , _show_outline(false)
100 , _lpe_key(lpe_key)
101 {
102 /* Because curve drag point is always created first, it does not cover nodes */
103 if (_lpe_key.empty()) {
104 _i2d_transform = sp_item_i2d_affine(SP_ITEM(path));
105 } else {
106 _i2d_transform = Geom::identity();
107 }
108 _d2i_transform = _i2d_transform.inverse();
109 _dragpoint->setVisible(false);
111 _getGeometry();
113 _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
114 sp_canvas_item_hide(_outline);
115 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
116 SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
117 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
119 _subpaths.signal_insert_node.connect(
120 sigc::mem_fun(*this, &PathManipulator::_attachNodeHandlers));
121 _subpaths.signal_remove_node.connect(
122 sigc::mem_fun(*this, &PathManipulator::_removeNodeHandlers));
123 _selection.signal_update.connect(
124 sigc::mem_fun(*this, &PathManipulator::update));
125 _selection.signal_point_changed.connect(
126 sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
127 _dragpoint->signal_update.connect(
128 sigc::mem_fun(*this, &PathManipulator::update));
129 _desktop->signal_zoom_changed.connect(
130 sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
132 _createControlPointsFromGeometry();
134 _path->repr->addObserver(*_observer);
135 }
137 PathManipulator::~PathManipulator()
138 {
139 delete _dragpoint;
140 if (_path) _path->repr->removeObserver(*_observer);
141 delete _observer;
142 gtk_object_destroy(_outline);
143 if (_spcurve) _spcurve->unref();
144 clear();
145 }
147 /** Handle motion events to update the position of the curve drag point. */
148 bool PathManipulator::event(GdkEvent *event)
149 {
150 if (empty()) return false;
152 switch (event->type)
153 {
154 case GDK_MOTION_NOTIFY:
155 _updateDragPoint(event_point(event->motion));
156 break;
157 default: break;
158 }
159 return false;
160 }
162 /** Check whether the manipulator has any nodes. */
163 bool PathManipulator::empty() {
164 return !_path || _subpaths.empty();
165 }
167 /** Update the display and the outline of the path. */
168 void PathManipulator::update()
169 {
170 _createGeometryFromControlPoints();
171 }
173 /** Store the changes to the path in XML. */
174 void PathManipulator::writeXML()
175 {
176 if (!_path) return;
177 _observer->block();
178 if (!empty()) {
179 SP_OBJECT(_path)->updateRepr();
180 _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
181 } else {
182 // this manipulator will have to be destroyed right after this call
183 _getXMLNode()->removeObserver(*_observer);
184 sp_object_ref(_path);
185 _path->deleteObject(true, true);
186 sp_object_unref(_path);
187 _path = 0;
188 }
189 _observer->unblock();
190 }
192 /** Remove all nodes from the path. */
193 void PathManipulator::clear()
194 {
195 // no longer necessary since nodes remove themselves from selection on destruction
196 //_removeNodesFromSelection();
197 _subpaths.clear();
198 }
200 /** Select all nodes in subpaths that have something selected. */
201 void PathManipulator::selectSubpaths()
202 {
203 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
204 NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
205 for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
206 if (j->selected()) {
207 // if at least one of the nodes from this subpath is selected,
208 // select all nodes from this subpath
209 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
210 _selection.insert(ins.ptr());
211 continue;
212 }
213 }
214 }
215 }
217 /** Move the selection forward or backward by one node in each subpath, based on the sign
218 * of the parameter. */
219 void PathManipulator::shiftSelection(int dir)
220 {
221 if (dir == 0) return;
222 // We cannot do any tricks here, like iterating in different directions based on
223 // the sign and only setting the selection of nodes behind us, because it would break
224 // for closed paths.
225 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
226 std::deque<bool> sels; // I hope this is specialized for bools!
227 unsigned num = 0;
229 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
230 sels.push_back(j->selected());
231 _selection.erase(j.ptr());
232 ++num;
233 }
234 if (num == 0) continue; // should never happen!
236 num = 0;
237 // In closed subpath, shift the selection cyclically. In an open one,
238 // let the selection 'slide into nothing' at ends.
239 if (dir > 0) {
240 if ((*i)->closed()) {
241 bool last = sels.back();
242 sels.pop_back();
243 sels.push_front(last);
244 } else {
245 sels.push_front(false);
246 }
247 } else {
248 if ((*i)->closed()) {
249 bool first = sels.front();
250 sels.pop_front();
251 sels.push_back(first);
252 } else {
253 sels.push_back(false);
254 num = 1;
255 }
256 }
258 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
259 if (sels[num]) _selection.insert(j.ptr());
260 ++num;
261 }
262 }
263 }
265 /** Invert selection in the selected subpaths. */
266 void PathManipulator::invertSelectionInSubpaths()
267 {
268 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
269 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
270 if (j->selected()) {
271 // found selected node - invert selection in this subpath
272 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
273 if (k->selected()) _selection.erase(k.ptr());
274 else _selection.insert(k.ptr());
275 }
276 // next subpath
277 break;
278 }
279 }
280 }
281 }
283 /** Insert a new node in the middle of each selected segment. */
284 void PathManipulator::insertNodes()
285 {
286 if (!_num_selected) return;
288 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
289 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
290 NodeList::iterator k = j.next();
291 if (k && j->selected() && k->selected()) {
292 j = subdivideSegment(j, 0.5);
293 _selection.insert(j.ptr());
294 }
295 }
296 }
297 }
299 /** Replace contiguous selections of nodes in each subpath with one node. */
300 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
301 {
302 if (!_num_selected) return;
303 _dragpoint->setVisible(false);
305 bool pos_valid = preserve_pos;
306 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
307 SubpathPtr sp = *i;
308 unsigned num_selected = 0, num_unselected = 0;
309 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
310 if (j->selected()) ++num_selected;
311 else ++num_unselected;
312 }
313 if (num_selected < 2) continue;
314 if (num_unselected == 0) {
315 // if all nodes in a subpath are selected, the operation doesn't make much sense
316 continue;
317 }
319 // Start from unselected node in closed paths, so that we don't start in the middle
320 // of a contiguous selection
321 NodeList::iterator sel_beg = sp->begin(), sel_end;
322 if (sp->closed()) {
323 while (sel_beg->selected()) ++sel_beg;
324 }
326 // Main loop
327 while (num_selected > 0) {
328 // Find selected node
329 while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
330 if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
331 "but there are still nodes to process!");
333 unsigned num_points = 0;
334 bool use_pos = false;
335 Geom::Point back_pos, front_pos;
336 back_pos = *sel_beg->back();
338 for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
339 ++num_points;
340 front_pos = *sel_end->front();
341 if (pos_valid && sel_end == preserve_pos) use_pos = true;
342 }
343 if (num_points > 1) {
344 Geom::Point joined_pos;
345 if (use_pos) {
346 joined_pos = preserve_pos->position();
347 pos_valid = false;
348 } else {
349 joined_pos = Geom::middle_point(back_pos, front_pos);
350 }
351 sel_beg->setType(NODE_CUSP, false);
352 sel_beg->move(joined_pos);
353 // do not move handles if they aren't degenerate
354 if (!sel_beg->back()->isDegenerate()) {
355 sel_beg->back()->setPosition(back_pos);
356 }
357 if (!sel_end.prev()->front()->isDegenerate()) {
358 sel_beg->front()->setPosition(front_pos);
359 }
360 sel_beg = sel_beg.next();
361 while (sel_beg != sel_end) {
362 NodeList::iterator next = sel_beg.next();
363 sp->erase(sel_beg);
364 sel_beg = next;
365 --num_selected;
366 }
367 }
368 --num_selected; // for the joined node or single selected node
369 }
370 }
371 }
373 /** Remove nodes in the middle of selected segments. */
374 void PathManipulator::weldSegments()
375 {
376 // TODO
377 }
379 /** Break the subpath at selected nodes. It also works for single node closed paths. */
380 void PathManipulator::breakNodes()
381 {
382 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
383 SubpathPtr sp = *i;
384 NodeList::iterator cur = sp->begin(), end = sp->end();
385 if (!sp->closed()) {
386 // Each open path must have at least two nodes so no checks are required.
387 // For 2-node open paths, cur == end
388 ++cur;
389 --end;
390 }
391 for (; cur != end; ++cur) {
392 if (!cur->selected()) continue;
393 SubpathPtr ins;
394 bool becomes_open = false;
396 if (sp->closed()) {
397 // Move the node to break at to the beginning of path
398 if (cur != sp->begin())
399 sp->splice(sp->begin(), *sp, cur, sp->end());
400 sp->setClosed(false);
401 ins = sp;
402 becomes_open = true;
403 } else {
404 SubpathPtr new_sp(new NodeList(_subpaths));
405 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
406 _subpaths.insert(i, new_sp);
407 ins = new_sp;
408 }
410 Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
411 ins->insert(ins->end(), n);
412 cur->setType(NODE_CUSP, false);
413 n->back()->setRelativePos(cur->back()->relativePos());
414 cur->back()->retract();
415 n->sink();
417 if (becomes_open) {
418 cur = sp->begin(); // this will be increased to ++sp->begin()
419 end = --sp->end();
420 }
421 }
422 }
423 }
425 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
426 * in a way that attempts to preserve the original shape of the curve. */
427 void PathManipulator::deleteNodes(bool keep_shape)
428 {
429 if (!_num_selected) return;
430 hideDragPoint();
432 unsigned const samples_per_segment = 10;
433 double const t_step = 1.0 / samples_per_segment;
435 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
436 SubpathPtr sp = *i;
438 // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
439 // in a closed one, delete entire subpath.
440 unsigned num_unselected = 0, num_selected = 0;
441 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
442 if (j->selected()) ++num_selected;
443 else ++num_unselected;
444 }
445 if (num_selected == 0) {
446 ++i;
447 continue;
448 }
449 if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
450 _subpaths.erase(i++);
451 continue;
452 }
454 // In closed paths, start from an unselected node - otherwise we might start in the middle
455 // of a selected stretch and the resulting bezier fit would be suboptimal
456 NodeList::iterator sel_beg = sp->begin(), sel_end;
457 if (sp->closed()) {
458 while (sel_beg->selected()) ++sel_beg;
459 }
460 sel_end = sel_beg;
462 while (num_selected > 0) {
463 while (!sel_beg->selected()) sel_beg = sel_beg.next();
464 sel_end = sel_beg;
465 unsigned del_len = 0;
466 while (sel_end && sel_end->selected()) {
467 ++del_len;
468 sel_end = sel_end.next();
469 }
471 // set surrounding node types to cusp if:
472 // 1. keep_shape is on, or
473 // 2. we are deleting at the end or beginning of an open path
474 // if !sel_end then sel_beg.prev() must be valid, otherwise the entire subpath
475 // would be deleted before we get here
476 if ((keep_shape || !sel_end) && sel_beg.prev()) sel_beg.prev()->setType(NODE_CUSP, false);
477 if ((keep_shape || !sel_beg.prev()) && sel_end) sel_end->setType(NODE_CUSP, false);
479 if (keep_shape && sel_beg.prev() && sel_end) {
480 // Fill fit data
481 unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
482 Geom::Point *bezier_data = new Geom::Point[num_samples];
483 Geom::Point result[4];
484 unsigned seg = 0;
486 for (NodeList::iterator cur = sel_beg.prev(); cur != sel_end; cur = cur.next()) {
487 Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
488 for (unsigned s = 0; s < samples_per_segment; ++s) {
489 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
490 }
491 ++seg;
492 }
493 // Fill last point
494 bezier_data[num_samples - 1] = sel_end->position();
495 // Compute replacement bezier curve
496 // TODO the fitting algorithm sucks - rewrite it to be awesome
497 bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
498 delete[] bezier_data;
500 sel_beg.prev()->front()->setPosition(result[1]);
501 sel_end->back()->setPosition(result[2]);
502 }
503 // We cannot simply use sp->erase(sel_beg, sel_end), because it would break
504 // for cases when the selected stretch crosses the beginning of the path
505 while (sel_beg != sel_end) {
506 NodeList::iterator next = sel_beg.next();
507 sp->erase(sel_beg);
508 sel_beg = next;
509 }
510 num_selected -= del_len;
511 }
512 ++i;
513 }
514 }
516 /** Removes selected segments */
517 void PathManipulator::deleteSegments()
518 {
519 if (_num_selected == 0) return;
520 hideDragPoint();
522 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
523 SubpathPtr sp = *i;
524 bool has_unselected = false;
525 unsigned num_selected = 0;
526 for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
527 if (j->selected()) {
528 ++num_selected;
529 } else {
530 has_unselected = true;
531 }
532 }
533 if (!has_unselected) {
534 _subpaths.erase(i++);
535 continue;
536 }
538 NodeList::iterator sel_beg = sp->begin();
539 if (sp->closed()) {
540 while (sel_beg && sel_beg->selected()) ++sel_beg;
541 }
542 while (num_selected > 0) {
543 if (!sel_beg->selected()) {
544 sel_beg = sel_beg.next();
545 continue;
546 }
547 NodeList::iterator sel_end = sel_beg;
548 unsigned num_points = 0;
549 while (sel_end && sel_end->selected()) {
550 sel_end = sel_end.next();
551 ++num_points;
552 }
553 if (num_points >= 2) {
554 // Retract end handles
555 sel_end.prev()->setType(NODE_CUSP, false);
556 sel_end.prev()->back()->retract();
557 sel_beg->setType(NODE_CUSP, false);
558 sel_beg->front()->retract();
559 if (sp->closed()) {
560 // In closed paths, relocate the beginning of the path to the last selected
561 // node and then unclose it. Remove the nodes from the first selected node
562 // to the new end of path.
563 if (sel_end.prev() != sp->begin())
564 sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
565 sp->setClosed(false);
566 sp->erase(sel_beg.next(), sp->end());
567 } else {
568 // for open paths:
569 // 1. At end or beginning, delete including the node on the end or beginning
570 // 2. In the middle, delete only inner nodes
571 if (sel_beg == sp->begin()) {
572 sp->erase(sp->begin(), sel_end.prev());
573 } else if (sel_end == sp->end()) {
574 sp->erase(sel_beg.next(), sp->end());
575 } else {
576 SubpathPtr new_sp(new NodeList(_subpaths));
577 new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
578 _subpaths.insert(i, new_sp);
579 if (sel_end.prev())
580 sp->erase(sp->begin(), sel_end.prev());
581 }
582 }
583 }
584 sel_beg = sel_end;
585 num_selected -= num_points;
586 }
587 ++i;
588 }
589 }
591 /** Reverse the subpaths that have anything selected. */
592 void PathManipulator::reverseSubpaths()
593 {
594 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
595 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
596 if (j->selected()) {
597 (*i)->reverse();
598 break; // continue with the next subpath
599 }
600 }
601 }
602 }
604 /** Make selected segments curves / lines. */
605 void PathManipulator::setSegmentType(SegmentType type)
606 {
607 if (!_num_selected) return;
608 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
609 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
610 NodeList::iterator k = j.next();
611 if (!(k && j->selected() && k->selected())) continue;
612 switch (type) {
613 case SEGMENT_STRAIGHT:
614 if (j->front()->isDegenerate() && k->back()->isDegenerate())
615 break;
616 j->front()->move(*j);
617 k->back()->move(*k);
618 break;
619 case SEGMENT_CUBIC_BEZIER:
620 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
621 break;
622 j->front()->move(j->position() + (k->position() - j->position()) / 3);
623 k->back()->move(k->position() + (j->position() - k->position()) / 3);
624 break;
625 }
626 }
627 }
628 }
630 /** Set the visibility of handles. */
631 void PathManipulator::showHandles(bool show)
632 {
633 if (show == _show_handles) return;
634 if (show) {
635 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
636 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
637 if (!j->selected()) continue;
638 j->showHandles(true);
639 if (j.prev()) j.prev()->showHandles(true);
640 if (j.next()) j.next()->showHandles(true);
641 }
642 }
643 } else {
644 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
645 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
646 j->showHandles(false);
647 }
648 }
649 }
650 _show_handles = show;
651 }
653 /** Set the visibility of outline. */
654 void PathManipulator::showOutline(bool show)
655 {
656 if (show == _show_outline) return;
657 _show_outline = show;
658 _updateOutline();
659 }
661 void PathManipulator::showPathDirection(bool show)
662 {
663 if (show == _show_path_direction) return;
664 _show_path_direction = show;
665 _updateOutline();
666 }
668 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
669 {
670 Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
671 _edit_transform = tnew;
672 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
673 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
674 j->transform(delta);
675 }
676 }
677 _createGeometryFromControlPoints();
678 }
680 /** Hide the curve drag point until the next motion event. */
681 void PathManipulator::hideDragPoint()
682 {
683 _dragpoint->setVisible(false);
684 _dragpoint->setIterator(NodeList::iterator());
685 }
687 /** Insert a node in the segment beginning with the supplied iterator,
688 * at the given time value */
689 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
690 {
691 if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
692 NodeList &list = NodeList::get(first);
693 NodeList::iterator second = first.next();
694 if (!second) throw std::invalid_argument("Subdivide after last node in open path");
696 // We need to insert the segment after 'first'. We can't simply use 'second'
697 // as the point of insertion, because when 'first' is the last node of closed path,
698 // the new node will be inserted as the first node instead.
699 NodeList::iterator insert_at = first;
700 ++insert_at;
702 NodeList::iterator inserted;
703 if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
704 // for a line segment, insert a cusp node
705 Node *n = new Node(_multi_path_manipulator._path_data.node_data,
706 Geom::lerp(t, first->position(), second->position()));
707 n->setType(NODE_CUSP, false);
708 inserted = list.insert(insert_at, n);
709 } else {
710 // build bezier curve and subdivide
711 Geom::CubicBezier temp(first->position(), first->front()->position(),
712 second->back()->position(), second->position());
713 std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
714 std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
716 // set new handle positions
717 Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
718 n->back()->setPosition(seg1[2]);
719 n->front()->setPosition(seg2[1]);
720 n->setType(NODE_SMOOTH, false);
721 inserted = list.insert(insert_at, n);
723 first->front()->move(seg1[1]);
724 second->back()->move(seg2[2]);
725 }
726 return inserted;
727 }
729 /** Find the node that is closest/farthest from the origin
730 * @param origin Point of reference
731 * @param search_selected Consider selected nodes
732 * @param search_unselected Consider unselected nodes
733 * @param closest If true, return closest node, if false, return farthest
734 * @return The matching node, or an empty iterator if none found
735 */
736 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
737 bool search_unselected, bool closest)
738 {
739 NodeList::iterator match;
740 double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
741 if (_num_selected == 0 && !search_unselected) return match;
743 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
744 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
745 if(j->selected()) {
746 if (!search_selected) continue;
747 } else {
748 if (!search_unselected) continue;
749 }
750 double dist = Geom::distance(*j, *origin);
751 bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
752 if (cond) {
753 match = j;
754 extr_dist = dist;
755 }
756 }
757 }
758 return match;
759 }
761 /** Called by the XML observer when something else than us modifies the path. */
762 void PathManipulator::_externalChange(unsigned type)
763 {
764 switch (type) {
765 case PATH_CHANGE_D: {
766 _getGeometry();
768 // ugly: stored offsets of selected nodes in a vector
769 // vector<bool> should be specialized so that it takes only 1 bit per value
770 std::vector<bool> selpos;
771 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
772 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
773 selpos.push_back(j->selected());
774 }
775 }
776 unsigned size = selpos.size(), curpos = 0;
778 _createControlPointsFromGeometry();
780 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
781 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
782 if (curpos >= size) goto end_restore;
783 if (selpos[curpos]) _selection.insert(j.ptr());
784 ++curpos;
785 }
786 }
787 end_restore:
789 _updateOutline();
790 } break;
791 case PATH_CHANGE_TRANSFORM: {
792 Geom::Matrix i2d_change = _d2i_transform;
793 _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path));
794 _d2i_transform = _i2d_transform.inverse();
795 i2d_change *= _i2d_transform;
796 for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
797 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
798 j->transform(i2d_change);
799 }
800 }
801 _updateOutline();
802 } break;
803 default: break;
804 }
805 }
807 /** Create nodes and handles based on the XML of the edited path. */
808 void PathManipulator::_createControlPointsFromGeometry()
809 {
810 clear();
812 // sanitize pathvector and store it in SPCurve,
813 // so that _updateDragPoint doesn't crash on paths with naked movetos
814 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
815 for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
816 if (i->empty()) pathv.erase(i++);
817 else ++i;
818 }
819 _spcurve->set_pathvector(pathv);
821 pathv *= (_edit_transform * _i2d_transform);
823 // in this loop, we know that there are no zero-segment subpaths
824 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
825 // prepare new subpath
826 SubpathPtr subpath(new NodeList(_subpaths));
827 _subpaths.push_back(subpath);
829 Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
830 subpath->push_back(previous_node);
831 Geom::Curve const &cseg = pit->back_closed();
832 bool fuse_ends = pit->closed()
833 && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
835 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
836 Geom::Point pos = cit->finalPoint();
837 Node *current_node;
838 // if the closing segment is degenerate and the path is closed, we need to move
839 // the handle of the first node instead of creating a new one
840 if (fuse_ends && cit == --(pit->end_open())) {
841 current_node = subpath->begin().get_pointer();
842 } else {
843 /* regardless of segment type, create a new node at the end
844 * of this segment (unless this is the last segment of a closed path
845 * with a degenerate closing segment */
846 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
847 subpath->push_back(current_node);
848 }
849 // if this is a bezier segment, move handles appropriately
850 if (Geom::CubicBezier const *cubic_bezier =
851 dynamic_cast<Geom::CubicBezier const*>(&*cit))
852 {
853 std::vector<Geom::Point> points = cubic_bezier->points();
855 previous_node->front()->setPosition(points[1]);
856 current_node ->back() ->setPosition(points[2]);
857 }
858 previous_node = current_node;
859 }
860 // If the path is closed, make the list cyclic
861 if (pit->closed()) subpath->setClosed(true);
862 }
864 // we need to set the nodetypes after all the handles are in place,
865 // so that pickBestType works correctly
866 // TODO maybe migrate to inkscape:node-types?
867 gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0;
868 std::string nodetype_string = nts_raw ? nts_raw : "";
869 /* Calculate the needed length of the nodetype string.
870 * For closed paths, the entry is duplicated for the starting node,
871 * so we can just use the count of segments including the closing one
872 * to include the extra end node. */
873 std::string::size_type nodetype_len = 0;
874 for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
875 if (i->empty()) continue;
876 nodetype_len += i->size_closed();
877 }
878 /* pad the string to required length with a bogus value.
879 * 'b' and any other letter not recognized by the parser causes the best fit to be set
880 * as the node type */
881 if (nodetype_len > nodetype_string.size()) {
882 nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
883 }
884 std::string::iterator tsi = nodetype_string.begin();
885 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
886 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
887 j->setType(Node::parse_nodetype(*tsi++), false);
888 }
889 if ((*i)->closed()) {
890 // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
891 // the first one to remain backward compatible.
892 (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
893 }
894 }
895 }
897 /** Construct the geometric representation of nodes and handles, update the outline
898 * and display */
899 void PathManipulator::_createGeometryFromControlPoints()
900 {
901 Geom::PathBuilder builder;
902 for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
903 SubpathPtr subpath = *spi;
904 if (subpath->empty()) {
905 _subpaths.erase(spi++);
906 continue;
907 }
908 NodeList::iterator prev = subpath->begin();
909 builder.moveTo(prev->position());
911 for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
912 build_segment(builder, prev.ptr(), i.ptr());
913 prev = i;
914 }
915 if (subpath->closed()) {
916 // Here we link the last and first node if the path is closed.
917 // If the last segment is Bezier, we add it.
918 if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
919 build_segment(builder, prev.ptr(), subpath->begin().ptr());
920 }
921 // if that segment is linear, we just call closePath().
922 builder.closePath();
923 }
924 ++spi;
925 }
926 builder.finish();
927 _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
928 _updateOutline();
929 _setGeometry();
930 }
932 /** Build one segment of the geometric representation.
933 * @relates PathManipulator */
934 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
935 {
936 if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
937 {
938 // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
939 // and trying to display a path using them results in funny artifacts.
940 builder.lineTo(cur_node->position());
941 } else {
942 // this is a bezier segment
943 builder.curveTo(
944 prev_node->front()->position(),
945 cur_node->back()->position(),
946 cur_node->position());
947 }
948 }
950 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
951 std::string PathManipulator::_createTypeString()
952 {
953 // precondition: no single-node subpaths
954 std::stringstream tstr;
955 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
956 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
957 tstr << j->type();
958 }
959 // nodestring format peculiarity: first node is counted twice for closed paths
960 if ((*i)->closed()) tstr << (*i)->begin()->type();
961 }
962 return tstr.str();
963 }
965 /** Update the path outline. */
966 void PathManipulator::_updateOutline()
967 {
968 if (!_show_outline) {
969 sp_canvas_item_hide(_outline);
970 return;
971 }
973 Geom::PathVector pv = _spcurve->get_pathvector();
974 pv *= (_edit_transform * _i2d_transform);
975 // This SPCurve thing has to be killed with extreme prejudice
976 SPCurve *_hc = new SPCurve();
977 if (_show_path_direction) {
978 // To show the direction, we append additional subpaths which consist of a single
979 // linear segment that starts at the time value of 0.5 and extends for 10 pixels
980 // at an angle 150 degrees from the unit tangent. This creates the appearance
981 // of little 'harpoons' that show the direction of the subpaths.
982 Geom::PathVector arrows;
983 for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
984 Geom::Path &path = *i;
985 for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
986 Geom::Point at = j->pointAt(0.5);
987 Geom::Point ut = j->unitTangentAt(0.5);
988 // rotate the point
989 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
990 Geom::Point arrow_end = _desktop->w2d(
991 _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
993 Geom::Path arrow(at);
994 arrow.appendNew<Geom::LineSegment>(arrow_end);
995 arrows.push_back(arrow);
996 }
997 }
998 pv.insert(pv.end(), arrows.begin(), arrows.end());
999 }
1000 _hc->set_pathvector(pv);
1001 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1002 sp_canvas_item_show(_outline);
1003 _hc->unref();
1004 }
1006 /** Retrieve the geometry of the edited object from the object tree */
1007 void PathManipulator::_getGeometry()
1008 {
1009 using namespace Inkscape::LivePathEffect;
1010 if (!_lpe_key.empty()) {
1011 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1012 if (lpe) {
1013 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1014 if (!_spcurve)
1015 _spcurve = new SPCurve(pathparam->get_pathvector());
1016 else
1017 _spcurve->set_pathvector(pathparam->get_pathvector());
1018 }
1019 } else {
1020 if (_spcurve) _spcurve->unref();
1021 _spcurve = sp_path_get_curve_for_edit(_path);
1022 }
1023 }
1025 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1026 void PathManipulator::_setGeometry()
1027 {
1028 using namespace Inkscape::LivePathEffect;
1029 if (empty()) return;
1031 if (!_lpe_key.empty()) {
1032 // copied from nodepath.cpp
1033 // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1034 // a LivePathEffectObject. (mad laughter)
1035 Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1036 if (lpe) {
1037 PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1038 pathparam->set_new_value(_spcurve->get_pathvector(), false);
1039 LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1040 }
1041 } else {
1042 if (_path->repr->attribute("inkscape:original-d"))
1043 sp_path_set_original_curve(_path, _spcurve, true, false);
1044 else
1045 sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false);
1046 }
1047 }
1049 /** Figure out in what attribute to store the nodetype string. */
1050 Glib::ustring PathManipulator::_nodetypesKey()
1051 {
1052 if (_lpe_key.empty()) return "sodipodi:nodetypes";
1053 return _lpe_key + "-nodetypes";
1054 }
1056 /** Return the XML node we are editing.
1057 * This method is wrong but necessary at the moment. */
1058 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1059 {
1060 if (_lpe_key.empty()) return _path->repr;
1061 return LIVEPATHEFFECT(_path)->repr;
1062 }
1064 void PathManipulator::_attachNodeHandlers(Node *node)
1065 {
1066 Handle *handles[2] = { node->front(), node->back() };
1067 for (int i = 0; i < 2; ++i) {
1068 handles[i]->signal_update.connect(
1069 sigc::mem_fun(*this, &PathManipulator::update));
1070 handles[i]->signal_ungrabbed.connect(
1071 sigc::hide(
1072 sigc::mem_fun(*this, &PathManipulator::_handleUngrabbed)));
1073 handles[i]->signal_grabbed.connect(
1074 sigc::bind_return(
1075 sigc::hide(
1076 sigc::mem_fun(*this, &PathManipulator::_handleGrabbed)),
1077 false));
1078 handles[i]->signal_clicked.connect(
1079 sigc::bind<0>(
1080 sigc::mem_fun(*this, &PathManipulator::_handleClicked),
1081 handles[i]));
1082 }
1083 node->signal_clicked.connect(
1084 sigc::bind<0>(
1085 sigc::mem_fun(*this, &PathManipulator::_nodeClicked),
1086 node));
1087 }
1088 void PathManipulator::_removeNodeHandlers(Node *node)
1089 {
1090 // It is safe to assume that nobody else connected to handles' signals after us,
1091 // so we pop our slots from the back. This preserves existing connections
1092 // created by Node and Handle constructors.
1093 Handle *handles[2] = { node->front(), node->back() };
1094 for (int i = 0; i < 2; ++i) {
1095 handles[i]->signal_update.slots().pop_back();
1096 handles[i]->signal_grabbed.slots().pop_back();
1097 handles[i]->signal_ungrabbed.slots().pop_back();
1098 handles[i]->signal_clicked.slots().pop_back();
1099 }
1100 // Same for this one: CPS only connects to grab, drag, and ungrab
1101 node->signal_clicked.slots().pop_back();
1102 }
1104 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1105 {
1106 // cycle between node types on ctrl+click
1107 if (event->button != 1 || !held_control(*event)) return false;
1108 if (n->isEndNode()) {
1109 if (n->type() == NODE_CUSP) {
1110 n->setType(NODE_SMOOTH);
1111 } else {
1112 n->setType(NODE_CUSP);
1113 }
1114 } else {
1115 n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1116 }
1117 update();
1118 _commit(_("Cycle node type"));
1119 return true;
1120 }
1122 void PathManipulator::_handleGrabbed()
1123 {
1124 _selection.hideTransformHandles();
1125 }
1127 void PathManipulator::_handleUngrabbed()
1128 {
1129 _selection.restoreTransformHandles();
1130 _commit(_("Drag handle"));
1131 }
1133 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1134 {
1135 // retracting by Ctrl+click
1136 if (event->button == 1 && held_control(*event)) {
1137 h->move(h->parent()->position());
1138 update();
1139 _commit(_("Retract handle"));
1140 return true;
1141 }
1142 return false;
1143 }
1145 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1146 {
1147 // don't do anything if we do not show handles
1148 if (!_show_handles) return;
1150 // only do something if a node changed selection state
1151 Node *node = dynamic_cast<Node*>(p);
1152 if (!node) return;
1154 // update handle display
1155 NodeList::iterator iters[5];
1156 iters[2] = NodeList::get_iterator(node);
1157 iters[1] = iters[2].prev();
1158 iters[3] = iters[2].next();
1159 if (selected) {
1160 // selection - show handles on this node and adjacent ones
1161 node->showHandles(true);
1162 if (iters[1]) iters[1]->showHandles(true);
1163 if (iters[3]) iters[3]->showHandles(true);
1164 } else {
1165 /* Deselection is more complex.
1166 * The change might affect 3 nodes - this one and two adjacent.
1167 * If the node and both its neighbors are deselected, hide handles.
1168 * Otherwise, leave as is. */
1169 if (iters[1]) iters[0] = iters[1].prev();
1170 if (iters[3]) iters[4] = iters[3].next();
1171 bool nodesel[5];
1172 for (int i = 0; i < 5; ++i) {
1173 nodesel[i] = iters[i] && iters[i]->selected();
1174 }
1175 for (int i = 1; i < 4; ++i) {
1176 if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1177 iters[i]->showHandles(false);
1178 }
1179 }
1180 }
1182 if (selected) ++_num_selected;
1183 else --_num_selected;
1184 }
1186 /** Removes all nodes belonging to this manipulator from the control pont selection */
1187 void PathManipulator::_removeNodesFromSelection()
1188 {
1189 // remove this manipulator's nodes from selection
1190 for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1191 for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1192 _selection.erase(j.get_pointer());
1193 }
1194 }
1195 }
1197 /** Update the XML representation and put the specified annotation on the undo stack */
1198 void PathManipulator::_commit(Glib::ustring const &annotation)
1199 {
1200 writeXML();
1201 sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1202 }
1204 /** Update the position of the curve drag point such that it is over the nearest
1205 * point of the path. */
1206 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1207 {
1208 // TODO find a way to make this faster (no transform required)
1209 Geom::PathVector pv = _spcurve->get_pathvector() * (_edit_transform * _i2d_transform);
1210 boost::optional<Geom::PathVectorPosition> pvp
1211 = Geom::nearestPoint(pv, _desktop->w2d(evp));
1212 if (!pvp) return;
1213 Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t));
1215 double fracpart;
1216 std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1217 for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1218 NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1220 double stroke_tolerance = _getStrokeTolerance();
1221 if (Geom::distance(evp, nearest_point) < stroke_tolerance) {
1222 _dragpoint->setVisible(true);
1223 _dragpoint->setPosition(_desktop->w2d(nearest_point));
1224 _dragpoint->setSize(2 * stroke_tolerance);
1225 _dragpoint->setTimeValue(fracpart);
1226 _dragpoint->setIterator(first);
1227 } else {
1228 _dragpoint->setVisible(false);
1229 }
1230 }
1232 /// This is called on zoom change to update the direction arrows
1233 void PathManipulator::_updateOutlineOnZoomChange()
1234 {
1235 if (_show_path_direction) _updateOutline();
1236 }
1238 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1239 * or segment selection, in window coordinates. */
1240 double PathManipulator::_getStrokeTolerance()
1241 {
1242 /* Stroke event tolerance is equal to half the stroke's width plus the global
1243 * drag tolerance setting. */
1244 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1245 double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1246 if (_path && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1247 ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1248 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1249 * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1250 }
1251 return ret;
1252 }
1254 } // namespace UI
1255 } // namespace Inkscape
1257 /*
1258 Local Variables:
1259 mode:c++
1260 c-file-style:"stroustrup"
1261 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1262 indent-tabs-mode:nil
1263 fill-column:99
1264 End:
1265 */
1266 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :