Code

A simple layout document as to what, why and how is cppification.
[inkscape.git] / src / ui / tool / path-manipulator.cpp
1 /** @file
2  * Path manipulator - implementation
3  */
4 /* Authors:
5  *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
6  *
7  * Copyright (C) 2009 Authors
8  * Released under GNU GPL, read the file 'COPYING' for more information
9  */
11 #include <string>
12 #include <sstream>
13 #include <deque>
14 #include <stdexcept>
15 #include <boost/shared_ptr.hpp>
16 #include <2geom/bezier-curve.h>
17 #include <2geom/bezier-utils.h>
18 #include <2geom/svg-path.h>
19 #include <glibmm.h>
20 #include <glibmm/i18n.h>
21 #include "ui/tool/path-manipulator.h"
22 #include "desktop.h"
23 #include "desktop-handles.h"
24 #include "display/sp-canvas.h"
25 #include "display/sp-canvas-util.h"
26 #include "display/curve.h"
27 #include "display/canvas-bpath.h"
28 #include "document.h"
29 #include "live_effects/effect.h"
30 #include "live_effects/lpeobject.h"
31 #include "live_effects/parameter/path.h"
32 #include "sp-path.h"
33 #include "helper/geom.h"
34 #include "preferences.h"
35 #include "style.h"
36 #include "ui/tool/control-point-selection.h"
37 #include "ui/tool/curve-drag-point.h"
38 #include "ui/tool/event-utils.h"
39 #include "ui/tool/multi-path-manipulator.h"
40 #include "xml/node.h"
41 #include "xml/node-observer.h"
43 namespace Inkscape {
44 namespace UI {
46 namespace {
47 /// Types of path changes that we must react to.
48 enum PathChange {
49     PATH_CHANGE_D,
50     PATH_CHANGE_TRANSFORM
51 };
53 } // anonymous namespace
55 /**
56  * Notifies the path manipulator when something changes the path being edited
57  * (e.g. undo / redo)
58  */
59 class PathManipulatorObserver : public Inkscape::XML::NodeObserver {
60 public:
61     PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node)
62         : _pm(p)
63         , _node(node)
64         , _blocked(false)
65     {
66         Inkscape::GC::anchor(_node);
67         _node->addObserver(*this);
68     }
70     ~PathManipulatorObserver() {
71         _node->removeObserver(*this);
72         Inkscape::GC::release(_node);
73     }
75     virtual void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr,
76         Util::ptr_shared<char>, Util::ptr_shared<char>)
77     {
78         // do nothing if blocked
79         if (_blocked) return;
81         GQuark path_d = g_quark_from_static_string("d");
82         GQuark path_transform = g_quark_from_static_string("transform");
83         GQuark lpe_quark = _pm->_lpe_key.empty() ? 0 : g_quark_from_string(_pm->_lpe_key.data());
85         // only react to "d" (path data) and "transform" attribute changes
86         if (attr == lpe_quark || attr == path_d) {
87             _pm->_externalChange(PATH_CHANGE_D);
88         } else if (attr == path_transform) {
89             _pm->_externalChange(PATH_CHANGE_TRANSFORM);
90         }
91     }
93     void block() { _blocked = true; }
94     void unblock() { _blocked = false; }
95 private:
96     PathManipulator *_pm;
97     Inkscape::XML::Node *_node;
98     bool _blocked;
99 };
101 void build_segment(Geom::PathBuilder &, Node *, Node *);
103 PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path,
104         Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key)
105     : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection)
106     , _subpaths(*this)
107     , _multi_path_manipulator(mpm)
108     , _path(path)
109     , _spcurve(new SPCurve())
110     , _dragpoint(new CurveDragPoint(*this))
111     , /* XML Tree being used here directly while it shouldn't be*/_observer(new PathManipulatorObserver(this, SP_OBJECT(path)->getRepr()))
112     , _edit_transform(et)
113     , _num_selected(0)
114     , _show_handles(true)
115     , _show_outline(false)
116     , _show_path_direction(false)
117     , _live_outline(true)
118     , _live_objects(true)
119     , _lpe_key(lpe_key)
121     if (_lpe_key.empty()) {
122         _i2d_transform = SP_ITEM(path)->i2d_affine();
123     } else {
124         _i2d_transform = Geom::identity();
125     }
126     _d2i_transform = _i2d_transform.inverse();
127     _dragpoint->setVisible(false);
129     _getGeometry();
131     _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL);
132     sp_canvas_item_hide(_outline);
133     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0,
134         SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
135     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO);
137     _selection.signal_update.connect(
138         sigc::mem_fun(*this, &PathManipulator::update));
139     _selection.signal_point_changed.connect(
140         sigc::mem_fun(*this, &PathManipulator::_selectionChanged));
141     _desktop->signal_zoom_changed.connect(
142         sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange)));
144     _createControlPointsFromGeometry();
147 PathManipulator::~PathManipulator()
149     delete _dragpoint;
150     delete _observer;
151     gtk_object_destroy(_outline);
152     _spcurve->unref();
153     clear();
156 /** Handle motion events to update the position of the curve drag point. */
157 bool PathManipulator::event(GdkEvent *event)
159     if (empty()) return false;
161     switch (event->type)
162     {
163     case GDK_MOTION_NOTIFY:
164         _updateDragPoint(event_point(event->motion));
165         break;
166     default: break;
167     }
168     return false;
171 /** Check whether the manipulator has any nodes. */
172 bool PathManipulator::empty() {
173     return !_path || _subpaths.empty();
176 /** Update the display and the outline of the path. */
177 void PathManipulator::update()
179     _createGeometryFromControlPoints();
182 /** Store the changes to the path in XML. */
183 void PathManipulator::writeXML()
185     if (!_live_outline)
186         _updateOutline();
187     if (!_live_objects)
188         _setGeometry();
190     if (!_path) return;
191     _observer->block();
192     if (!empty()) {
193         SP_OBJECT(_path)->updateRepr();
194         _getXMLNode()->setAttribute(_nodetypesKey().data(), _createTypeString().data());
195     } else {
196         // this manipulator will have to be destroyed right after this call
197         _getXMLNode()->removeObserver(*_observer);
198         sp_object_ref(_path);
199         _path->deleteObject(true, true);
200         sp_object_unref(_path);
201         _path = 0;
202     }
203     _observer->unblock();
206 /** Remove all nodes from the path. */
207 void PathManipulator::clear()
209     // no longer necessary since nodes remove themselves from selection on destruction
210     //_removeNodesFromSelection();
211     _subpaths.clear();
214 /** Select all nodes in subpaths that have something selected. */
215 void PathManipulator::selectSubpaths()
217     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
218         NodeList::iterator sp_start = (*i)->begin(), sp_end = (*i)->end();
219         for (NodeList::iterator j = sp_start; j != sp_end; ++j) {
220             if (j->selected()) {
221                 // if at least one of the nodes from this subpath is selected,
222                 // select all nodes from this subpath
223                 for (NodeList::iterator ins = sp_start; ins != sp_end; ++ins)
224                     _selection.insert(ins.ptr());
225                 continue;
226             }
227         }
228     }
231 /** Move the selection forward or backward by one node in each subpath, based on the sign
232  * of the parameter. */
233 void PathManipulator::shiftSelection(int dir)
235     if (dir == 0) return;
236     if (_num_selected == 0) {
237         // select the first node of the path.
238         SubpathList::iterator s = _subpaths.begin();
239         if (s == _subpaths.end()) return;
240         NodeList::iterator n = (*s)->begin();
241         if (n != (*s)->end())
242             _selection.insert(n.ptr());
243         return;
244     }
245     // We cannot do any tricks here, like iterating in different directions based on
246     // the sign and only setting the selection of nodes behind us, because it would break
247     // for closed paths.
248     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
249         std::deque<bool> sels; // I hope this is specialized for bools!
250         unsigned num = 0;
251         
252         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
253             sels.push_back(j->selected());
254             _selection.erase(j.ptr());
255             ++num;
256         }
257         if (num == 0) continue; // should never happen! zero-node subpaths are not allowed
259         num = 0;
260         // In closed subpath, shift the selection cyclically. In an open one,
261         // let the selection 'slide into nothing' at ends.
262         if (dir > 0) {
263             if ((*i)->closed()) {
264                 bool last = sels.back();
265                 sels.pop_back();
266                 sels.push_front(last);
267             } else {
268                 sels.push_front(false);
269             }
270         } else {
271             if ((*i)->closed()) {
272                 bool first = sels.front();
273                 sels.pop_front();
274                 sels.push_back(first);
275             } else {
276                 sels.push_back(false);
277                 num = 1;
278             }
279         }
281         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
282             if (sels[num]) _selection.insert(j.ptr());
283             ++num;
284         }
285     }
288 /** Invert selection in the selected subpaths. */
289 void PathManipulator::invertSelectionInSubpaths()
291     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
292         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
293             if (j->selected()) {
294                 // found selected node - invert selection in this subpath
295                 for (NodeList::iterator k = (*i)->begin(); k != (*i)->end(); ++k) {
296                     if (k->selected()) _selection.erase(k.ptr());
297                     else _selection.insert(k.ptr());
298                 }
299                 // next subpath
300                 break;
301             }
302         }
303     }
306 /** Insert a new node in the middle of each selected segment. */
307 void PathManipulator::insertNodes()
309     if (_num_selected < 2) return;
311     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
312         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
313             NodeList::iterator k = j.next();
314             if (k && j->selected() && k->selected()) {
315                 j = subdivideSegment(j, 0.5);
316                 _selection.insert(j.ptr());
317             }
318         }
319     }
322 /** Replace contiguous selections of nodes in each subpath with one node. */
323 void PathManipulator::weldNodes(NodeList::iterator preserve_pos)
325     if (_num_selected < 2) return;
326     hideDragPoint();
328     bool pos_valid = preserve_pos;
329     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
330         SubpathPtr sp = *i;
331         unsigned num_selected = 0, num_unselected = 0;
332         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
333             if (j->selected()) ++num_selected;
334             else ++num_unselected;
335         }
336         if (num_selected < 2) continue;
337         if (num_unselected == 0) {
338             // if all nodes in a subpath are selected, the operation doesn't make much sense
339             continue;
340         }
342         // Start from unselected node in closed paths, so that we don't start in the middle
343         // of a selection
344         NodeList::iterator sel_beg = sp->begin(), sel_end;
345         if (sp->closed()) {
346             while (sel_beg->selected()) ++sel_beg;
347         }
349         // Work loop
350         while (num_selected > 0) {
351             // Find selected node
352             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
353             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
354                 "but there are still nodes to process!");
356             // note: this is initialized to zero, because the loop below counts sel_beg as well
357             // the loop conditions are simpler that way
358             unsigned num_points = 0;
359             bool use_pos = false;
360             Geom::Point back_pos, front_pos;
361             back_pos = *sel_beg->back();
363             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
364                 ++num_points;
365                 front_pos = *sel_end->front();
366                 if (pos_valid && sel_end == preserve_pos) use_pos = true;
367             }
368             if (num_points > 1) {
369                 Geom::Point joined_pos;
370                 if (use_pos) {
371                     joined_pos = preserve_pos->position();
372                     pos_valid = false;
373                 } else {
374                     joined_pos = Geom::middle_point(back_pos, front_pos);
375                 }
376                 sel_beg->setType(NODE_CUSP, false);
377                 sel_beg->move(joined_pos);
378                 // do not move handles if they aren't degenerate
379                 if (!sel_beg->back()->isDegenerate()) {
380                     sel_beg->back()->setPosition(back_pos);
381                 }
382                 if (!sel_end.prev()->front()->isDegenerate()) {
383                     sel_beg->front()->setPosition(front_pos);
384                 }
385                 sel_beg = sel_beg.next();
386                 while (sel_beg != sel_end) {
387                     NodeList::iterator next = sel_beg.next();
388                     sp->erase(sel_beg);
389                     sel_beg = next;
390                     --num_selected;
391                 }
392             }
393             --num_selected; // for the joined node or single selected node
394         }
395     }
398 /** Remove nodes in the middle of selected segments. */
399 void PathManipulator::weldSegments()
401     if (_num_selected < 2) return;
402     hideDragPoint();
404     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
405         SubpathPtr sp = *i;
406         unsigned num_selected = 0, num_unselected = 0;
407         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
408             if (j->selected()) ++num_selected;
409             else ++num_unselected;
410         }
411         if (num_selected < 3) continue;
412         if (num_unselected == 0 && sp->closed()) {
413             // if all nodes in a closed subpath are selected, the operation doesn't make much sense
414             continue;
415         }
417         // Start from unselected node in closed paths, so that we don't start in the middle
418         // of a selection
419         NodeList::iterator sel_beg = sp->begin(), sel_end;
420         if (sp->closed()) {
421             while (sel_beg->selected()) ++sel_beg;
422         }
424         // Work loop
425         while (num_selected > 0) {
426             // Find selected node
427             while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next();
428             if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, "
429                 "but there are still nodes to process!");
431             // note: this is initialized to zero, because the loop below counts sel_beg as well
432             // the loop conditions are simpler that way
433             unsigned num_points = 0;
435             // find the end of selected segment
436             for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) {
437                 ++num_points;
438             }
439             if (num_points > 2) {
440                 // remove nodes in the middle
441                 sel_beg = sel_beg.next();
442                 while (sel_beg != sel_end.prev()) {
443                     NodeList::iterator next = sel_beg.next();
444                     sp->erase(sel_beg);
445                     sel_beg = next;
446                 }
447                 sel_beg = sel_end;
448             }
449             num_selected -= num_points;
450         }
451     }
454 /** Break the subpath at selected nodes. It also works for single node closed paths. */
455 void PathManipulator::breakNodes()
457     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
458         SubpathPtr sp = *i;
459         NodeList::iterator cur = sp->begin(), end = sp->end();
460         if (!sp->closed()) {
461             // Each open path must have at least two nodes so no checks are required.
462             // For 2-node open paths, cur == end
463             ++cur;
464             --end;
465         }
466         for (; cur != end; ++cur) {
467             if (!cur->selected()) continue;
468             SubpathPtr ins;
469             bool becomes_open = false;
471             if (sp->closed()) {
472                 // Move the node to break at to the beginning of path
473                 if (cur != sp->begin())
474                     sp->splice(sp->begin(), *sp, cur, sp->end());
475                 sp->setClosed(false);
476                 ins = sp;
477                 becomes_open = true;
478             } else {
479                 SubpathPtr new_sp(new NodeList(_subpaths));
480                 new_sp->splice(new_sp->end(), *sp, sp->begin(), cur);
481                 _subpaths.insert(i, new_sp);
482                 ins = new_sp;
483             }
485             Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position());
486             ins->insert(ins->end(), n);
487             cur->setType(NODE_CUSP, false);
488             n->back()->setRelativePos(cur->back()->relativePos());
489             cur->back()->retract();
490             n->sink();
492             if (becomes_open) {
493                 cur = sp->begin(); // this will be increased to ++sp->begin()
494                 end = --sp->end();
495             }
496         }
497     }
500 /** Delete selected nodes in the path, optionally substituting deleted segments with bezier curves
501  * in a way that attempts to preserve the original shape of the curve. */
502 void PathManipulator::deleteNodes(bool keep_shape)
504     if (_num_selected == 0) return;
505     hideDragPoint();
507     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
508         SubpathPtr sp = *i;
510         // If there are less than 2 unselected nodes in an open subpath or no unselected nodes
511         // in a closed one, delete entire subpath.
512         unsigned num_unselected = 0, num_selected = 0;
513         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
514             if (j->selected()) ++num_selected;
515             else ++num_unselected;
516         }
517         if (num_selected == 0) {
518             ++i;
519             continue;
520         }
521         if (sp->closed() ? (num_unselected < 1) : (num_unselected < 2)) {
522             _subpaths.erase(i++);
523             continue;
524         }
526         // In closed paths, start from an unselected node - otherwise we might start in the middle
527         // of a selected stretch and the resulting bezier fit would be suboptimal
528         NodeList::iterator sel_beg = sp->begin(), sel_end;
529         if (sp->closed()) {
530             while (sel_beg->selected()) ++sel_beg;
531         }
532         sel_end = sel_beg;
533         
534         while (num_selected > 0) {
535             while (sel_beg && !sel_beg->selected()) {
536                 sel_beg = sel_beg.next();
537             }
538             sel_end = sel_beg;
540             while (sel_end && sel_end->selected()) {
541                 sel_end = sel_end.next();
542             }
543             
544             num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape);
545             sel_beg = sel_end;
546         }
547         ++i;
548     }
551 /** @brief Delete nodes between the two iterators.
552  * The given range can cross the beginning of the subpath in closed subpaths.
553  * @param start      Beginning of the range to delete
554  * @param end        End of the range
555  * @param keep_shape Whether to fit the handles at surrounding nodes to approximate
556  *                   the shape before deletion
557  * @return Number of deleted nodes */
558 unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape)
560     unsigned const samples_per_segment = 10;
561     double const t_step = 1.0 / samples_per_segment;
563     unsigned del_len = 0;
564     for (NodeList::iterator i = start; i != end; i = i.next()) {
565         ++del_len;
566     }
567     if (del_len == 0) return 0;
569     // set surrounding node types to cusp if:
570     // 1. keep_shape is on, or
571     // 2. we are deleting at the end or beginning of an open path
572     if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false);
573     if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false);
575     if (keep_shape && start.prev() && end) {
576         unsigned num_samples = (del_len + 1) * samples_per_segment + 1;
577         Geom::Point *bezier_data = new Geom::Point[num_samples];
578         Geom::Point result[4];
579         unsigned seg = 0;
581         for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) {
582             Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back());
583             for (unsigned s = 0; s < samples_per_segment; ++s) {
584                 bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s);
585             }
586             ++seg;
587         }
588         // Fill last point
589         bezier_data[num_samples - 1] = end->position();
590         // Compute replacement bezier curve
591         // TODO the fitting algorithm sucks - rewrite it to be awesome
592         bezier_fit_cubic(result, bezier_data, num_samples, 0.5);
593         delete[] bezier_data;
595         start.prev()->front()->setPosition(result[1]);
596         end->back()->setPosition(result[2]);
597     }
599     // We can't use nl->erase(start, end), because it would break when the stretch
600     // crosses the beginning of a closed subpath
601     NodeList &nl = start->nodeList();
602     while (start != end) {
603         NodeList::iterator next = start.next();
604         nl.erase(start);
605         start = next;
606     }
608     return del_len;
611 /** Removes selected segments */
612 void PathManipulator::deleteSegments()
614     if (_num_selected == 0) return;
615     hideDragPoint();
617     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) {
618         SubpathPtr sp = *i;
619         bool has_unselected = false;
620         unsigned num_selected = 0;
621         for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) {
622             if (j->selected()) {
623                 ++num_selected;
624             } else {
625                 has_unselected = true;
626             }
627         }
628         if (!has_unselected) {
629             _subpaths.erase(i++);
630             continue;
631         }
633         NodeList::iterator sel_beg = sp->begin();
634         if (sp->closed()) {
635             while (sel_beg && sel_beg->selected()) ++sel_beg;
636         }
637         while (num_selected > 0) {
638             if (!sel_beg->selected()) {
639                 sel_beg = sel_beg.next();
640                 continue;
641             }
642             NodeList::iterator sel_end = sel_beg;
643             unsigned num_points = 0;
644             while (sel_end && sel_end->selected()) {
645                 sel_end = sel_end.next();
646                 ++num_points;
647             }
648             if (num_points >= 2) {
649                 // Retract end handles
650                 sel_end.prev()->setType(NODE_CUSP, false);
651                 sel_end.prev()->back()->retract();
652                 sel_beg->setType(NODE_CUSP, false);
653                 sel_beg->front()->retract();
654                 if (sp->closed()) {
655                     // In closed paths, relocate the beginning of the path to the last selected
656                     // node and then unclose it. Remove the nodes from the first selected node
657                     // to the new end of path.
658                     if (sel_end.prev() != sp->begin())
659                         sp->splice(sp->begin(), *sp, sel_end.prev(), sp->end());
660                     sp->setClosed(false);
661                     sp->erase(sel_beg.next(), sp->end());
662                 } else {
663                     // for open paths:
664                     // 1. At end or beginning, delete including the node on the end or beginning
665                     // 2. In the middle, delete only inner nodes
666                     if (sel_beg == sp->begin()) {
667                         sp->erase(sp->begin(), sel_end.prev());
668                     } else if (sel_end == sp->end()) {
669                         sp->erase(sel_beg.next(), sp->end());
670                     } else {
671                         SubpathPtr new_sp(new NodeList(_subpaths));
672                         new_sp->splice(new_sp->end(), *sp, sp->begin(), sel_beg.next());
673                         _subpaths.insert(i, new_sp);
674                         if (sel_end.prev())
675                             sp->erase(sp->begin(), sel_end.prev());
676                     }
677                 }
678             }
679             sel_beg = sel_end;
680             num_selected -= num_points;
681         }
682         ++i;
683     }
686 /** Reverse subpaths of the path.
687  * @param selected_only If true, only paths that have at least one selected node
688  *                      will be reversed. Otherwise all subpaths will be reversed. */
689 void PathManipulator::reverseSubpaths(bool selected_only)
691     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
692         if (selected_only) {
693             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
694                 if (j->selected()) {
695                     (*i)->reverse();
696                     break; // continue with the next subpath
697                 }
698             }
699         } else {
700             (*i)->reverse();
701         }
702     }
705 /** Make selected segments curves / lines. */
706 void PathManipulator::setSegmentType(SegmentType type)
708     if (_num_selected == 0) return;
709     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
710         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
711             NodeList::iterator k = j.next();
712             if (!(k && j->selected() && k->selected())) continue;
713             switch (type) {
714             case SEGMENT_STRAIGHT:
715                 if (j->front()->isDegenerate() && k->back()->isDegenerate())
716                     break;
717                 j->front()->move(*j);
718                 k->back()->move(*k);
719                 break;
720             case SEGMENT_CUBIC_BEZIER:
721                 if (!j->front()->isDegenerate() || !k->back()->isDegenerate())
722                     break;
723                 // move both handles to 1/3 of the line
724                 j->front()->move(j->position() + (k->position() - j->position()) / 3);
725                 k->back()->move(k->position() + (j->position() - k->position()) / 3);
726                 break;
727             }
728         }
729     }
732 void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel)
734     if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) {
735         n->setType(NODE_SMOOTH);
736     }
737     Handle *h = _chooseHandle(n, which);
738     double length_change;
740     if (pixel) {
741         length_change = 1.0 / _desktop->current_zoom() * dir;
742     } else {
743         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
744         length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000);
745         length_change *= dir;
746     }
748     Geom::Point relpos;
749     if (h->isDegenerate()) {
750         if (dir < 0) return;
751         Node *nh = n->nodeToward(h);
752         if (!nh) return;
753         relpos = Geom::unit_vector(nh->position() - n->position()) * length_change;
754     } else {
755         relpos = h->relativePos();
756         double rellen = relpos.length();
757         relpos *= ((rellen + length_change) / rellen);
758     }
759     h->setRelativePos(relpos);
760     update();
762     gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right";
763     _commit(_("Scale handle"), key);
766 void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel)
768     if (n->type() != NODE_CUSP) {
769         n->setType(NODE_CUSP);
770     }
771     Handle *h = _chooseHandle(n, which);
772     if (h->isDegenerate()) return;
774     double angle;
775     if (pixel) {
776         // Rotate by "one pixel"
777         angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir;
778     } else {
779         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
780         int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000);
781         angle = M_PI * dir / snaps;
782     }
784     h->setRelativePos(h->relativePos() * Geom::Rotate(angle));
785     update();
786     gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right";
787     _commit(_("Rotate handle"), key);
790 Handle *PathManipulator::_chooseHandle(Node *n, int which)
792     NodeList::iterator i = NodeList::get_iterator(n);
793     Node *prev = i.prev().ptr();
794     Node *next = i.next().ptr();
796     // on an endnode, the remaining handle automatically wins
797     if (!next) return n->back();
798     if (!prev) return n->front();
800     // compare X coord ofline segments
801     Geom::Point npos = next->position();
802     Geom::Point ppos = prev->position();
803     if (which < 0) {
804         // pick left handle.
805         // we just swap the handles and pick the right handle below.
806         std::swap(npos, ppos);
807     }
809     if (npos[Geom::X] >= ppos[Geom::X]) {
810         return n->front();
811     } else {
812         return n->back();
813     }
816 /** Set the visibility of handles. */
817 void PathManipulator::showHandles(bool show)
819     if (show == _show_handles) return;
820     if (show) {
821         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
822             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
823                 if (!j->selected()) continue;
824                 j->showHandles(true);
825                 if (j.prev()) j.prev()->showHandles(true);
826                 if (j.next()) j.next()->showHandles(true);
827             }
828         }
829     } else {
830         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
831             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
832                 j->showHandles(false);
833             }
834         }
835     }
836     _show_handles = show;
839 /** Set the visibility of outline. */
840 void PathManipulator::showOutline(bool show)
842     if (show == _show_outline) return;
843     _show_outline = show;
844     _updateOutline();
847 void PathManipulator::showPathDirection(bool show)
849     if (show == _show_path_direction) return;
850     _show_path_direction = show;
851     _updateOutline();
854 void PathManipulator::setLiveOutline(bool set)
856     _live_outline = set;
859 void PathManipulator::setLiveObjects(bool set)
861     _live_objects = set;
864 void PathManipulator::setControlsTransform(Geom::Matrix const &tnew)
866     Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform;
867     _edit_transform = tnew;
868     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
869         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
870             j->transform(delta);
871         }
872     }
873     _createGeometryFromControlPoints();
876 /** Hide the curve drag point until the next motion event.
877  * This should be called at the beginning of every method that can delete nodes.
878  * Otherwise the invalidated iterator in the dragpoint can cause crashes. */
879 void PathManipulator::hideDragPoint()
881     _dragpoint->setVisible(false);
882     _dragpoint->setIterator(NodeList::iterator());
885 /** Insert a node in the segment beginning with the supplied iterator,
886  * at the given time value */
887 NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, double t)
889     if (!first) throw std::invalid_argument("Subdivide after invalid iterator");
890     NodeList &list = NodeList::get(first);
891     NodeList::iterator second = first.next();
892     if (!second) throw std::invalid_argument("Subdivide after last node in open path");
894     // We need to insert the segment after 'first'. We can't simply use 'second'
895     // as the point of insertion, because when 'first' is the last node of closed path,
896     // the new node will be inserted as the first node instead.
897     NodeList::iterator insert_at = first;
898     ++insert_at;
900     NodeList::iterator inserted;
901     if (first->front()->isDegenerate() && second->back()->isDegenerate()) {
902         // for a line segment, insert a cusp node
903         Node *n = new Node(_multi_path_manipulator._path_data.node_data,
904             Geom::lerp(t, first->position(), second->position()));
905         n->setType(NODE_CUSP, false);
906         inserted = list.insert(insert_at, n);
907     } else {
908         // build bezier curve and subdivide
909         Geom::CubicBezier temp(first->position(), first->front()->position(),
910             second->back()->position(), second->position());
911         std::pair<Geom::CubicBezier, Geom::CubicBezier> div = temp.subdivide(t);
912         std::vector<Geom::Point> seg1 = div.first.points(), seg2 = div.second.points();
914         // set new handle positions
915         Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]);
916         n->back()->setPosition(seg1[2]);
917         n->front()->setPosition(seg2[1]);
918         n->setType(NODE_SMOOTH, false);
919         inserted = list.insert(insert_at, n);
921         first->front()->move(seg1[1]);
922         second->back()->move(seg2[2]);
923     }
924     return inserted;
927 /** Find the node that is closest/farthest from the origin
928  * @param origin Point of reference
929  * @param search_selected Consider selected nodes
930  * @param search_unselected Consider unselected nodes
931  * @param closest If true, return closest node, if false, return farthest
932  * @return The matching node, or an empty iterator if none found
933  */
934 NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected,
935     bool search_unselected, bool closest)
937     NodeList::iterator match;
938     double extr_dist = closest ? HUGE_VAL : -HUGE_VAL;
939     if (_num_selected == 0 && !search_unselected) return match;
941     for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
942         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
943             if(j->selected()) {
944                 if (!search_selected) continue;
945             } else {
946                 if (!search_unselected) continue;
947             }
948             double dist = Geom::distance(*j, *origin);
949             bool cond = closest ? (dist < extr_dist) : (dist > extr_dist);
950             if (cond) {
951                 match = j;
952                 extr_dist = dist;
953             }
954         }
955     }
956     return match;
959 /** Called by the XML observer when something else than us modifies the path. */
960 void PathManipulator::_externalChange(unsigned type)
962     switch (type) {
963     case PATH_CHANGE_D: {
964         _getGeometry();
966         // ugly: stored offsets of selected nodes in a vector
967         // vector<bool> should be specialized so that it takes only 1 bit per value
968         std::vector<bool> selpos;
969         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
970             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
971                 selpos.push_back(j->selected());
972             }
973         }
974         unsigned size = selpos.size(), curpos = 0;
976         _createControlPointsFromGeometry();
978         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
979             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
980                 if (curpos >= size) goto end_restore;
981                 if (selpos[curpos]) _selection.insert(j.ptr());
982                 ++curpos;
983             }
984         }
985         end_restore:
987         _updateOutline();
988         } break;
989     case PATH_CHANGE_TRANSFORM: {
990         Geom::Matrix i2d_change = _d2i_transform;
991         _i2d_transform = SP_ITEM(_path)->i2d_affine();
992         _d2i_transform = _i2d_transform.inverse();
993         i2d_change *= _i2d_transform;
994         for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
995             for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
996                 j->transform(i2d_change);
997             }
998         }
999         _updateOutline();
1000         } break;
1001     default: break;
1002     }
1005 /** Create nodes and handles based on the XML of the edited path. */
1006 void PathManipulator::_createControlPointsFromGeometry()
1008     clear();
1010     // sanitize pathvector and store it in SPCurve,
1011     // so that _updateDragPoint doesn't crash on paths with naked movetos
1012     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector());
1013     for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) {
1014         // NOTE: this utilizes the fact that Geom::PathVector is an std::vector.
1015         // When we erase an element, the next one slides into position,
1016         // so we do not increment the iterator even though it is theoretically invalidated.
1017         if (i->empty()) {
1018             pathv.erase(i);
1019         } else {
1020             ++i;
1021         }
1022     }
1023     _spcurve->set_pathvector(pathv);
1025     pathv *= (_edit_transform * _i2d_transform);
1027     // in this loop, we know that there are no zero-segment subpaths
1028     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
1029         // prepare new subpath
1030         SubpathPtr subpath(new NodeList(_subpaths));
1031         _subpaths.push_back(subpath);
1033         Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint());
1034         subpath->push_back(previous_node);
1035         Geom::Curve const &cseg = pit->back_closed();
1036         bool fuse_ends = pit->closed()
1037             && Geom::are_near(cseg.initialPoint(), cseg.finalPoint());
1039         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_open(); ++cit) {
1040             Geom::Point pos = cit->finalPoint();
1041             Node *current_node;
1042             // if the closing segment is degenerate and the path is closed, we need to move
1043             // the handle of the first node instead of creating a new one
1044             if (fuse_ends && cit == --(pit->end_open())) {
1045                 current_node = subpath->begin().get_pointer();
1046             } else {
1047                 /* regardless of segment type, create a new node at the end
1048                  * of this segment (unless this is the last segment of a closed path
1049                  * with a degenerate closing segment */
1050                 current_node = new Node(_multi_path_manipulator._path_data.node_data, pos);
1051                 subpath->push_back(current_node);
1052             }
1053             // if this is a bezier segment, move handles appropriately
1054             if (Geom::CubicBezier const *cubic_bezier =
1055                 dynamic_cast<Geom::CubicBezier const*>(&*cit))
1056             {
1057                 std::vector<Geom::Point> points = cubic_bezier->points();
1059                 previous_node->front()->setPosition(points[1]);
1060                 current_node ->back() ->setPosition(points[2]);
1061             }
1062             previous_node = current_node;
1063         }
1064         // If the path is closed, make the list cyclic
1065         if (pit->closed()) subpath->setClosed(true);
1066     }
1068     // we need to set the nodetypes after all the handles are in place,
1069     // so that pickBestType works correctly
1070     // TODO maybe migrate to inkscape:node-types?
1071     // TODO move this into SPPath - do not manipulate directly
1073         //XML Tree being used here directly while it shouldn't be.
1074     gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : 0;
1075     std::string nodetype_string = nts_raw ? nts_raw : "";
1076     /* Calculate the needed length of the nodetype string.
1077      * For closed paths, the entry is duplicated for the starting node,
1078      * so we can just use the count of segments including the closing one
1079      * to include the extra end node. */
1080     std::string::size_type nodetype_len = 0;
1081     for (Geom::PathVector::const_iterator i = pathv.begin(); i != pathv.end(); ++i) {
1082         if (i->empty()) continue;
1083         nodetype_len += i->size_closed();
1084     }
1085     /* pad the string to required length with a bogus value.
1086      * 'b' and any other letter not recognized by the parser causes the best fit to be set
1087      * as the node type */
1088     if (nodetype_len > nodetype_string.size()) {
1089         nodetype_string.append(nodetype_len - nodetype_string.size(), 'b');
1090     }
1091     std::string::iterator tsi = nodetype_string.begin();
1092     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1093         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1094             j->setType(Node::parse_nodetype(*tsi++), false);
1095         }
1096         if ((*i)->closed()) {
1097             // STUPIDITY ALERT: it seems we need to use the duplicate type symbol instead of
1098             // the first one to remain backward compatible.
1099             (*i)->begin()->setType(Node::parse_nodetype(*tsi++), false);
1100         }
1101     }
1104 /** Construct the geometric representation of nodes and handles, update the outline
1105  * and display */
1106 void PathManipulator::_createGeometryFromControlPoints()
1108     Geom::PathBuilder builder;
1109     for (std::list<SubpathPtr>::iterator spi = _subpaths.begin(); spi != _subpaths.end(); ) {
1110         SubpathPtr subpath = *spi;
1111         if (subpath->empty()) {
1112             _subpaths.erase(spi++);
1113             continue;
1114         }
1115         NodeList::iterator prev = subpath->begin();
1116         builder.moveTo(prev->position());
1118         for (NodeList::iterator i = ++subpath->begin(); i != subpath->end(); ++i) {
1119             build_segment(builder, prev.ptr(), i.ptr());
1120             prev = i;
1121         }
1122         if (subpath->closed()) {
1123             // Here we link the last and first node if the path is closed.
1124             // If the last segment is Bezier, we add it.
1125             if (!prev->front()->isDegenerate() || !subpath->begin()->back()->isDegenerate()) {
1126                 build_segment(builder, prev.ptr(), subpath->begin().ptr());
1127             }
1128             // if that segment is linear, we just call closePath().
1129             builder.closePath();
1130         }
1131         ++spi;
1132     }
1133     builder.finish();
1134     _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse());
1135     if (_live_outline)
1136         _updateOutline();
1137     if (_live_objects)
1138         _setGeometry();
1141 /** Build one segment of the geometric representation.
1142  * @relates PathManipulator */
1143 void build_segment(Geom::PathBuilder &builder, Node *prev_node, Node *cur_node)
1145     if (cur_node->back()->isDegenerate() && prev_node->front()->isDegenerate())
1146     {
1147         // NOTE: It seems like the renderer cannot correctly handle vline / hline segments,
1148         // and trying to display a path using them results in funny artifacts.
1149         builder.lineTo(cur_node->position());
1150     } else {
1151         // this is a bezier segment
1152         builder.curveTo(
1153             prev_node->front()->position(),
1154             cur_node->back()->position(),
1155             cur_node->position());
1156     }
1159 /** Construct a node type string to store in the sodipodi:nodetypes attribute. */
1160 std::string PathManipulator::_createTypeString()
1162     // precondition: no single-node subpaths
1163     std::stringstream tstr;
1164     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1165         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1166             tstr << j->type();
1167         }
1168         // nodestring format peculiarity: first node is counted twice for closed paths
1169         if ((*i)->closed()) tstr << (*i)->begin()->type();
1170     }
1171     return tstr.str();
1174 /** Update the path outline. */
1175 void PathManipulator::_updateOutline()
1177     if (!_show_outline) {
1178         sp_canvas_item_hide(_outline);
1179         return;
1180     }
1182     Geom::PathVector pv = _spcurve->get_pathvector();
1183     pv *= (_edit_transform * _i2d_transform);
1184     // This SPCurve thing has to be killed with extreme prejudice
1185     SPCurve *_hc = new SPCurve();
1186     if (_show_path_direction) {
1187         // To show the direction, we append additional subpaths which consist of a single
1188         // linear segment that starts at the time value of 0.5 and extends for 10 pixels
1189         // at an angle 150 degrees from the unit tangent. This creates the appearance
1190         // of little 'harpoons' that show the direction of the subpaths.
1191         Geom::PathVector arrows;
1192         for (Geom::PathVector::iterator i = pv.begin(); i != pv.end(); ++i) {
1193             Geom::Path &path = *i;
1194             for (Geom::Path::const_iterator j = path.begin(); j != path.end_default(); ++j) {
1195                 Geom::Point at = j->pointAt(0.5);
1196                 Geom::Point ut = j->unitTangentAt(0.5);
1197                 // rotate the point 
1198                 ut *= Geom::Rotate(150.0 / 180.0 * M_PI);
1199                 Geom::Point arrow_end = _desktop->w2d(
1200                     _desktop->d2w(at) + Geom::unit_vector(_desktop->d2w(ut)) * 10.0);
1202                 Geom::Path arrow(at);
1203                 arrow.appendNew<Geom::LineSegment>(arrow_end);
1204                 arrows.push_back(arrow);
1205             }
1206         }
1207         pv.insert(pv.end(), arrows.begin(), arrows.end());
1208     }
1209     _hc->set_pathvector(pv);
1210     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(_outline), _hc);
1211     sp_canvas_item_show(_outline);
1212     _hc->unref();
1215 /** Retrieve the geometry of the edited object from the object tree */
1216 void PathManipulator::_getGeometry()
1218     using namespace Inkscape::LivePathEffect;
1219     if (!_lpe_key.empty()) {
1220         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1221         if (lpe) {
1222             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1223             _spcurve->unref();
1224             _spcurve = new SPCurve(pathparam->get_pathvector());
1225         }
1226     } else {
1227         _spcurve->unref();
1228         _spcurve = sp_path_get_curve_for_edit(_path);
1229     }
1232 /** Set the geometry of the edited object in the object tree, but do not commit to XML */
1233 void PathManipulator::_setGeometry()
1235     using namespace Inkscape::LivePathEffect;
1236     if (empty()) return;
1238     if (!_lpe_key.empty()) {
1239         // copied from nodepath.cpp
1240         // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is
1241         // a LivePathEffectObject. (mad laughter)
1242         Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe();
1243         if (lpe) {
1244             PathParam *pathparam = dynamic_cast<PathParam *>(lpe->getParameter(_lpe_key.data()));
1245             pathparam->set_new_value(_spcurve->get_pathvector(), false);
1246             LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG);
1247         }
1248     } else {
1249                 //XML Tree being used here directly while it shouldn't be.
1250         if (_path->getRepr()->attribute("inkscape:original-d"))
1251             sp_path_set_original_curve(_path, _spcurve, false, false);
1252         else
1253             SP_SHAPE(_path)->setCurve(_spcurve, false);
1254     }
1257 /** Figure out in what attribute to store the nodetype string. */
1258 Glib::ustring PathManipulator::_nodetypesKey()
1260     if (_lpe_key.empty()) return "sodipodi:nodetypes";
1261     return _lpe_key + "-nodetypes";
1264 /** Return the XML node we are editing.
1265  * This method is wrong but necessary at the moment. */
1266 Inkscape::XML::Node *PathManipulator::_getXMLNode()
1268         //XML Tree being used here directly while it shouldn't be.
1269     if (_lpe_key.empty()) return _path->getRepr();
1270         //XML Tree being used here directly while it shouldn't be.
1271     return LIVEPATHEFFECT(_path)->getRepr();
1274 bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event)
1276     if (event->button != 1) return false;
1277     if (held_alt(*event) && held_control(*event)) {
1278         // Ctrl+Alt+click: delete nodes
1279         hideDragPoint();
1280         NodeList::iterator iter = NodeList::get_iterator(n);
1281         NodeList &nl = iter->nodeList();
1283         if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) {
1284             // Removing last node of closed path - delete it
1285             nl.kill();
1286         } else {
1287             // In other cases, delete the node under cursor
1288             _deleteStretch(iter, iter.next(), true);
1289         }
1291         if (!empty()) { 
1292             update();
1293         }
1294         // We need to call MPM's method because it could have been our last node
1295         _multi_path_manipulator._doneWithCleanup(_("Delete node"));
1297         return true;
1298     } else if (held_control(*event)) {
1299         // Ctrl+click: cycle between node types
1300         if (n->isEndNode()) {
1301             if (n->type() == NODE_CUSP) {
1302                 n->setType(NODE_SMOOTH);
1303             } else {
1304                 n->setType(NODE_CUSP);
1305             }
1306         } else {
1307             n->setType(static_cast<NodeType>((n->type() + 1) % NODE_LAST_REAL_TYPE));
1308         }
1309         update();
1310         _commit(_("Cycle node type"));
1311         return true;
1312     }
1313     return false;
1316 void PathManipulator::_handleGrabbed()
1318     _selection.hideTransformHandles();
1321 void PathManipulator::_handleUngrabbed()
1323     _selection.restoreTransformHandles();
1324     _commit(_("Drag handle"));
1327 bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event)
1329     // retracting by Ctrl+click
1330     if (event->button == 1 && held_control(*event)) {
1331         h->move(h->parent()->position());
1332         update();
1333         _commit(_("Retract handle"));
1334         return true;
1335     }
1336     return false;
1339 void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected)
1341     if (selected) ++_num_selected;
1342     else --_num_selected;
1344     // don't do anything if we do not show handles
1345     if (!_show_handles) return;
1347     // only do something if a node changed selection state
1348     Node *node = dynamic_cast<Node*>(p);
1349     if (!node) return;
1351     // update handle display
1352     NodeList::iterator iters[5];
1353     iters[2] = NodeList::get_iterator(node);
1354     iters[1] = iters[2].prev();
1355     iters[3] = iters[2].next();
1356     if (selected) {
1357         // selection - show handles on this node and adjacent ones
1358         node->showHandles(true);
1359         if (iters[1]) iters[1]->showHandles(true);
1360         if (iters[3]) iters[3]->showHandles(true);
1361     } else {
1362         /* Deselection is more complex.
1363          * The change might affect 3 nodes - this one and two adjacent.
1364          * If the node and both its neighbors are deselected, hide handles.
1365          * Otherwise, leave as is. */
1366         if (iters[1]) iters[0] = iters[1].prev();
1367         if (iters[3]) iters[4] = iters[3].next();
1368         bool nodesel[5];
1369         for (int i = 0; i < 5; ++i) {
1370             nodesel[i] = iters[i] && iters[i]->selected();
1371         }
1372         for (int i = 1; i < 4; ++i) {
1373             if (iters[i] && !nodesel[i-1] && !nodesel[i] && !nodesel[i+1]) {
1374                 iters[i]->showHandles(false);
1375             }
1376         }
1377     }
1380 /** Removes all nodes belonging to this manipulator from the control pont selection */
1381 void PathManipulator::_removeNodesFromSelection()
1383     // remove this manipulator's nodes from selection
1384     for (std::list<SubpathPtr>::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) {
1385         for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {
1386             _selection.erase(j.get_pointer());
1387         }
1388     }
1391 /** Update the XML representation and put the specified annotation on the undo stack */
1392 void PathManipulator::_commit(Glib::ustring const &annotation)
1394     writeXML();
1395     SPDocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data());
1398 void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key)
1400     writeXML();
1401     SPDocumentUndo::maybe_done(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE,
1402             annotation.data());
1405 /** Update the position of the curve drag point such that it is over the nearest
1406  * point of the path. */
1407 void PathManipulator::_updateDragPoint(Geom::Point const &evp)
1409     Geom::Matrix to_desktop = _edit_transform * _i2d_transform;
1410     Geom::PathVector pv = _spcurve->get_pathvector();
1411     boost::optional<Geom::PathVectorPosition> pvp
1412         = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse());
1413     if (!pvp) return;
1414     Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop);
1415     
1416     double fracpart;
1417     std::list<SubpathPtr>::iterator spi = _subpaths.begin();
1418     for (unsigned i = 0; i < pvp->path_nr; ++i, ++spi) {}
1419     NodeList::iterator first = (*spi)->before(pvp->t, &fracpart);
1420     
1421     double stroke_tolerance = _getStrokeTolerance();
1422     if (Geom::distance(evp, nearest_point) < stroke_tolerance) {
1423         _dragpoint->setVisible(true);
1424         _dragpoint->setPosition(_desktop->w2d(nearest_point));
1425         _dragpoint->setSize(2 * stroke_tolerance);
1426         _dragpoint->setTimeValue(fracpart);
1427         _dragpoint->setIterator(first);
1428     } else {
1429         _dragpoint->setVisible(false);
1430     }
1433 /// This is called on zoom change to update the direction arrows
1434 void PathManipulator::_updateOutlineOnZoomChange()
1436     if (_show_path_direction) _updateOutline();
1439 /** Compute the radius from the edge of the path where clicks chould initiate a curve drag
1440  * or segment selection, in window coordinates. */
1441 double PathManipulator::_getStrokeTolerance()
1443     /* Stroke event tolerance is equal to half the stroke's width plus the global
1444      * drag tolerance setting.  */
1445     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1446     double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100);
1447     if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) {
1448         ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5
1449             * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords
1450             * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords
1451     }
1452     return ret;
1455 } // namespace UI
1456 } // namespace Inkscape
1458 /*
1459   Local Variables:
1460   mode:c++
1461   c-file-style:"stroustrup"
1462   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1463   indent-tabs-mode:nil
1464   fill-column:99
1465   End:
1466 */
1467 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :