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