X-Git-Url: https://git.tokkee.org/?a=blobdiff_plain;f=src%2Fui%2Ftool%2Fpath-manipulator.cpp;h=5ae9c4137255c7ab9cc1db66f7cb700045190448;hb=9dc68827cbd515262ecb8d5ae8547d9e82c72e00;hp=0ad509a9b473ab06586834a3245c968dd3a967e1;hpb=4738512f05259cc6016d0d3aea12ea6c55c9e438;p=inkscape.git diff --git a/src/ui/tool/path-manipulator.cpp b/src/ui/tool/path-manipulator.cpp index 0ad509a9b..5ae9c4137 100644 --- a/src/ui/tool/path-manipulator.cpp +++ b/src/ui/tool/path-manipulator.cpp @@ -3,6 +3,7 @@ */ /* Authors: * Krzysztof Kosiński + * Abhishek Sharma * * Copyright (C) 2009 Authors * Released under GNU GPL, read the file 'COPYING' for more information @@ -58,8 +59,21 @@ enum PathChange { */ class PathManipulatorObserver : public Inkscape::XML::NodeObserver { public: - PathManipulatorObserver(PathManipulator *p) : _pm(p), _blocked(false) {} - virtual void notifyAttributeChanged(Inkscape::XML::Node &, GQuark attr, + PathManipulatorObserver(PathManipulator *p, Inkscape::XML::Node *node) + : _pm(p) + , _node(node) + , _blocked(false) + { + Inkscape::GC::anchor(_node); + _node->addObserver(*this); + } + + ~PathManipulatorObserver() { + _node->removeObserver(*this); + Inkscape::GC::release(_node); + } + + virtual void notifyAttributeChanged(Inkscape::XML::Node &/*node*/, GQuark attr, Util::ptr_shared, Util::ptr_shared) { // do nothing if blocked @@ -76,31 +90,37 @@ public: _pm->_externalChange(PATH_CHANGE_TRANSFORM); } } + void block() { _blocked = true; } void unblock() { _blocked = false; } private: PathManipulator *_pm; + Inkscape::XML::Node *_node; bool _blocked; }; void build_segment(Geom::PathBuilder &, Node *, Node *); -PathManipulator::PathManipulator(PathSharedData const &data, SPPath *path, +PathManipulator::PathManipulator(MultiPathManipulator &mpm, SPPath *path, Geom::Matrix const &et, guint32 outline_color, Glib::ustring lpe_key) - : PointManipulator(data.node_data.desktop, *data.node_data.selection) - , _path_data(data) + : PointManipulator(mpm._path_data.node_data.desktop, *mpm._path_data.node_data.selection) + , _subpaths(*this) + , _multi_path_manipulator(mpm) , _path(path) - , _spcurve(NULL) + , _spcurve(new SPCurve()) , _dragpoint(new CurveDragPoint(*this)) - , _observer(new PathManipulatorObserver(this)) + , /* XML Tree being used here directly while it shouldn't be*/_observer(new PathManipulatorObserver(this, SP_OBJECT(path)->getRepr())) , _edit_transform(et) + , _num_selected(0) , _show_handles(true) , _show_outline(false) + , _show_path_direction(false) + , _live_outline(true) + , _live_objects(true) , _lpe_key(lpe_key) { - /* Because curve drag point is always created first, it does not cover nodes */ if (_lpe_key.empty()) { - _i2d_transform = sp_item_i2d_affine(SP_ITEM(path)); + _i2d_transform = SP_ITEM(path)->i2d_affine(); } else { _i2d_transform = Geom::identity(); } @@ -109,37 +129,28 @@ PathManipulator::PathManipulator(PathSharedData const &data, SPPath *path, _getGeometry(); - _outline = sp_canvas_bpath_new(_path_data.outline_group, NULL); + _outline = sp_canvas_bpath_new(_multi_path_manipulator._path_data.outline_group, NULL); sp_canvas_item_hide(_outline); sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(_outline), outline_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT); sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(_outline), 0, SP_WIND_RULE_NONZERO); - _subpaths.signal_insert_node.connect( - sigc::mem_fun(*this, &PathManipulator::_attachNodeHandlers)); - _subpaths.signal_remove_node.connect( - sigc::mem_fun(*this, &PathManipulator::_removeNodeHandlers)); _selection.signal_update.connect( sigc::mem_fun(*this, &PathManipulator::update)); _selection.signal_point_changed.connect( sigc::mem_fun(*this, &PathManipulator::_selectionChanged)); - _dragpoint->signal_update.connect( - sigc::mem_fun(*this, &PathManipulator::update)); _desktop->signal_zoom_changed.connect( sigc::hide( sigc::mem_fun(*this, &PathManipulator::_updateOutlineOnZoomChange))); _createControlPointsFromGeometry(); - - _path->repr->addObserver(*_observer); } PathManipulator::~PathManipulator() { delete _dragpoint; - if (_path) _path->repr->removeObserver(*_observer); delete _observer; gtk_object_destroy(_outline); - if (_spcurve) _spcurve->unref(); + _spcurve->unref(); clear(); } @@ -172,6 +183,11 @@ void PathManipulator::update() /** Store the changes to the path in XML. */ void PathManipulator::writeXML() { + if (!_live_outline) + _updateOutline(); + if (!_live_objects) + _setGeometry(); + if (!_path) return; _observer->block(); if (!empty()) { @@ -213,47 +229,20 @@ void PathManipulator::selectSubpaths() } } -/** Select all nodes in the path. */ -void PathManipulator::selectAll() -{ - for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { - for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { - _selection.insert(j.ptr()); - } - } -} - -/** Select points inside the given rectangle. If all points inside it are already selected, - * they will be deselected. - * @param area Area to select - */ -void PathManipulator::selectArea(Geom::Rect const &area) -{ - bool nothing_selected = true; - std::vector in_area; - for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { - for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { - if (area.contains(j->position())) { - in_area.push_back(j.ptr()); - if (!j->selected()) { - _selection.insert(j.ptr()); - nothing_selected = false; - } - } - } - } - if (nothing_selected) { - for (std::vector::iterator i = in_area.begin(); i != in_area.end(); ++i) { - _selection.erase(*i); - } - } -} - /** Move the selection forward or backward by one node in each subpath, based on the sign * of the parameter. */ void PathManipulator::shiftSelection(int dir) { if (dir == 0) return; + if (_num_selected == 0) { + // select the first node of the path. + SubpathList::iterator s = _subpaths.begin(); + if (s == _subpaths.end()) return; + NodeList::iterator n = (*s)->begin(); + if (n != (*s)->end()) + _selection.insert(n.ptr()); + return; + } // We cannot do any tricks here, like iterating in different directions based on // the sign and only setting the selection of nodes behind us, because it would break // for closed paths. @@ -266,7 +255,7 @@ void PathManipulator::shiftSelection(int dir) _selection.erase(j.ptr()); ++num; } - if (num == 0) continue; // should never happen! + if (num == 0) continue; // should never happen! zero-node subpaths are not allowed num = 0; // In closed subpath, shift the selection cyclically. In an open one, @@ -297,17 +286,6 @@ void PathManipulator::shiftSelection(int dir) } } -/** Invert selection in the entire path. */ -void PathManipulator::invertSelection() -{ - for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { - for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { - if (j->selected()) _selection.erase(j.ptr()); - else _selection.insert(j.ptr()); - } - } -} - /** Invert selection in the selected subpaths. */ void PathManipulator::invertSelectionInSubpaths() { @@ -329,7 +307,7 @@ void PathManipulator::invertSelectionInSubpaths() /** Insert a new node in the middle of each selected segment. */ void PathManipulator::insertNodes() { - if (!_num_selected) return; + if (_num_selected < 2) return; for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { @@ -342,11 +320,44 @@ void PathManipulator::insertNodes() } } +/** Insert new nodes exactly at the positions of selected nodes while preserving shape. + * This is equivalent to breaking, except that it doesn't split into subpaths. */ +void PathManipulator::duplicateNodes() +{ + if (_num_selected == 0) return; + + for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { + for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { + if (j->selected()) { + NodeList::iterator k = j.next(); + Node *n = new Node(_multi_path_manipulator._path_data.node_data, *j); + + // Move the new node to the bottom of the Z-order. This way you can drag all + // nodes that were selected before this operation without deselecting + // everything because there is a new node above. + n->sink(); + + n->front()->setPosition(*j->front()); + j->front()->retract(); + j->setType(NODE_CUSP, false); + (*i)->insert(k, n); + + // We need to manually call the selection change callback to refresh + // the handle display correctly. + // This call changes num_selected, but we call this once for a selected node + // and once for an unselected node, so in the end the number stays correct. + _selectionChanged(j.ptr(), true); + _selectionChanged(n, false); + } + } + } +} + /** Replace contiguous selections of nodes in each subpath with one node. */ -void PathManipulator::weldNodes(NodeList::iterator const &preserve_pos) +void PathManipulator::weldNodes(NodeList::iterator preserve_pos) { - if (!_num_selected) return; - _dragpoint->setVisible(false); + if (_num_selected < 2) return; + hideDragPoint(); bool pos_valid = preserve_pos; for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { @@ -363,19 +374,21 @@ void PathManipulator::weldNodes(NodeList::iterator const &preserve_pos) } // Start from unselected node in closed paths, so that we don't start in the middle - // of a contiguous selection + // of a selection NodeList::iterator sel_beg = sp->begin(), sel_end; if (sp->closed()) { while (sel_beg->selected()) ++sel_beg; } - // Main loop + // Work loop while (num_selected > 0) { // Find selected node while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next(); if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, " "but there are still nodes to process!"); + // note: this is initialized to zero, because the loop below counts sel_beg as well + // the loop conditions are simpler that way unsigned num_points = 0; bool use_pos = false; Geom::Point back_pos, front_pos; @@ -419,7 +432,57 @@ void PathManipulator::weldNodes(NodeList::iterator const &preserve_pos) /** Remove nodes in the middle of selected segments. */ void PathManipulator::weldSegments() { - // TODO + if (_num_selected < 2) return; + hideDragPoint(); + + for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { + SubpathPtr sp = *i; + unsigned num_selected = 0, num_unselected = 0; + for (NodeList::iterator j = sp->begin(); j != sp->end(); ++j) { + if (j->selected()) ++num_selected; + else ++num_unselected; + } + if (num_selected < 3) continue; + if (num_unselected == 0 && sp->closed()) { + // if all nodes in a closed subpath are selected, the operation doesn't make much sense + continue; + } + + // Start from unselected node in closed paths, so that we don't start in the middle + // of a selection + NodeList::iterator sel_beg = sp->begin(), sel_end; + if (sp->closed()) { + while (sel_beg->selected()) ++sel_beg; + } + + // Work loop + while (num_selected > 0) { + // Find selected node + while (sel_beg && !sel_beg->selected()) sel_beg = sel_beg.next(); + if (!sel_beg) throw std::logic_error("Join nodes: end of open path reached, " + "but there are still nodes to process!"); + + // note: this is initialized to zero, because the loop below counts sel_beg as well + // the loop conditions are simpler that way + unsigned num_points = 0; + + // find the end of selected segment + for (sel_end = sel_beg; sel_end && sel_end->selected(); sel_end = sel_end.next()) { + ++num_points; + } + if (num_points > 2) { + // remove nodes in the middle + sel_beg = sel_beg.next(); + while (sel_beg != sel_end.prev()) { + NodeList::iterator next = sel_beg.next(); + sp->erase(sel_beg); + sel_beg = next; + } + sel_beg = sel_end; + } + num_selected -= num_points; + } + } } /** Break the subpath at selected nodes. It also works for single node closed paths. */ @@ -453,7 +516,7 @@ void PathManipulator::breakNodes() ins = new_sp; } - Node *n = new Node(_path_data.node_data, cur->position()); + Node *n = new Node(_multi_path_manipulator._path_data.node_data, cur->position()); ins->insert(ins->end(), n); cur->setType(NODE_CUSP, false); n->back()->setRelativePos(cur->back()->relativePos()); @@ -472,11 +535,8 @@ void PathManipulator::breakNodes() * in a way that attempts to preserve the original shape of the curve. */ void PathManipulator::deleteNodes(bool keep_shape) { - if (!_num_selected) return; + if (_num_selected == 0) return; hideDragPoint(); - - unsigned const samples_per_segment = 10; - double const t_step = 1.0 / samples_per_segment; for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end();) { SubpathPtr sp = *i; @@ -506,59 +566,82 @@ void PathManipulator::deleteNodes(bool keep_shape) sel_end = sel_beg; while (num_selected > 0) { - while (!sel_beg->selected()) sel_beg = sel_beg.next(); + while (sel_beg && !sel_beg->selected()) { + sel_beg = sel_beg.next(); + } sel_end = sel_beg; - unsigned del_len = 0; + while (sel_end && sel_end->selected()) { - ++del_len; sel_end = sel_end.next(); } - // set surrounding node types to cusp if: - // 1. keep_shape is on, or - // 2. we are deleting at the end or beginning of an open path - // if !sel_end then sel_beg.prev() must be valid, otherwise the entire subpath - // would be deleted before we get here - if ((keep_shape || !sel_end) && sel_beg.prev()) sel_beg.prev()->setType(NODE_CUSP, false); - if ((keep_shape || !sel_beg.prev()) && sel_end) sel_end->setType(NODE_CUSP, false); - - if (keep_shape && sel_beg.prev() && sel_end) { - // Fill fit data - unsigned num_samples = (del_len + 1) * samples_per_segment + 1; - Geom::Point *bezier_data = new Geom::Point[num_samples]; - Geom::Point result[4]; - unsigned seg = 0; - - for (NodeList::iterator cur = sel_beg.prev(); cur != sel_end; cur = cur.next()) { - Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back()); - for (unsigned s = 0; s < samples_per_segment; ++s) { - bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s); - } - ++seg; - } - // Fill last point - bezier_data[num_samples - 1] = sel_end->position(); - // Compute replacement bezier curve - // TODO the fitting algorithm sucks - rewrite it to be awesome - bezier_fit_cubic(result, bezier_data, num_samples, 0.5); - delete[] bezier_data; - - sel_beg.prev()->front()->setPosition(result[1]); - sel_end->back()->setPosition(result[2]); - } - // We cannot simply use sp->erase(sel_beg, sel_end), because it would break - // for cases when the selected stretch crosses the beginning of the path - while (sel_beg != sel_end) { - NodeList::iterator next = sel_beg.next(); - sp->erase(sel_beg); - sel_beg = next; - } - num_selected -= del_len; + num_selected -= _deleteStretch(sel_beg, sel_end, keep_shape); + sel_beg = sel_end; } ++i; } } +/** @brief Delete nodes between the two iterators. + * The given range can cross the beginning of the subpath in closed subpaths. + * @param start Beginning of the range to delete + * @param end End of the range + * @param keep_shape Whether to fit the handles at surrounding nodes to approximate + * the shape before deletion + * @return Number of deleted nodes */ +unsigned PathManipulator::_deleteStretch(NodeList::iterator start, NodeList::iterator end, bool keep_shape) +{ + unsigned const samples_per_segment = 10; + double const t_step = 1.0 / samples_per_segment; + + unsigned del_len = 0; + for (NodeList::iterator i = start; i != end; i = i.next()) { + ++del_len; + } + if (del_len == 0) return 0; + + // set surrounding node types to cusp if: + // 1. keep_shape is on, or + // 2. we are deleting at the end or beginning of an open path + if ((keep_shape || !end) && start.prev()) start.prev()->setType(NODE_CUSP, false); + if ((keep_shape || !start.prev()) && end) end->setType(NODE_CUSP, false); + + if (keep_shape && start.prev() && end) { + unsigned num_samples = (del_len + 1) * samples_per_segment + 1; + Geom::Point *bezier_data = new Geom::Point[num_samples]; + Geom::Point result[4]; + unsigned seg = 0; + + for (NodeList::iterator cur = start.prev(); cur != end; cur = cur.next()) { + Geom::CubicBezier bc(*cur, *cur->front(), *cur.next(), *cur.next()->back()); + for (unsigned s = 0; s < samples_per_segment; ++s) { + bezier_data[seg * samples_per_segment + s] = bc.pointAt(t_step * s); + } + ++seg; + } + // Fill last point + bezier_data[num_samples - 1] = end->position(); + // Compute replacement bezier curve + // TODO the fitting algorithm sucks - rewrite it to be awesome + bezier_fit_cubic(result, bezier_data, num_samples, 0.5); + delete[] bezier_data; + + start.prev()->front()->setPosition(result[1]); + end->back()->setPosition(result[2]); + } + + // We can't use nl->erase(start, end), because it would break when the stretch + // crosses the beginning of a closed subpath + NodeList &nl = start->nodeList(); + while (start != end) { + NodeList::iterator next = start.next(); + nl.erase(start); + start = next; + } + + return del_len; +} + /** Removes selected segments */ void PathManipulator::deleteSegments() { @@ -634,15 +717,21 @@ void PathManipulator::deleteSegments() } } -/** Reverse the subpaths that have anything selected. */ -void PathManipulator::reverseSubpaths() +/** Reverse subpaths of the path. + * @param selected_only If true, only paths that have at least one selected node + * will be reversed. Otherwise all subpaths will be reversed. */ +void PathManipulator::reverseSubpaths(bool selected_only) { for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { - for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { - if (j->selected()) { - (*i)->reverse(); - break; // continue with the next subpath + if (selected_only) { + for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { + if (j->selected()) { + (*i)->reverse(); + break; // continue with the next subpath + } } + } else { + (*i)->reverse(); } } } @@ -650,7 +739,7 @@ void PathManipulator::reverseSubpaths() /** Make selected segments curves / lines. */ void PathManipulator::setSegmentType(SegmentType type) { - if (!_num_selected) return; + if (_num_selected == 0) return; for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { NodeList::iterator k = j.next(); @@ -665,6 +754,7 @@ void PathManipulator::setSegmentType(SegmentType type) case SEGMENT_CUBIC_BEZIER: if (!j->front()->isDegenerate() || !k->back()->isDegenerate()) break; + // move both handles to 1/3 of the line j->front()->move(j->position() + (k->position() - j->position()) / 3); k->back()->move(k->position() + (j->position() - k->position()) / 3); break; @@ -673,6 +763,90 @@ void PathManipulator::setSegmentType(SegmentType type) } } +void PathManipulator::scaleHandle(Node *n, int which, int dir, bool pixel) +{ + if (n->type() == NODE_SYMMETRIC || n->type() == NODE_AUTO) { + n->setType(NODE_SMOOTH); + } + Handle *h = _chooseHandle(n, which); + double length_change; + + if (pixel) { + length_change = 1.0 / _desktop->current_zoom() * dir; + } else { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + length_change = prefs->getDoubleLimited("/options/defaultscale/value", 2, 1, 1000); + length_change *= dir; + } + + Geom::Point relpos; + if (h->isDegenerate()) { + if (dir < 0) return; + Node *nh = n->nodeToward(h); + if (!nh) return; + relpos = Geom::unit_vector(nh->position() - n->position()) * length_change; + } else { + relpos = h->relativePos(); + double rellen = relpos.length(); + relpos *= ((rellen + length_change) / rellen); + } + h->setRelativePos(relpos); + update(); + + gchar const *key = which < 0 ? "handle:scale:left" : "handle:scale:right"; + _commit(_("Scale handle"), key); +} + +void PathManipulator::rotateHandle(Node *n, int which, int dir, bool pixel) +{ + if (n->type() != NODE_CUSP) { + n->setType(NODE_CUSP); + } + Handle *h = _chooseHandle(n, which); + if (h->isDegenerate()) return; + + double angle; + if (pixel) { + // Rotate by "one pixel" + angle = atan2(1.0 / _desktop->current_zoom(), h->length()) * dir; + } else { + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int snaps = prefs->getIntLimited("/options/rotationsnapsperpi/value", 12, 1, 1000); + angle = M_PI * dir / snaps; + } + + h->setRelativePos(h->relativePos() * Geom::Rotate(angle)); + update(); + gchar const *key = which < 0 ? "handle:rotate:left" : "handle:rotate:right"; + _commit(_("Rotate handle"), key); +} + +Handle *PathManipulator::_chooseHandle(Node *n, int which) +{ + NodeList::iterator i = NodeList::get_iterator(n); + Node *prev = i.prev().ptr(); + Node *next = i.next().ptr(); + + // on an endnode, the remaining handle automatically wins + if (!next) return n->back(); + if (!prev) return n->front(); + + // compare X coord ofline segments + Geom::Point npos = next->position(); + Geom::Point ppos = prev->position(); + if (which < 0) { + // pick left handle. + // we just swap the handles and pick the right handle below. + std::swap(npos, ppos); + } + + if (npos[Geom::X] >= ppos[Geom::X]) { + return n->front(); + } else { + return n->back(); + } +} + /** Set the visibility of handles. */ void PathManipulator::showHandles(bool show) { @@ -711,6 +885,16 @@ void PathManipulator::showPathDirection(bool show) _updateOutline(); } +void PathManipulator::setLiveOutline(bool set) +{ + _live_outline = set; +} + +void PathManipulator::setLiveObjects(bool set) +{ + _live_objects = set; +} + void PathManipulator::setControlsTransform(Geom::Matrix const &tnew) { Geom::Matrix delta = _i2d_transform.inverse() * _edit_transform.inverse() * tnew * _i2d_transform; @@ -723,6 +907,9 @@ void PathManipulator::setControlsTransform(Geom::Matrix const &tnew) _createGeometryFromControlPoints(); } +/** Hide the curve drag point until the next motion event. + * This should be called at the beginning of every method that can delete nodes. + * Otherwise the invalidated iterator in the dragpoint can cause crashes. */ void PathManipulator::hideDragPoint() { _dragpoint->setVisible(false); @@ -747,7 +934,7 @@ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, d NodeList::iterator inserted; if (first->front()->isDegenerate() && second->back()->isDegenerate()) { // for a line segment, insert a cusp node - Node *n = new Node(_path_data.node_data, + Node *n = new Node(_multi_path_manipulator._path_data.node_data, Geom::lerp(t, first->position(), second->position())); n->setType(NODE_CUSP, false); inserted = list.insert(insert_at, n); @@ -759,7 +946,7 @@ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, d std::vector seg1 = div.first.points(), seg2 = div.second.points(); // set new handle positions - Node *n = new Node(_path_data.node_data, seg2[0]); + Node *n = new Node(_multi_path_manipulator._path_data.node_data, seg2[0]); n->back()->setPosition(seg1[2]); n->front()->setPosition(seg2[1]); n->setType(NODE_SMOOTH, false); @@ -771,9 +958,43 @@ NodeList::iterator PathManipulator::subdivideSegment(NodeList::iterator first, d return inserted; } +/** Find the node that is closest/farthest from the origin + * @param origin Point of reference + * @param search_selected Consider selected nodes + * @param search_unselected Consider unselected nodes + * @param closest If true, return closest node, if false, return farthest + * @return The matching node, or an empty iterator if none found + */ +NodeList::iterator PathManipulator::extremeNode(NodeList::iterator origin, bool search_selected, + bool search_unselected, bool closest) +{ + NodeList::iterator match; + double extr_dist = closest ? HUGE_VAL : -HUGE_VAL; + if (_num_selected == 0 && !search_unselected) return match; + + for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { + for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j) { + if(j->selected()) { + if (!search_selected) continue; + } else { + if (!search_unselected) continue; + } + double dist = Geom::distance(*j, *origin); + bool cond = closest ? (dist < extr_dist) : (dist > extr_dist); + if (cond) { + match = j; + extr_dist = dist; + } + } + } + return match; +} + /** Called by the XML observer when something else than us modifies the path. */ void PathManipulator::_externalChange(unsigned type) { + hideDragPoint(); + switch (type) { case PATH_CHANGE_D: { _getGeometry(); @@ -803,7 +1024,7 @@ void PathManipulator::_externalChange(unsigned type) } break; case PATH_CHANGE_TRANSFORM: { Geom::Matrix i2d_change = _d2i_transform; - _i2d_transform = sp_item_i2d_affine(SP_ITEM(_path)); + _i2d_transform = SP_ITEM(_path)->i2d_affine(); _d2i_transform = _i2d_transform.inverse(); i2d_change *= _i2d_transform; for (SubpathList::iterator i = _subpaths.begin(); i != _subpaths.end(); ++i) { @@ -826,8 +1047,14 @@ void PathManipulator::_createControlPointsFromGeometry() // so that _updateDragPoint doesn't crash on paths with naked movetos Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers(_spcurve->get_pathvector()); for (Geom::PathVector::iterator i = pathv.begin(); i != pathv.end(); ) { - if (i->empty()) pathv.erase(i++); - else ++i; + // NOTE: this utilizes the fact that Geom::PathVector is an std::vector. + // When we erase an element, the next one slides into position, + // so we do not increment the iterator even though it is theoretically invalidated. + if (i->empty()) { + pathv.erase(i); + } else { + ++i; + } } _spcurve->set_pathvector(pathv); @@ -839,7 +1066,7 @@ void PathManipulator::_createControlPointsFromGeometry() SubpathPtr subpath(new NodeList(_subpaths)); _subpaths.push_back(subpath); - Node *previous_node = new Node(_path_data.node_data, pit->initialPoint()); + Node *previous_node = new Node(_multi_path_manipulator._path_data.node_data, pit->initialPoint()); subpath->push_back(previous_node); Geom::Curve const &cseg = pit->back_closed(); bool fuse_ends = pit->closed() @@ -856,7 +1083,7 @@ void PathManipulator::_createControlPointsFromGeometry() /* regardless of segment type, create a new node at the end * of this segment (unless this is the last segment of a closed path * with a degenerate closing segment */ - current_node = new Node(_path_data.node_data, pos); + current_node = new Node(_multi_path_manipulator._path_data.node_data, pos); subpath->push_back(current_node); } // if this is a bezier segment, move handles appropriately @@ -877,7 +1104,10 @@ void PathManipulator::_createControlPointsFromGeometry() // we need to set the nodetypes after all the handles are in place, // so that pickBestType works correctly // TODO maybe migrate to inkscape:node-types? - gchar const *nts_raw = _path ? _path->repr->attribute(_nodetypesKey().data()) : 0; + // TODO move this into SPPath - do not manipulate directly + + //XML Tree being used here directly while it shouldn't be. + gchar const *nts_raw = _path ? _path->getRepr()->attribute(_nodetypesKey().data()) : 0; std::string nodetype_string = nts_raw ? nts_raw : ""; /* Calculate the needed length of the nodetype string. * For closed paths, the entry is duplicated for the starting node, @@ -938,8 +1168,10 @@ void PathManipulator::_createGeometryFromControlPoints() } builder.finish(); _spcurve->set_pathvector(builder.peek() * (_edit_transform * _i2d_transform).inverse()); - _updateOutline(); - _setGeometry(); + if (_live_outline) + _updateOutline(); + if (_live_objects) + _setGeometry(); } /** Build one segment of the geometric representation. @@ -1024,13 +1256,11 @@ void PathManipulator::_getGeometry() Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe(); if (lpe) { PathParam *pathparam = dynamic_cast(lpe->getParameter(_lpe_key.data())); - if (!_spcurve) - _spcurve = new SPCurve(pathparam->get_pathvector()); - else - _spcurve->set_pathvector(pathparam->get_pathvector()); + _spcurve->unref(); + _spcurve = new SPCurve(pathparam->get_pathvector()); } } else { - if (_spcurve) _spcurve->unref(); + _spcurve->unref(); _spcurve = sp_path_get_curve_for_edit(_path); } } @@ -1042,9 +1272,9 @@ void PathManipulator::_setGeometry() if (empty()) return; if (!_lpe_key.empty()) { - // LPE brain damage follows - copied from nodepath.cpp + // copied from nodepath.cpp // NOTE: if we are editing an LPE param, _path is not actually an SPPath, it is - // a LivePathEffectObject. + // a LivePathEffectObject. (mad laughter) Effect *lpe = LIVEPATHEFFECT(_path)->get_lpe(); if (lpe) { PathParam *pathparam = dynamic_cast(lpe->getParameter(_lpe_key.data())); @@ -1052,83 +1282,65 @@ void PathManipulator::_setGeometry() LIVEPATHEFFECT(_path)->requestModified(SP_OBJECT_MODIFIED_FLAG); } } else { - if (_path->repr->attribute("inkscape:original-d")) - sp_path_set_original_curve(_path, _spcurve, true, false); + //XML Tree being used here directly while it shouldn't be. + if (_path->getRepr()->attribute("inkscape:original-d")) + sp_path_set_original_curve(_path, _spcurve, false, false); else - sp_shape_set_curve(SP_SHAPE(_path), _spcurve, false); + SP_SHAPE(_path)->setCurve(_spcurve, false); } } -/** LPE brain damage */ +/** Figure out in what attribute to store the nodetype string. */ Glib::ustring PathManipulator::_nodetypesKey() { if (_lpe_key.empty()) return "sodipodi:nodetypes"; return _lpe_key + "-nodetypes"; } -/** LPE brain damage */ +/** Return the XML node we are editing. + * This method is wrong but necessary at the moment. */ Inkscape::XML::Node *PathManipulator::_getXMLNode() { - if (_lpe_key.empty()) return _path->repr; - return LIVEPATHEFFECT(_path)->repr; -} - -void PathManipulator::_attachNodeHandlers(Node *node) -{ - Handle *handles[2] = { node->front(), node->back() }; - for (int i = 0; i < 2; ++i) { - handles[i]->signal_update.connect( - sigc::mem_fun(*this, &PathManipulator::update)); - handles[i]->signal_ungrabbed.connect( - sigc::hide( - sigc::mem_fun(*this, &PathManipulator::_handleUngrabbed))); - handles[i]->signal_grabbed.connect( - sigc::bind_return( - sigc::hide( - sigc::mem_fun(*this, &PathManipulator::_handleGrabbed)), - false)); - handles[i]->signal_clicked.connect( - sigc::bind<0>( - sigc::mem_fun(*this, &PathManipulator::_handleClicked), - handles[i])); - } - node->signal_clicked.connect( - sigc::bind<0>( - sigc::mem_fun(*this, &PathManipulator::_nodeClicked), - node)); -} -void PathManipulator::_removeNodeHandlers(Node *node) -{ - // It is safe to assume that nobody else connected to handles' signals after us, - // so we pop our slots from the back. This preserves existing connections - // created by Node and Handle constructors. - Handle *handles[2] = { node->front(), node->back() }; - for (int i = 0; i < 2; ++i) { - handles[i]->signal_update.slots().pop_back(); - handles[i]->signal_grabbed.slots().pop_back(); - handles[i]->signal_ungrabbed.slots().pop_back(); - handles[i]->signal_clicked.slots().pop_back(); - } - // Same for this one: CPS only connects to grab, drag, and ungrab - node->signal_clicked.slots().pop_back(); + //XML Tree being used here directly while it shouldn't be. + if (_lpe_key.empty()) return _path->getRepr(); + //XML Tree being used here directly while it shouldn't be. + return LIVEPATHEFFECT(_path)->getRepr(); } bool PathManipulator::_nodeClicked(Node *n, GdkEventButton *event) { - // cycle between node types on ctrl+click - if (event->button != 1 || !held_control(*event)) return false; - if (n->isEndNode()) { - if (n->type() == NODE_CUSP) { - n->setType(NODE_SMOOTH); + if (event->button != 1) return false; + if (held_alt(*event) && held_control(*event)) { + // Ctrl+Alt+click: delete nodes + hideDragPoint(); + NodeList::iterator iter = NodeList::get_iterator(n); + NodeList &nl = iter->nodeList(); + + if (nl.size() <= 1 || (nl.size() <= 2 && !nl.closed())) { + // Removing last node of closed path - delete it + nl.kill(); } else { - n->setType(NODE_CUSP); + // In other cases, delete the node under cursor + _deleteStretch(iter, iter.next(), true); } - } else { - n->setType(static_cast((n->type() + 1) % NODE_LAST_REAL_TYPE)); + + if (!empty()) { + update(); + } + // We need to call MPM's method because it could have been our last node + _multi_path_manipulator._doneWithCleanup(_("Delete node")); + + return true; + } else if (held_control(*event)) { + // Ctrl+click: cycle between node types + if (!n->isEndNode()) { + n->setType(static_cast((n->type() + 1) % NODE_LAST_REAL_TYPE)); + update(); + _commit(_("Cycle node type")); + } + return true; } - update(); - _commit(_("Cycle node type")); - return true; + return false; } void PathManipulator::_handleGrabbed() @@ -1156,6 +1368,9 @@ bool PathManipulator::_handleClicked(Handle *h, GdkEventButton *event) void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected) { + if (selected) ++_num_selected; + else --_num_selected; + // don't do anything if we do not show handles if (!_show_handles) return; @@ -1190,9 +1405,6 @@ void PathManipulator::_selectionChanged(SelectableControlPoint *p, bool selected } } } - - if (selected) ++_num_selected; - else --_num_selected; } /** Removes all nodes belonging to this manipulator from the control pont selection */ @@ -1210,19 +1422,26 @@ void PathManipulator::_removeNodesFromSelection() void PathManipulator::_commit(Glib::ustring const &annotation) { writeXML(); - sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data()); + DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_NODE, annotation.data()); +} + +void PathManipulator::_commit(Glib::ustring const &annotation, gchar const *key) +{ + writeXML(); + DocumentUndo::maybeDone(sp_desktop_document(_desktop), key, SP_VERB_CONTEXT_NODE, + annotation.data()); } /** Update the position of the curve drag point such that it is over the nearest * point of the path. */ void PathManipulator::_updateDragPoint(Geom::Point const &evp) { - // TODO find a way to make this faster (no transform required) - Geom::PathVector pv = _spcurve->get_pathvector() * (_edit_transform * _i2d_transform); + Geom::Matrix to_desktop = _edit_transform * _i2d_transform; + Geom::PathVector pv = _spcurve->get_pathvector(); boost::optional pvp - = Geom::nearestPoint(pv, _desktop->w2d(evp)); + = Geom::nearestPoint(pv, _desktop->w2d(evp) * to_desktop.inverse()); if (!pvp) return; - Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t)); + Geom::Point nearest_point = _desktop->d2w(pv.at(pvp->path_nr).pointAt(pvp->t) * to_desktop); double fracpart; std::list::iterator spi = _subpaths.begin(); @@ -1230,7 +1449,10 @@ void PathManipulator::_updateDragPoint(Geom::Point const &evp) NodeList::iterator first = (*spi)->before(pvp->t, &fracpart); double stroke_tolerance = _getStrokeTolerance(); - if (Geom::distance(evp, nearest_point) < stroke_tolerance) { + if (first && first.next() && + fracpart != 0.0 && + Geom::distance(evp, nearest_point) < stroke_tolerance) + { _dragpoint->setVisible(true); _dragpoint->setPosition(_desktop->w2d(nearest_point)); _dragpoint->setSize(2 * stroke_tolerance); @@ -1255,7 +1477,7 @@ double PathManipulator::_getStrokeTolerance() * drag tolerance setting. */ Inkscape::Preferences *prefs = Inkscape::Preferences::get(); double ret = prefs->getIntLimited("/options/dragtolerance/value", 2, 0, 100); - if (_path && !SP_OBJECT_STYLE(_path)->stroke.isNone()) { + if (_path && SP_OBJECT_STYLE(_path) && !SP_OBJECT_STYLE(_path)->stroke.isNone()) { ret += SP_OBJECT_STYLE(_path)->stroke_width.computed * 0.5 * (_edit_transform * _i2d_transform).descrim() // scale to desktop coords * _desktop->current_zoom(); // == _d2w.descrim() - scale to window coords @@ -1275,4 +1497,4 @@ double PathManipulator::_getStrokeTolerance() fill-column:99 End: */ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :