1 /**
2 * \file object-snapper.cpp
3 * \brief Snapping things to objects.
4 *
5 * Authors:
6 * Carl Hetherington <inkscape@carlh.net>
7 * Diederik van Lierop <mail@diedenrezi.nl>
8 * Jon A. Cruz <jon@joncruz.org>
9 * Abhishek Sharma
10 *
11 * Copyright (C) 2005 - 2010 Authors
12 *
13 * Released under GNU GPL, read the file 'COPYING' for more information
14 */
16 #include "svg/svg.h"
17 #include <2geom/path-intersection.h>
18 #include <2geom/pathvector.h>
19 #include <2geom/point.h>
20 #include <2geom/rect.h>
21 #include <2geom/line.h>
22 #include <2geom/circle.h>
23 #include "document.h"
24 #include "sp-namedview.h"
25 #include "sp-image.h"
26 #include "sp-item-group.h"
27 #include "sp-item.h"
28 #include "sp-use.h"
29 #include "display/curve.h"
30 #include "inkscape.h"
31 #include "preferences.h"
32 #include "sp-text.h"
33 #include "sp-flowtext.h"
34 #include "text-editing.h"
35 #include "sp-clippath.h"
36 #include "sp-mask.h"
37 #include "helper/geom-curves.h"
38 #include "desktop.h"
40 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
41 : Snapper(sm, d)
42 {
43 _candidates = new std::vector<SnapCandidateItem>;
44 _points_to_snap_to = new std::vector<Inkscape::SnapCandidatePoint>;
45 _paths_to_snap_to = new std::vector<Inkscape::SnapCandidatePath >;
46 }
48 Inkscape::ObjectSnapper::~ObjectSnapper()
49 {
50 _candidates->clear();
51 delete _candidates;
53 _points_to_snap_to->clear();
54 delete _points_to_snap_to;
56 _clear_paths();
57 delete _paths_to_snap_to;
58 }
60 /**
61 * \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
62 */
63 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
64 {
65 SPDesktop const *dt = _snapmanager->getDesktop();
66 double const zoom = dt ? dt->current_zoom() : 1;
67 return _snapmanager->snapprefs.getObjectTolerance() / zoom;
68 }
70 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
71 {
72 return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
73 }
75 /**
76 * Find all items within snapping range.
77 * \param parent Pointer to the document's root, or to a clipped path or mask object
78 * \param it List of items to ignore
79 * \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
80 */
82 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
83 std::vector<SPItem const *> const *it,
84 bool const &first_point,
85 Geom::Rect const &bbox_to_snap,
86 bool const clip_or_mask,
87 Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
88 {
89 if (!ThisSnapperMightSnap()) {
90 return;
91 }
93 if (_snapmanager->getDesktop() == NULL) {
94 g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
95 // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
96 }
98 if (first_point) {
99 _candidates->clear();
100 }
102 Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
103 bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
105 for ( SPObject *o = parent->firstChild(); o; o = o->getNext() ) {
106 g_assert(_snapmanager->getDesktop() != NULL);
107 if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
108 // Snapping to items in a locked layer is allowed
109 // Don't snap to hidden objects, unless they're a clipped path or a mask
110 /* See if this item is on the ignore list */
111 std::vector<SPItem const *>::const_iterator i;
112 if (it != NULL) {
113 i = it->begin();
114 while (i != it->end() && *i != o) {
115 i++;
116 }
117 }
119 if (it == NULL || i == it->end()) {
120 SPItem *item = SP_ITEM(o);
121 if (item) {
122 SPObject *obj = NULL;
123 if (!clip_or_mask) { // cannot clip or mask more than once
124 // The current item is not a clipping path or a mask, but might
125 // still be the subject of clipping or masking itself ; if so, then
126 // we should also consider that path or mask for snapping to
127 obj = SP_OBJECT(item->clip_ref->getObject());
128 if (obj) {
129 _findCandidates(obj, it, false, bbox_to_snap, true, item->i2doc_affine());
130 }
131 obj = SP_OBJECT(item->mask_ref->getObject());
132 if (obj) {
133 _findCandidates(obj, it, false, bbox_to_snap, true, item->i2doc_affine());
134 }
135 }
136 }
138 if (SP_IS_GROUP(o)) {
139 _findCandidates(o, it, false, bbox_to_snap, clip_or_mask, additional_affine);
140 } else {
141 Geom::OptRect bbox_of_item = Geom::Rect();
142 if (clip_or_mask) {
143 // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
144 // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
145 item->invoke_bbox(bbox_of_item,
146 item->i2doc_affine() * additional_affine * _snapmanager->getDesktop()->doc2dt(),
147 true);
148 } else {
149 item->invoke_bbox( bbox_of_item, item->i2d_affine(), true);
150 }
151 if (bbox_of_item) {
152 // See if the item is within range
153 if (bbox_to_snap_incl.intersects(*bbox_of_item)
154 || (_snapmanager->snapprefs.getIncludeItemCenter() && bbox_to_snap_incl.contains(item->getCenter()))) { // rotation center might be outside of the bounding box
155 // This item is within snapping range, so record it as a candidate
156 _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
157 // For debugging: print the id of the candidate to the console
158 // SPObject *obj = (SPObject*)item;
159 // std::cout << "Snap candidate added: " << obj->getId() << std::endl;
160 }
161 }
162 }
163 }
164 }
165 }
166 }
169 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
170 bool const &first_point) const
171 {
172 // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
173 // e.g. when translating an item using the selector tool, then we will only do this for the
174 // first point and store the collection for later use. This significantly improves the performance
175 if (first_point) {
176 _points_to_snap_to->clear();
178 // Determine the type of bounding box we should snap to
179 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
181 bool p_is_a_node = t & Inkscape::SNAPSOURCE_NODE_CATEGORY;
182 bool p_is_a_bbox = t & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
183 bool p_is_other = t & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
185 // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
186 g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
188 if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
189 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
190 bool prefs_bbox = prefs->getBool("/tools/bounding_box");
191 bbox_type = !prefs_bbox ?
192 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
193 }
195 // Consider the page border for snapping to
196 if (_snapmanager->snapprefs.getSnapToPageBorder()) {
197 _getBorderNodes(_points_to_snap_to);
198 }
200 for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
201 //Geom::Matrix i2doc(Geom::identity());
202 SPItem *root_item = (*i).item;
203 if (SP_IS_USE((*i).item)) {
204 root_item = sp_use_root(SP_USE((*i).item));
205 }
206 g_return_if_fail(root_item);
208 //Collect all nodes so we can snap to them
209 if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
210 // Note: there are two ways in which intersections are considered:
211 // Method 1: Intersections are calculated for each shape individually, for both the
212 // snap source and snap target (see sp_shape_snappoints)
213 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
214 // the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
215 // Some differences:
216 // - Method 1 doesn't find intersections within a set of multiple objects
217 // - Method 2 only works for targets
218 // When considering intersections as snap targets:
219 // - Method 1 only works when snapping to nodes, whereas
220 // - Method 2 only works when snapping to paths
221 // - There will be performance differences too!
222 // If both methods are being used simultaneously, then this might lead to duplicate targets!
224 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
225 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
226 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
227 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
228 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
229 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
230 if (_snapmanager->snapprefs.getSnapToItemPath()) {
231 _snapmanager->snapprefs.setSnapIntersectionCS(false);
232 }
234 // We should not snap a transformation center to any of the centers of the items in the
235 // current selection (see the comment in SelTrans::centerRequest())
236 bool old_pref2 = _snapmanager->snapprefs.getIncludeItemCenter();
237 if (old_pref2) {
238 for ( GSList const *itemlist = _snapmanager->getRotationCenterSource(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
239 if ((*i).item == reinterpret_cast<SPItem*>(itemlist->data)) {
240 // don't snap to this item's rotation center
241 _snapmanager->snapprefs.setIncludeItemCenter(false);
242 break;
243 }
244 }
245 }
247 root_item->getSnappoints(*_points_to_snap_to, &_snapmanager->snapprefs);
249 // restore the original snap preferences
250 _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
251 _snapmanager->snapprefs.setIncludeItemCenter(old_pref2);
252 }
254 //Collect the bounding box's corners so we can snap to them
255 if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
256 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
257 // of the item AND the bbox of the clipping path at the same time
258 if (!(*i).clip_or_mask) {
259 Geom::OptRect b = root_item->getBboxDesktop(bbox_type);
260 getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
261 }
262 }
263 }
264 }
265 }
267 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
268 Inkscape::SnapCandidatePoint const &p,
269 std::vector<SnapCandidatePoint> *unselected_nodes,
270 SnapConstraint const &c,
271 Geom::Point const &p_proj_on_constraint) const
272 {
273 // Iterate through all nodes, find out which one is the closest to p, and snap to it!
275 _collectNodes(p.getSourceType(), p.getSourceNum() <= 0);
277 if (unselected_nodes != NULL && unselected_nodes->size() > 0) {
278 g_assert(_points_to_snap_to != NULL);
279 _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
280 }
282 SnappedPoint s;
283 bool success = false;
285 for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
286 Geom::Point target_pt = (*k).getPoint();
287 Geom::Coord dist = NR_HUGE;
288 if (!c.isUndefined()) {
289 // We're snapping to nodes along a constraint only, so find out if this node
290 // is at the constraint, while allowing for a small margin
291 if (Geom::L2(target_pt - c.projection(target_pt)) > 1e-9) {
292 // The distance from the target point to its projection on the constraint
293 // is too large, so this point is not on the constraint. Skip it!
294 continue;
295 }
296 dist = Geom::L2(target_pt - p_proj_on_constraint);
297 } else {
298 // Free (unconstrained) snapping
299 dist = Geom::L2(target_pt - p.getPoint());
300 }
302 if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
303 s = SnappedPoint(target_pt, p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
304 success = true;
305 }
306 }
308 if (success) {
309 sc.points.push_back(s);
310 }
311 }
313 void Inkscape::ObjectSnapper::_snapTranslatingGuide(SnappedConstraints &sc,
314 Geom::Point const &p,
315 Geom::Point const &guide_normal) const
316 {
317 // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
318 _collectNodes(SNAPSOURCE_GUIDE, true);
320 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
321 _collectPaths(p, SNAPSOURCE_GUIDE, true);
322 _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
323 }
325 SnappedPoint s;
327 Geom::Coord tol = getSnapperTolerance();
329 for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
330 Geom::Point target_pt = (*k).getPoint();
331 // Project each node (*k) on the guide line (running through point p)
332 Geom::Point p_proj = Geom::projection(target_pt, Geom::Line(p, p + Geom::rot90(guide_normal)));
333 Geom::Coord dist = Geom::L2(target_pt - p_proj); // distance from node to the guide
334 Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
335 if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
336 s = SnappedPoint(target_pt, SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
337 sc.points.push_back(s);
338 }
339 }
340 }
343 /**
344 * Returns index of first NR_END bpath in array.
345 */
347 void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/,
348 Inkscape::SnapSourceType const source_type,
349 bool const &first_point) const
350 {
351 // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
352 // e.g. when translating an item using the selector tool, then we will only do this for the
353 // first point and store the collection for later use. This significantly improves the performance
354 if (first_point) {
355 _clear_paths();
357 // Determine the type of bounding box we should snap to
358 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
360 bool p_is_a_node = source_type & Inkscape::SNAPSOURCE_NODE_CATEGORY;
361 bool p_is_other = source_type & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
363 if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
364 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
365 int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
366 bbox_type = !prefs_bbox ?
367 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
368 }
370 // Consider the page border for snapping
371 if (_snapmanager->snapprefs.getSnapToPageBorder() && _snapmanager->snapprefs.getSnapModeBBoxOrNodes()) {
372 Geom::PathVector *border_path = _getBorderPathv();
373 if (border_path != NULL) {
374 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
375 }
376 }
378 for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
380 /* Transform the requested snap point to this item's coordinates */
381 Geom::Matrix i2doc(Geom::identity());
382 SPItem *root_item = NULL;
383 /* We might have a clone at hand, so make sure we get the root item */
384 if (SP_IS_USE((*i).item)) {
385 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
386 root_item = sp_use_root(SP_USE((*i).item));
387 g_return_if_fail(root_item);
388 } else {
389 i2doc = (*i).item->i2doc_affine();
390 root_item = (*i).item;
391 }
393 //Build a list of all paths considered for snapping to
395 //Add the item's path to snap to
396 if (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapModeNode()) {
397 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
398 // Snapping to the path of characters is very cool, but for a large
399 // chunk of text this will take ages! So limit snapping to text paths
400 // containing max. 240 characters. Snapping the bbox will not be affected
401 bool very_lenghty_prose = false;
402 if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
403 very_lenghty_prose = sp_text_get_length(SP_TEXT(root_item)) > 240;
404 }
405 // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
406 // which corresponds to a lag of 500 msec. This is for snapping a rect
407 // to a single line of text.
409 // Snapping for example to a traced bitmap is also very stressing for
410 // the CPU, so we'll only snap to paths having no more than 500 nodes
411 // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
412 bool very_complex_path = false;
413 if (SP_IS_PATH(root_item)) {
414 very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
415 }
417 if (!very_lenghty_prose && !very_complex_path) {
418 SPCurve *curve = curve_for_item(root_item);
419 if (curve) {
420 // We will get our own copy of the pathvector, which must be freed at some point
422 // Geom::PathVector *pv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
424 Geom::PathVector *pv = new Geom::PathVector(curve->get_pathvector());
425 (*pv) *= root_item->i2d_affine() * (*i).additional_affine * _snapmanager->getDesktop()->doc2dt(); // (_edit_transform * _i2d_transform);
427 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
428 curve->unref();
429 }
430 }
431 }
432 }
434 //Add the item's bounding box to snap to
435 if (_snapmanager->snapprefs.getSnapToBBoxPath() && _snapmanager->snapprefs.getSnapModeBBox()) {
436 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
437 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
438 // of the item AND the bbox of the clipping path at the same time
439 if (!(*i).clip_or_mask) {
440 Geom::OptRect rect;
441 root_item->invoke_bbox( rect, i2doc, TRUE, bbox_type);
442 if (rect) {
443 Geom::PathVector *path = _getPathvFromRect(*rect);
444 rect = root_item->getBboxDesktop(bbox_type);
445 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
446 }
447 }
448 }
449 }
450 }
451 }
452 }
454 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
455 Inkscape::SnapCandidatePoint const &p,
456 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
457 SPPath const *selected_path) const
458 {
459 _collectPaths(p.getPoint(), p.getSourceType(), p.getSourceNum() <= 0);
460 // Now we can finally do the real snapping, using the paths collected above
462 g_assert(_snapmanager->getDesktop() != NULL);
463 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
465 bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
467 if (p.getSourceNum() <= 0) {
468 /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
469 * currently being edited, because that path requires special care: when snapping to nodes
470 * only the unselected nodes of that path should be considered, and these will be passed on separately.
471 * This path must not be ignored however when snapping to the paths, so we add it here
472 * manually when applicable.
473 * */
474 if (node_tool_active) {
475 SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
476 if (curve) {
477 Geom::PathVector *pathv = pathvector_for_curve(SP_ITEM(selected_path), curve, true, true, Geom::identity(), Geom::identity()); // We will get our own copy of the path, which must be freed at some point
478 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
479 curve->unref();
480 }
481 }
482 }
484 int num_path = 0;
485 int num_segm = 0;
487 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
488 bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
489 //if true then this pathvector it_pv is currently being edited in the node tool
491 for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
492 // Find a nearest point for each curve within this path
493 // n curves will return n time values with 0 <= t <= 1
494 std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
496 std::vector<double>::const_iterator np = anp.begin();
497 unsigned int index = 0;
498 for (; np != anp.end(); np++, index++) {
499 Geom::Curve const *curve = &((*it_pv).at_index(index));
500 Geom::Point const sp_doc = curve->pointAt(*np);
502 bool c1 = true;
503 bool c2 = true;
504 if (being_edited) {
505 /* If the path is being edited, then we should only snap though to stationary pieces of the path
506 * and not to the pieces that are being dragged around. This way we avoid
507 * self-snapping. For this we check whether the nodes at both ends of the current
508 * piece are unselected; if they are then this piece must be stationary
509 */
510 g_assert(unselected_nodes != NULL);
511 Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
512 Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
513 c1 = isUnselectedNode(start_pt, unselected_nodes);
514 c2 = isUnselectedNode(end_pt, unselected_nodes);
515 /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
516 * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
517 * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
518 * used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
519 * should be in the exact same order for both classes, so we can index them
520 * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
521 */
522 }
524 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
525 if (!being_edited || (c1 && c2)) {
526 Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
527 if (dist < getSnapperTolerance()) {
528 sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, num_path, num_segm, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, p.getSourceType(), p.getSourceNum(), it_p->target_type, it_p->target_bbox));
529 }
530 }
531 }
532 num_segm++;
533 } // End of: for (Geom::PathVector::iterator ....)
534 num_path++;
535 }
536 }
538 /* Returns true if point is coincident with one of the unselected nodes */
539 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
540 {
541 if (unselected_nodes == NULL) {
542 return false;
543 }
545 if (unselected_nodes->size() == 0) {
546 return false;
547 }
549 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
550 if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
551 return true;
552 }
553 }
555 return false;
556 }
558 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
559 Inkscape::SnapCandidatePoint const &p,
560 SnapConstraint const &c,
561 Geom::Point const &p_proj_on_constraint) const
562 {
564 _collectPaths(p_proj_on_constraint, p.getSourceType(), p.getSourceNum() <= 0);
566 // Now we can finally do the real snapping, using the paths collected above
568 g_assert(_snapmanager->getDesktop() != NULL);
569 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint);
571 Geom::Point direction_vector = c.getDirection();
572 if (!is_zero(direction_vector)) {
573 direction_vector = Geom::unit_vector(direction_vector);
574 }
576 // The intersection point of the constraint line with any path, must lie within two points on the
577 // SnapConstraint: p_min_on_cl and p_max_on_cl. The distance between those points is twice the snapping tolerance
578 Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint - getSnapperTolerance() * direction_vector);
579 Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint + getSnapperTolerance() * direction_vector);
580 Geom::Coord tolerance = getSnapperTolerance();
582 // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have
583 // to convert the snapper coordinates from the desktop coordinates to document coordinates
585 std::vector<Geom::Path> constraint_path;
586 if (c.isCircular()) {
587 Geom::Circle constraint_circle(_snapmanager->getDesktop()->dt2doc(c.getPoint()), c.getRadius());
588 constraint_circle.getPath(constraint_path);
589 } else {
590 Geom::Path constraint_line;
591 constraint_line.start(p_min_on_cl);
592 constraint_line.appendNew<Geom::LineSegment>(p_max_on_cl);
593 constraint_path.push_back(constraint_line);
594 }
595 // Length of constraint_path will always be one
597 // Find all intersections of the constrained path with the snap target candidates
598 std::vector<Geom::Point> intersections;
599 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
600 if (k->path_vector) {
601 // Do the intersection math
602 Geom::CrossingSet cs = Geom::crossings(constraint_path, *(k->path_vector));
603 // Store the results as intersection points
604 unsigned int index = 0;
605 for (Geom::CrossingSet::const_iterator i = cs.begin(); i != cs.end(); i++) {
606 if (index >= constraint_path.size()) {
607 break;
608 }
609 // Reconstruct and store the points of intersection
610 for (Geom::Crossings::const_iterator m = (*i).begin(); m != (*i).end(); m++) {
611 intersections.push_back(constraint_path[index].pointAt((*m).ta));
612 }
613 index++;
614 }
616 //Geom::crossings will not consider the closing segment apparently, so we'll handle that separately here
617 //TODO: This should have been fixed in rev. #9859, which makes this workaround obsolete
618 for(Geom::PathVector::iterator it_pv = k->path_vector->begin(); it_pv != k->path_vector->end(); ++it_pv) {
619 if (it_pv->closed()) {
620 // Get the closing linesegment and convert it to a path
621 Geom::Path cls;
622 cls.close(false);
623 cls.append(it_pv->back_closed());
624 // Intersect that closing path with the constrained path
625 Geom::Crossings cs = Geom::crossings(constraint_path.front(), cls);
626 // Reconstruct and store the points of intersection
627 index = 0; // assuming the constraint path vector has only one path
628 for (Geom::Crossings::const_iterator m = cs.begin(); m != cs.end(); m++) {
629 intersections.push_back(constraint_path[index].pointAt((*m).ta));
630 }
631 }
632 }
634 // Convert the collected points of intersection to snapped points
635 for (std::vector<Geom::Point>::iterator p_inters = intersections.begin(); p_inters != intersections.end(); p_inters++) {
636 // Convert to desktop coordinates
637 (*p_inters) = _snapmanager->getDesktop()->doc2dt(*p_inters);
638 // Construct a snapped point
639 Geom::Coord dist = Geom::L2(p.getPoint() - *p_inters);
640 SnappedPoint s = SnappedPoint(*p_inters, p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);;
641 // Store the snapped point
642 if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it
643 sc.points.push_back(s);
644 }
645 }
646 }
647 }
648 }
651 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
652 Inkscape::SnapCandidatePoint const &p,
653 Geom::OptRect const &bbox_to_snap,
654 std::vector<SPItem const *> const *it,
655 std::vector<SnapCandidatePoint> *unselected_nodes) const
656 {
657 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false ) {
658 return;
659 }
661 /* Get a list of all the SPItems that we will try to snap to */
662 if (p.getSourceNum() <= 0) {
663 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
664 _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
665 }
667 // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
668 bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
669 _snapmanager->snapprefs.getSnapToItemNode() ||
670 _snapmanager->snapprefs.getSnapSmoothNodes() ||
671 _snapmanager->snapprefs.getSnapLineMidpoints() ||
672 _snapmanager->snapprefs.getSnapObjectMidpoints()
673 )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
674 _snapmanager->snapprefs.getSnapToBBoxNode() ||
675 _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
676 _snapmanager->snapprefs.getSnapBBoxMidpoints()
677 )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
678 _snapmanager->snapprefs.getIncludeItemCenter() ||
679 _snapmanager->snapprefs.getSnapToPageBorder()
680 ));
682 if (snap_nodes) {
683 _snapNodes(sc, p, unselected_nodes);
684 }
686 if ((_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getSnapToItemPath()) ||
687 (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxPath()) ||
688 (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && _snapmanager->snapprefs.getSnapToPageBorder())) {
689 unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
690 if (n > 0) {
691 /* While editing a path in the node tool, findCandidates must ignore that path because
692 * of the node snapping requirements (i.e. only unselected nodes must be snapable).
693 * That path must not be ignored however when snapping to the paths, so we add it here
694 * manually when applicable
695 */
696 SPPath *path = NULL;
697 if (it != NULL) {
698 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
699 path = SP_PATH(*it->begin());
700 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
701 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
702 }
703 _snapPaths(sc, p, unselected_nodes, path);
704 } else {
705 _snapPaths(sc, p, NULL, NULL);
706 }
707 }
708 }
710 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
711 Inkscape::SnapCandidatePoint const &p,
712 Geom::OptRect const &bbox_to_snap,
713 SnapConstraint const &c,
714 std::vector<SPItem const *> const *it,
715 std::vector<SnapCandidatePoint> *unselected_nodes) const
716 {
717 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
718 return;
719 }
721 // project the mouse pointer onto the constraint. Only the projected point will be considered for snapping
722 Geom::Point pp = c.projection(p.getPoint());
724 /* Get a list of all the SPItems that we will try to snap to */
725 if (p.getSourceNum() <= 0) {
726 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(pp, pp);
727 _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
728 }
730 // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
731 // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
732 // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
734 // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
735 bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
736 _snapmanager->snapprefs.getSnapToItemNode() ||
737 _snapmanager->snapprefs.getSnapSmoothNodes() ||
738 _snapmanager->snapprefs.getSnapLineMidpoints() ||
739 _snapmanager->snapprefs.getSnapObjectMidpoints()
740 )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
741 _snapmanager->snapprefs.getSnapToBBoxNode() ||
742 _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
743 _snapmanager->snapprefs.getSnapBBoxMidpoints()
744 )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
745 _snapmanager->snapprefs.getIncludeItemCenter() ||
746 _snapmanager->snapprefs.getSnapToPageBorder()
747 ));
749 if (snap_nodes) {
750 _snapNodes(sc, p, unselected_nodes, c, pp);
751 }
753 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
754 _snapPathsConstrained(sc, p, c, pp);
755 }
756 }
759 // This method is used to snap a guide to nodes, while dragging the guide around
760 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
761 Geom::Point const &p,
762 Geom::Point const &guide_normal) const
763 {
764 /* Get a list of all the SPItems that we will try to snap to */
765 std::vector<SPItem*> cand;
766 std::vector<SPItem const *> const it; //just an empty list
768 _findCandidates(_snapmanager->getDocument()->getRoot(), &it, true, Geom::Rect(p, p), false, Geom::identity());
769 _snapTranslatingGuide(sc, p, guide_normal);
771 }
773 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
774 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
775 Geom::Point const &p,
776 Geom::Point const &guide_normal,
777 SnapConstraint const &/*c*/) const
778 {
779 /* Get a list of all the SPItems that we will try to snap to */
780 std::vector<SPItem*> cand;
781 std::vector<SPItem const *> const it; //just an empty list
783 _findCandidates(_snapmanager->getDocument()->getRoot(), &it, true, Geom::Rect(p, p), false, Geom::identity());
784 _snapTranslatingGuide(sc, p, guide_normal);
786 }
788 /**
789 * \return true if this Snapper will snap at least one kind of point.
790 */
791 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
792 {
793 bool snap_to_something = (_snapmanager->snapprefs.getSnapModeNode() && (
794 _snapmanager->snapprefs.getSnapToItemPath() ||
795 _snapmanager->snapprefs.getSnapToItemNode() ||
796 _snapmanager->snapprefs.getSnapSmoothNodes() ||
797 _snapmanager->snapprefs.getSnapLineMidpoints() ||
798 _snapmanager->snapprefs.getSnapObjectMidpoints()
799 )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
800 _snapmanager->snapprefs.getSnapToBBoxPath() ||
801 _snapmanager->snapprefs.getSnapToBBoxNode() ||
802 _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
803 _snapmanager->snapprefs.getSnapBBoxMidpoints()
804 )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
805 _snapmanager->snapprefs.getSnapToPageBorder() ||
806 _snapmanager->snapprefs.getIncludeItemCenter()
807 ));
809 return (_snap_enabled && snap_to_something);
810 }
812 void Inkscape::ObjectSnapper::_clear_paths() const
813 {
814 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
815 delete k->path_vector;
816 }
817 _paths_to_snap_to->clear();
818 }
820 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
821 {
822 Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point((_snapmanager->getDocument())->getWidth(),(_snapmanager->getDocument())->getHeight()));
823 return _getPathvFromRect(border_rect);
824 }
826 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
827 {
828 SPCurve const *border_curve = SPCurve::new_from_rect(rect, true);
829 if (border_curve) {
830 Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
831 return dummy;
832 } else {
833 return NULL;
834 }
835 }
837 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
838 {
839 Geom::Coord w = (_snapmanager->getDocument())->getWidth();
840 Geom::Coord h = (_snapmanager->getDocument())->getHeight();
841 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
842 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
843 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
844 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
845 }
847 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
848 std::vector<SnapCandidatePoint> *points,
849 bool const /*isTarget*/,
850 bool const includeCorners,
851 bool const includeLineMidpoints,
852 bool const includeObjectMidpoints)
853 {
854 if (bbox) {
855 // collect the corners of the bounding box
856 for ( unsigned k = 0 ; k < 4 ; k++ ) {
857 if (includeCorners) {
858 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, -1, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
859 }
860 // optionally, collect the midpoints of the bounding box's edges too
861 if (includeLineMidpoints) {
862 points->push_back(Inkscape::SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox));
863 }
864 }
865 if (includeObjectMidpoints) {
866 points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
867 }
868 }
869 }
871 /*
872 Local Variables:
873 mode:c++
874 c-file-style:"stroustrup"
875 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
876 indent-tabs-mode:nil
877 fill-column:99
878 End:
879 */
880 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :