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