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 *
9 * Copyright (C) 2005 - 2008 Authors
10 *
11 * Released under GNU GPL, read the file 'COPYING' for more information
12 */
14 #include "svg/svg.h"
15 #include <2geom/path-intersection.h>
16 #include <2geom/point.h>
17 #include <2geom/rect.h>
18 #include <2geom/line.h>
19 #include <2geom/circle.h>
20 #include "document.h"
21 #include "sp-namedview.h"
22 #include "sp-image.h"
23 #include "sp-item-group.h"
24 #include "sp-item.h"
25 #include "sp-use.h"
26 #include "display/curve.h"
27 #include "inkscape.h"
28 #include "preferences.h"
29 #include "sp-text.h"
30 #include "sp-flowtext.h"
31 #include "text-editing.h"
32 #include "sp-clippath.h"
33 #include "sp-mask.h"
34 #include "helper/geom-curves.h"
35 #include "desktop.h"
37 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
38 : Snapper(sm, d)
39 {
40 _candidates = new std::vector<SnapCandidateItem>;
41 _points_to_snap_to = new std::vector<Inkscape::SnapCandidatePoint>;
42 _paths_to_snap_to = new std::vector<Inkscape::SnapCandidatePath >;
43 }
45 Inkscape::ObjectSnapper::~ObjectSnapper()
46 {
47 _candidates->clear();
48 delete _candidates;
50 _points_to_snap_to->clear();
51 delete _points_to_snap_to;
53 _clear_paths();
54 delete _paths_to_snap_to;
55 }
57 /**
58 * \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
59 */
60 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
61 {
62 SPDesktop const *dt = _snapmanager->getDesktop();
63 double const zoom = dt ? dt->current_zoom() : 1;
64 return _snapmanager->snapprefs.getObjectTolerance() / zoom;
65 }
67 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
68 {
69 return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
70 }
72 /**
73 * Find all items within snapping range.
74 * \param parent Pointer to the document's root, or to a clipped path or mask object
75 * \param it List of items to ignore
76 * \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
77 * \param DimensionToSnap Snap in X, Y, or both directions.
78 */
80 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
81 std::vector<SPItem const *> const *it,
82 bool const &first_point,
83 Geom::Rect const &bbox_to_snap,
84 DimensionToSnap const snap_dim,
85 bool const clip_or_mask,
86 Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
87 {
88 bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
89 bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
91 if (!(c1 || c2)) {
92 return;
93 }
95 if (_snapmanager->getDesktop() == NULL) {
96 g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
97 // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
98 }
101 if (first_point) {
102 _candidates->clear();
103 }
105 Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
106 bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
108 for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
109 if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
110 // Snapping to items in a locked layer is allowed
111 // Don't snap to hidden objects, unless they're a clipped path or a mask
112 /* See if this item is on the ignore list */
113 std::vector<SPItem const *>::const_iterator i;
114 if (it != NULL) {
115 i = it->begin();
116 while (i != it->end() && *i != o) {
117 i++;
118 }
119 }
121 if (it == NULL || i == it->end()) {
122 SPItem *item = SP_ITEM(o);
123 if (item) {
124 SPObject *obj = NULL;
125 if (!clip_or_mask) { // cannot clip or mask more than once
126 // The current item is not a clipping path or a mask, but might
127 // still be the subject of clipping or masking itself ; if so, then
128 // we should also consider that path or mask for snapping to
129 obj = SP_OBJECT(item->clip_ref->getObject());
130 if (obj) {
131 _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
132 }
133 obj = SP_OBJECT(item->mask_ref->getObject());
134 if (obj) {
135 _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
136 }
137 }
138 }
140 if (SP_IS_GROUP(o)) {
141 _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
142 } else {
143 Geom::OptRect bbox_of_item = Geom::Rect();
144 if (clip_or_mask) {
145 // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
146 // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
147 sp_item_invoke_bbox(item,
148 bbox_of_item,
149 sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
150 true);
151 } else {
152 sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
153 }
154 if (bbox_of_item) {
155 // See if the item is within range
156 if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
157 // This item is within snapping range, so record it as a candidate
158 _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
159 // For debugging: print the id of the candidate to the console
160 // SPObject *obj = (SPObject*)item;
161 // std::cout << "Snap candidate added: " << obj->getId() << std::endl;
162 }
163 }
164 }
165 }
166 }
167 }
168 }
171 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
172 bool const &first_point) const
173 {
174 // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
175 // e.g. when translating an item using the selector tool, then we will only do this for the
176 // first point and store the collection for later use. This significantly improves the performance
177 if (first_point) {
178 _points_to_snap_to->clear();
180 // Determine the type of bounding box we should snap to
181 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
183 bool p_is_a_node = t & Inkscape::SNAPSOURCE_NODE_CATEGORY;
184 bool p_is_a_bbox = t & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
185 bool p_is_other = t & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
187 // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
188 g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
190 if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
191 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
192 bool prefs_bbox = prefs->getBool("/tools/bounding_box");
193 bbox_type = !prefs_bbox ?
194 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
195 }
197 // Consider the page border for snapping to
198 if (_snapmanager->snapprefs.getSnapToPageBorder()) {
199 _getBorderNodes(_points_to_snap_to);
200 }
202 for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
203 //Geom::Matrix i2doc(Geom::identity());
204 SPItem *root_item = (*i).item;
205 if (SP_IS_USE((*i).item)) {
206 root_item = sp_use_root(SP_USE((*i).item));
207 }
208 g_return_if_fail(root_item);
210 //Collect all nodes so we can snap to them
211 if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
212 // Note: there are two ways in which intersections are considered:
213 // Method 1: Intersections are calculated for each shape individually, for both the
214 // snap source and snap target (see sp_shape_snappoints)
215 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
216 // the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
217 // Some differences:
218 // - Method 1 doesn't find intersections within a set of multiple objects
219 // - Method 2 only works for targets
220 // When considering intersections as snap targets:
221 // - Method 1 only works when snapping to nodes, whereas
222 // - Method 2 only works when snapping to paths
223 // - There will be performance differences too!
224 // If both methods are being used simultaneously, then this might lead to duplicate targets!
226 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
227 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
228 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
229 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
230 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
231 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
232 if (_snapmanager->snapprefs.getSnapToItemPath()) {
233 _snapmanager->snapprefs.setSnapIntersectionCS(false);
234 }
236 sp_item_snappoints(root_item, *_points_to_snap_to, &_snapmanager->snapprefs);
238 if (_snapmanager->snapprefs.getSnapToItemPath()) {
239 _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
240 }
241 }
243 //Collect the bounding box's corners so we can snap to them
244 if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
245 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
246 // of the item AND the bbox of the clipping path at the same time
247 if (!(*i).clip_or_mask) {
248 Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
249 getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
250 }
251 }
252 }
253 }
254 }
256 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
257 Inkscape::SnapCandidatePoint const &p,
258 std::vector<SnapCandidatePoint> *unselected_nodes) const
259 {
260 // Iterate through all nodes, find out which one is the closest to p, and snap to it!
262 _collectNodes(p.getSourceType(), p.getSourceNum() == 0);
264 if (unselected_nodes != NULL) {
265 _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
266 }
268 SnappedPoint s;
269 bool success = false;
271 for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
272 Geom::Coord dist = Geom::L2((*k).getPoint() - p.getPoint());
273 if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
274 s = SnappedPoint((*k).getPoint(), p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
275 success = true;
276 }
277 }
279 if (success) {
280 sc.points.push_back(s);
281 }
282 }
284 void Inkscape::ObjectSnapper::_snapTranslatingGuide(SnappedConstraints &sc,
285 Geom::Point const &p,
286 Geom::Point const &guide_normal) const
287 {
288 // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
289 _collectNodes(SNAPSOURCE_GUIDE, true);
291 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
292 _collectPaths(Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), true);
293 _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
294 }
296 SnappedPoint s;
298 Geom::Coord tol = getSnapperTolerance();
300 for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
301 // Project each node (*k) on the guide line (running through point p)
302 Geom::Point p_proj = Geom::projection((*k).getPoint(), Geom::Line(p, p + Geom::rot90(guide_normal)));
303 Geom::Coord dist = Geom::L2((*k).getPoint() - p_proj); // distance from node to the guide
304 Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
305 if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
306 s = SnappedPoint((*k).getPoint(), SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
307 sc.points.push_back(s);
308 }
309 }
310 }
313 /**
314 * Returns index of first NR_END bpath in array.
315 */
317 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &p,
318 bool const &first_point) const
319 {
320 // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
321 // e.g. when translating an item using the selector tool, then we will only do this for the
322 // first point and store the collection for later use. This significantly improves the performance
323 if (first_point) {
324 _clear_paths();
326 // Determine the type of bounding box we should snap to
327 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
329 bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
330 bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
332 if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
333 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
334 int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
335 bbox_type = !prefs_bbox ?
336 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
337 }
339 // Consider the page border for snapping
340 if (_snapmanager->snapprefs.getSnapToPageBorder()) {
341 Geom::PathVector *border_path = _getBorderPathv();
342 if (border_path != NULL) {
343 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
344 }
345 }
347 for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
349 /* Transform the requested snap point to this item's coordinates */
350 Geom::Matrix i2doc(Geom::identity());
351 SPItem *root_item = NULL;
352 /* We might have a clone at hand, so make sure we get the root item */
353 if (SP_IS_USE((*i).item)) {
354 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
355 root_item = sp_use_root(SP_USE((*i).item));
356 g_return_if_fail(root_item);
357 } else {
358 i2doc = sp_item_i2doc_affine((*i).item);
359 root_item = (*i).item;
360 }
362 //Build a list of all paths considered for snapping to
364 //Add the item's path to snap to
365 if (_snapmanager->snapprefs.getSnapToItemPath()) {
366 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
367 // Snapping to the path of characters is very cool, but for a large
368 // chunk of text this will take ages! So limit snapping to text paths
369 // containing max. 240 characters. Snapping the bbox will not be affected
370 bool very_lenghty_prose = false;
371 if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
372 very_lenghty_prose = sp_text_get_length(SP_TEXT(root_item)) > 240;
373 }
374 // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
375 // which corresponds to a lag of 500 msec. This is for snapping a rect
376 // to a single line of text.
378 // Snapping for example to a traced bitmap is also very stressing for
379 // the CPU, so we'll only snap to paths having no more than 500 nodes
380 // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
381 bool very_complex_path = false;
382 if (SP_IS_PATH(root_item)) {
383 very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
384 }
386 if (!very_lenghty_prose && !very_complex_path) {
387 SPCurve *curve = curve_for_item(root_item);
388 if (curve) {
389 // We will get our own copy of the path, which must be freed at some point
390 Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
391 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(borderpathv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
392 curve->unref();
393 }
394 }
395 }
396 }
398 //Add the item's bounding box to snap to
399 if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
400 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
401 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
402 // of the item AND the bbox of the clipping path at the same time
403 if (!(*i).clip_or_mask) {
404 Geom::OptRect rect;
405 sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
406 if (rect) {
407 Geom::PathVector *path = _getPathvFromRect(*rect);
408 rect = sp_item_bbox_desktop(root_item, bbox_type);
409 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
410 }
411 }
412 }
413 }
414 }
415 }
416 }
418 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
419 Inkscape::SnapCandidatePoint const &p,
420 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
421 SPPath const *selected_path) const
422 {
423 _collectPaths(p, p.getSourceNum() == 0);
424 // Now we can finally do the real snapping, using the paths collected above
426 g_assert(_snapmanager->getDesktop() != NULL);
427 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
429 bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
431 if (p.getSourceNum() == 0) {
432 /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
433 * currently being edited, because that path requires special care: when snapping to nodes
434 * only the unselected nodes of that path should be considered, and these will be passed on separately.
435 * This path must not be ignored however when snapping to the paths, so we add it here
436 * manually when applicable.
437 * */
438 if (node_tool_active) {
439 SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
440 if (curve) {
441 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
442 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
443 curve->unref();
444 }
445 }
446 }
448 int num_path = 0;
449 int num_segm = 0;
451 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
452 bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
453 //if true then this pathvector it_pv is currently being edited in the node tool
455 for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
456 // Find a nearest point for each curve within this path
457 // n curves will return n time values with 0 <= t <= 1
458 std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
460 std::vector<double>::const_iterator np = anp.begin();
461 unsigned int index = 0;
462 for (; np != anp.end(); np++, index++) {
463 Geom::Curve const *curve = &((*it_pv).at_index(index));
464 Geom::Point const sp_doc = curve->pointAt(*np);
466 bool c1 = true;
467 bool c2 = true;
468 if (being_edited) {
469 /* If the path is being edited, then we should only snap though to stationary pieces of the path
470 * and not to the pieces that are being dragged around. This way we avoid
471 * self-snapping. For this we check whether the nodes at both ends of the current
472 * piece are unselected; if they are then this piece must be stationary
473 */
474 g_assert(unselected_nodes != NULL);
475 Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
476 Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
477 c1 = isUnselectedNode(start_pt, unselected_nodes);
478 c2 = isUnselectedNode(end_pt, unselected_nodes);
479 /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
480 * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
481 * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
482 * used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
483 * should be in the exact same order for both classes, so we can index them
484 * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
485 */
486 }
488 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
489 if (!being_edited || (c1 && c2)) {
490 Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
491 if (dist < getSnapperTolerance()) {
492 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));
493 }
494 }
495 }
496 num_segm++;
497 } // End of: for (Geom::PathVector::iterator ....)
498 num_path++;
499 }
500 }
502 /* Returns true if point is coincident with one of the unselected nodes */
503 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
504 {
505 if (unselected_nodes == NULL) {
506 return false;
507 }
509 if (unselected_nodes->size() == 0) {
510 return false;
511 }
513 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
514 if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
515 return true;
516 }
517 }
519 return false;
520 }
522 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
523 Inkscape::SnapCandidatePoint const &p,
524 SnapConstraint const &c) const
525 {
527 _collectPaths(p, p.getSourceNum() == 0);
529 // Now we can finally do the real snapping, using the paths collected above
531 g_assert(_snapmanager->getDesktop() != NULL);
532 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
534 Geom::Point direction_vector = c.getDirection();
535 if (!is_zero(direction_vector)) {
536 direction_vector = Geom::unit_vector(direction_vector);
537 }
539 // The intersection point of the constraint line with any path, must lie within two points on the
540 // SnapConstraint: p_min_on_cl and p_max_on_cl. The distance between those points is twice the snapping tolerance
541 Geom::Point const p_proj_on_cl = p.getPoint(); // projection has already been taken care of in constrainedSnap in the snapmanager;
542 Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);
543 Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
544 Geom::Coord tolerance = getSnapperTolerance();
546 // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have
547 // to convert the snapper coordinates from the desktop coordinates to document coordinates
549 std::vector<Geom::Path> constraint_path;
550 if (c.isCircular()) {
551 Geom::Circle constraint_circle(_snapmanager->getDesktop()->dt2doc(c.getPoint()), c.getRadius());
552 constraint_circle.getPath(constraint_path);
553 } else {
554 Geom::Path constraint_line;
555 constraint_line.start(p_min_on_cl);
556 constraint_line.appendNew<Geom::LineSegment>(p_max_on_cl);
557 constraint_path.push_back(constraint_line);
558 }
560 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
561 if (k->path_vector) {
562 Geom::CrossingSet cs = Geom::crossings(constraint_path, *(k->path_vector));
563 unsigned int index = 0;
564 for (Geom::CrossingSet::const_iterator i = cs.begin(); i != cs.end(); i++) {
565 if (index >= constraint_path.size()) {
566 break;
567 }
568 for (Geom::Crossings::const_iterator m = (*i).begin(); m != (*i).end(); m++) {
569 //std::cout << "ta = " << (*m).ta << " | tb = " << (*m).tb << std::endl;
570 // Reconstruct the point of intersection
571 Geom::Point p_inters = constraint_path[index].pointAt((*m).ta);
572 // .. and convert it to desktop coordinates
573 p_inters = _snapmanager->getDesktop()->doc2dt(p_inters);
574 Geom::Coord dist = Geom::L2(p_proj_on_cl - p_inters);
575 SnappedPoint s = SnappedPoint(p_inters, p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);;
576 if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it
577 sc.points.push_back(s);
578 }
579 }
580 index++;
581 }
582 }
583 }
584 }
587 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
588 Inkscape::SnapCandidatePoint const &p,
589 Geom::OptRect const &bbox_to_snap,
590 std::vector<SPItem const *> const *it,
591 std::vector<SnapCandidatePoint> *unselected_nodes) const
592 {
593 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false ) {
594 return;
595 }
597 /* Get a list of all the SPItems that we will try to snap to */
598 if (p.getSourceNum() == 0) {
599 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
600 _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
601 }
603 if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
604 || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
605 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
606 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
607 || _snapmanager->snapprefs.getIncludeItemCenter()) {
608 _snapNodes(sc, p, unselected_nodes);
609 }
611 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
612 unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
613 if (n > 0) {
614 /* While editing a path in the node tool, findCandidates must ignore that path because
615 * of the node snapping requirements (i.e. only unselected nodes must be snapable).
616 * That path must not be ignored however when snapping to the paths, so we add it here
617 * manually when applicable
618 */
619 SPPath *path = NULL;
620 if (it != NULL) {
621 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
622 path = SP_PATH(*it->begin());
623 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
624 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
625 }
626 _snapPaths(sc, p, unselected_nodes, path);
627 } else {
628 _snapPaths(sc, p, NULL, NULL);
629 }
630 }
631 }
633 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
634 Inkscape::SnapCandidatePoint const &p,
635 Geom::OptRect const &bbox_to_snap,
636 SnapConstraint const &c,
637 std::vector<SPItem const *> const *it) const
638 {
639 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
640 return;
641 }
643 /* Get a list of all the SPItems that we will try to snap to */
644 if (p.getSourceNum() == 0) {
645 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
646 _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
647 }
649 // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
650 // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
651 // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
653 // When snapping to objects, we either snap to their nodes or their paths. It is however very
654 // unlikely that any node will be exactly at the constrained line, so for a constrained snap
655 // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
656 // so we will more or less snap to them anyhow.
658 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
659 _snapPathsConstrained(sc, p, c);
660 }
661 }
664 // This method is used to snap a guide to nodes, while dragging the guide around
665 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
666 Geom::Point const &p,
667 Geom::Point const &guide_normal) const
668 {
669 /* Get a list of all the SPItems that we will try to snap to */
670 std::vector<SPItem*> cand;
671 std::vector<SPItem const *> const it; //just an empty list
673 DimensionToSnap snap_dim;
674 if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
675 snap_dim = GUIDE_TRANSL_SNAP_Y;
676 } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
677 snap_dim = GUIDE_TRANSL_SNAP_X;
678 } else {
679 snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
680 }
682 _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
683 _snapTranslatingGuide(sc, p, guide_normal);
685 }
687 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
688 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
689 Geom::Point const &p,
690 Geom::Point const &guide_normal,
691 SnapConstraint const &/*c*/) const
692 {
693 /* Get a list of all the SPItems that we will try to snap to */
694 std::vector<SPItem*> cand;
695 std::vector<SPItem const *> const it; //just an empty list
697 DimensionToSnap snap_dim;
698 if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
699 snap_dim = GUIDE_TRANSL_SNAP_Y;
700 } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
701 snap_dim = GUIDE_TRANSL_SNAP_X;
702 } else {
703 snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
704 }
706 _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
707 _snapTranslatingGuide(sc, p, guide_normal);
709 }
711 /**
712 * \return true if this Snapper will snap at least one kind of point.
713 */
714 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
715 {
716 bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
717 || _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
718 || _snapmanager->snapprefs.getSnapToBBoxPath()
719 || _snapmanager->snapprefs.getSnapToBBoxNode()
720 || _snapmanager->snapprefs.getSnapToPageBorder()
721 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
722 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
723 || _snapmanager->snapprefs.getIncludeItemCenter();
725 return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
726 }
728 bool Inkscape::ObjectSnapper::GuidesMightSnap() const // almost the same as ThisSnapperMightSnap above, but only looking at points (and not paths)
729 {
730 bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
731 || _snapmanager->snapprefs.getSnapToPageBorder()
732 || (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxNode())
733 || (_snapmanager->snapprefs.getSnapModeBBox() && (_snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()))
734 || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()))
735 || (_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getIncludeItemCenter())
736 || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapIntersectionCS()));
738 return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
739 }
741 void Inkscape::ObjectSnapper::_clear_paths() const
742 {
743 for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
744 delete k->path_vector;
745 }
746 _paths_to_snap_to->clear();
747 }
749 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
750 {
751 Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
752 return _getPathvFromRect(border_rect);
753 }
755 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
756 {
757 SPCurve const *border_curve = SPCurve::new_from_rect(rect, true);
758 if (border_curve) {
759 Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
760 return dummy;
761 } else {
762 return NULL;
763 }
764 }
766 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
767 {
768 Geom::Coord w = sp_document_width(_snapmanager->getDocument());
769 Geom::Coord h = sp_document_height(_snapmanager->getDocument());
770 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
771 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
772 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
773 points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
774 }
776 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
777 std::vector<SnapCandidatePoint> *points,
778 bool const /*isTarget*/,
779 bool const includeCorners,
780 bool const includeLineMidpoints,
781 bool const includeObjectMidpoints)
782 {
783 if (bbox) {
784 // collect the corners of the bounding box
785 for ( unsigned k = 0 ; k < 4 ; k++ ) {
786 if (includeCorners) {
787 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, 0, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
788 }
789 // optionally, collect the midpoints of the bounding box's edges too
790 if (includeLineMidpoints) {
791 points->push_back(Inkscape::SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox));
792 }
793 }
794 if (includeObjectMidpoints) {
795 points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
796 }
797 }
798 }
800 /*
801 Local Variables:
802 mode:c++
803 c-file-style:"stroustrup"
804 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
805 indent-tabs-mode:nil
806 fill-column:99
807 End:
808 */
809 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :