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 "libnr/nr-rect-ops.h"
16 #include "libnr/nr-point-fns.h"
17 #include <2geom/path-intersection.h>
18 #include <2geom/point.h>
19 #include <2geom/rect.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::SnapCandidate::SnapCandidate(SPItem* item, bool clip_or_mask, Geom::Matrix additional_affine)
38 : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine)
39 {
40 }
42 Inkscape::SnapCandidate::~SnapCandidate()
43 {
44 }
46 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
47 : Snapper(sm, d)
48 {
49 _candidates = new std::vector<SnapCandidate>;
50 _points_to_snap_to = new std::vector<std::pair<Geom::Point, int> >;
51 _paths_to_snap_to = new std::vector<std::pair<Geom::PathVector*, SnapTargetType> >;
52 }
54 Inkscape::ObjectSnapper::~ObjectSnapper()
55 {
56 _candidates->clear();
57 delete _candidates;
59 _points_to_snap_to->clear();
60 delete _points_to_snap_to;
62 _clear_paths();
63 delete _paths_to_snap_to;
64 }
66 /**
67 * \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
68 */
69 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
70 {
71 SPDesktop const *dt = _snapmanager->getDesktop();
72 double const zoom = dt ? dt->current_zoom() : 1;
73 return _snapmanager->snapprefs.getObjectTolerance() / zoom;
74 }
76 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
77 {
78 return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
79 }
81 /**
82 * Find all items within snapping range.
83 * \param parent Pointer to the document's root, or to a clipped path or mask object
84 * \param it List of items to ignore
85 * \param first_point If true then this point is the first one from a whole bunch of points
86 * \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
87 * \param DimensionToSnap Snap in X, Y, or both directions.
88 */
90 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
91 std::vector<SPItem const *> const *it,
92 bool const &first_point,
93 Geom::Rect const &bbox_to_snap,
94 DimensionToSnap const snap_dim,
95 bool const clip_or_mask,
96 Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
97 {
98 bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
99 bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
101 if (!(c1 || c2)) {
102 return;
103 }
105 if (first_point) {
106 _candidates->clear();
107 }
109 Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
110 bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
112 for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
113 g_assert(_snapmanager->getDesktop() != NULL);
114 if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
115 // Snapping to items in a locked layer is allowed
116 // Don't snap to hidden objects, unless they're a clipped path or a mask
117 /* See if this item is on the ignore list */
118 std::vector<SPItem const *>::const_iterator i;
119 if (it != NULL) {
120 i = it->begin();
121 while (i != it->end() && *i != o) {
122 i++;
123 }
124 }
126 if (it == NULL || i == it->end()) {
127 SPItem *item = SP_ITEM(o);
128 if (item) {
129 SPObject *obj = NULL;
130 if (!clip_or_mask) { // cannot clip or mask more than once
131 // The current item is not a clipping path or a mask, but might
132 // still be the subject of clipping or masking itself ; if so, then
133 // we should also consider that path or mask for snapping to
134 obj = SP_OBJECT(item->clip_ref->getObject());
135 if (obj) {
136 _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
137 }
138 obj = SP_OBJECT(item->mask_ref->getObject());
139 if (obj) {
140 _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
141 }
142 }
143 }
145 if (SP_IS_GROUP(o)) {
146 _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
147 } else {
148 Geom::OptRect bbox_of_item = Geom::Rect();
149 if (clip_or_mask) {
150 // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
151 // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
152 sp_item_invoke_bbox(item,
153 bbox_of_item,
154 sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
155 true);
156 } else {
157 sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
158 }
159 if (bbox_of_item) {
160 // See if the item is within range
161 if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
162 // This item is within snapping range, so record it as a candidate
163 _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
164 // For debugging: print the id of the candidate to the console
165 // SPObject *obj = (SPObject*)item;
166 // std::cout << "Snap candidate added: " << obj->id << std::endl;
167 }
168 }
169 }
170 }
171 }
172 }
173 }
176 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapPreferences::PointType const &t,
177 bool const &first_point) const
178 {
179 // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
180 // e.g. when translating an item using the selector tool, then we will only do this for the
181 // first point and store the collection for later use. This significantly improves the performance
182 if (first_point) {
183 _points_to_snap_to->clear();
185 // Determine the type of bounding box we should snap to
186 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
188 bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
189 bool p_is_a_bbox = t & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
190 bool p_is_a_guide = t & Inkscape::SnapPreferences::SNAPPOINT_GUIDE;
192 // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
193 g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_a_guide) || (p_is_a_node && p_is_a_guide)));
195 if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
196 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
197 bool prefs_bbox = prefs->getBool("/tools/bounding_box");
198 bbox_type = !prefs_bbox ?
199 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
200 }
202 // Consider the page border for snapping to
203 if (_snapmanager->snapprefs.getSnapToPageBorder()) {
204 _getBorderNodes(_points_to_snap_to);
205 }
207 for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
208 //Geom::Matrix i2doc(Geom::identity());
209 SPItem *root_item = (*i).item;
210 if (SP_IS_USE((*i).item)) {
211 root_item = sp_use_root(SP_USE((*i).item));
212 }
213 g_return_if_fail(root_item);
215 //Collect all nodes so we can snap to them
216 if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_a_guide) {
217 // Note: there are two ways in which intersections are considered:
218 // Method 1: Intersections are calculated for each shape individually, for both the
219 // snap source and snap target (see sp_shape_snappoints)
220 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
221 // the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
222 // Some differences:
223 // - Method 1 doesn't find intersections within a set of multiple objects
224 // - Method 2 only works for targets
225 // When considering intersections as snap targets:
226 // - Method 1 only works when snapping to nodes, whereas
227 // - Method 2 only works when snapping to paths
228 // - There will be performance differences too!
229 // If both methods are being used simultaneously, then this might lead to duplicate targets!
231 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
232 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
233 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
234 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
235 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
236 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
237 if (_snapmanager->snapprefs.getSnapToItemPath()) {
238 _snapmanager->snapprefs.setSnapIntersectionCS(false);
239 }
241 sp_item_snappoints(root_item, true, *_points_to_snap_to, &_snapmanager->snapprefs);
243 if (_snapmanager->snapprefs.getSnapToItemPath()) {
244 _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
245 }
246 }
248 //Collect the bounding box's corners so we can snap to them
249 if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_a_guide) {
250 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
251 // of the item AND the bbox of the clipping path at the same time
252 if (!(*i).clip_or_mask) {
253 Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
254 getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
255 }
256 }
257 }
258 }
259 }
261 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
262 Inkscape::SnapPreferences::PointType const &t,
263 Geom::Point const &p,
264 SnapSourceType const &source_type,
265 bool const &first_point,
266 std::vector<std::pair<Geom::Point, int> > *unselected_nodes) const
267 {
268 // Iterate through all nodes, find out which one is the closest to p, and snap to it!
270 _collectNodes(t, first_point);
272 if (unselected_nodes != NULL) {
273 _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
274 }
276 SnappedPoint s;
277 bool success = false;
279 for (std::vector<std::pair<Geom::Point, int> >::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
280 Geom::Coord dist = Geom::L2((*k).first - p);
281 if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
282 s = SnappedPoint((*k).first, source_type, static_cast<Inkscape::SnapTargetType>((*k).second), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
283 success = true;
284 }
285 }
287 if (success) {
288 sc.points.push_back(s);
289 }
290 }
292 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
293 Inkscape::SnapPreferences::PointType const &t,
294 Geom::Point const &p,
295 Geom::Point const &guide_normal) const
296 {
297 // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
298 _collectNodes(t, true);
300 SnappedPoint s;
301 bool success = false;
303 Geom::Coord tol = getSnapperTolerance();
305 for (std::vector<std::pair<Geom::Point, int> >::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
306 // Project each node (*k) on the guide line (running through point p)
307 Geom::Point p_proj = project_on_linesegment((*k).first, p, p + Geom::rot90(guide_normal));
308 Geom::Coord dist = Geom::L2((*k).first - p_proj); // distance from node to the guide
309 Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
310 if ((dist < tol && dist2 < tol) || (getSnapperAlwaysSnap() && dist < s.getSnapDistance())) {
311 s = SnappedPoint((*k).first, SNAPSOURCE_GUIDE, static_cast<Inkscape::SnapTargetType>((*k).second), dist, tol, getSnapperAlwaysSnap(), true);
312 success = true;
313 }
314 }
316 if (success) {
317 sc.points.push_back(s);
318 }
319 }
322 /**
323 * Returns index of first NR_END bpath in array.
324 */
326 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapPreferences::PointType const &t,
327 bool const &first_point) const
328 {
329 // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
330 // e.g. when translating an item using the selector tool, then we will only do this for the
331 // first point and store the collection for later use. This significantly improves the performance
332 if (first_point) {
333 _clear_paths();
335 // Determine the type of bounding box we should snap to
336 SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
338 bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
340 if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
341 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
342 int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
343 bbox_type = !prefs_bbox ?
344 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
345 }
347 // Consider the page border for snapping
348 if (_snapmanager->snapprefs.getSnapToPageBorder()) {
349 Geom::PathVector *border_path = _getBorderPathv();
350 if (border_path != NULL) {
351 _paths_to_snap_to->push_back(std::make_pair(border_path, SNAPTARGET_PAGE_BORDER));
352 }
353 }
355 for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
357 /* Transform the requested snap point to this item's coordinates */
358 Geom::Matrix i2doc(Geom::identity());
359 SPItem *root_item = NULL;
360 /* We might have a clone at hand, so make sure we get the root item */
361 if (SP_IS_USE((*i).item)) {
362 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
363 root_item = sp_use_root(SP_USE((*i).item));
364 g_return_if_fail(root_item);
365 } else {
366 i2doc = sp_item_i2doc_affine((*i).item);
367 root_item = (*i).item;
368 }
370 //Build a list of all paths considered for snapping to
372 //Add the item's path to snap to
373 if (_snapmanager->snapprefs.getSnapToItemPath()) {
374 if (!(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
375 // Snapping to the path of characters is very cool, but for a large
376 // chunk of text this will take ages! So limit snapping to text paths
377 // containing max. 240 characters. Snapping the bbox will not be affected
378 bool very_lenghty_prose = false;
379 if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
380 very_lenghty_prose = sp_text_get_length(SP_TEXT(root_item)) > 240;
381 }
382 // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
383 // which corresponds to a lag of 500 msec. This is for snapping a rect
384 // to a single line of text.
386 // Snapping for example to a traced bitmap is also very stressing for
387 // the CPU, so we'll only snap to paths having no more than 500 nodes
388 // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
389 bool very_complex_path = false;
390 if (SP_IS_PATH(root_item)) {
391 very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
392 }
394 if (!very_lenghty_prose && !very_complex_path) {
395 SPCurve *curve = curve_for_item(root_item);
396 if (curve) {
397 // We will get our own copy of the path, which must be freed at some point
398 Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
399 _paths_to_snap_to->push_back(std::make_pair(borderpathv, SNAPTARGET_PATH)); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
400 curve->unref();
401 }
402 }
403 }
404 }
406 //Add the item's bounding box to snap to
407 if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
408 if (!(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
409 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
410 // of the item AND the bbox of the clipping path at the same time
411 if (!(*i).clip_or_mask) {
412 Geom::OptRect rect;
413 sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
414 if (rect) {
415 Geom::PathVector *path = _getPathvFromRect(*rect);
416 _paths_to_snap_to->push_back(std::make_pair(path, SNAPTARGET_BBOX_EDGE));
417 }
418 }
419 }
420 }
421 }
422 }
423 }
425 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
426 Inkscape::SnapPreferences::PointType const &t,
427 Geom::Point const &p,
428 SnapSourceType const &source_type,
429 bool const &first_point,
430 std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
431 SPPath const *selected_path) const
432 {
433 _collectPaths(t, first_point);
434 // Now we can finally do the real snapping, using the paths collected above
436 g_assert(_snapmanager->getDesktop() != NULL);
437 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
439 bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
441 if (first_point) {
442 /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
443 * currently being edited, because that path requires special care: when snapping to nodes
444 * only the unselected nodes of that path should be considered, and these will be passed on separately.
445 * This path must not be ignored however when snapping to the paths, so we add it here
446 * manually when applicable.
447 *
448 * Note that this path must be the last in line!
449 * */
450 if (node_tool_active) {
451 SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
452 if (curve) {
453 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
454 _paths_to_snap_to->push_back(std::make_pair(pathv, SNAPTARGET_PATH));
455 curve->unref();
456 }
457 }
458 }
460 for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
461 bool const being_edited = (node_tool_active && (*it_p) == _paths_to_snap_to->back());
462 //if true then this pathvector it_pv is currently being edited in the node tool
464 // char * svgd = sp_svg_write_path(**it_p->first);
465 // std::cout << "Dumping the pathvector: " << svgd << std::endl;
467 for(Geom::PathVector::iterator it_pv = (it_p->first)->begin(); it_pv != (it_p->first)->end(); ++it_pv) {
468 // Find a nearest point for each curve within this path
469 // n curves will return n time values with 0 <= t <= 1
470 std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
472 std::vector<double>::const_iterator np = anp.begin();
473 unsigned int index = 0;
474 for (; np != anp.end(); np++, index++) {
475 Geom::Curve const *curve = &((*it_pv).at_index(index));
476 Geom::Point const sp_doc = curve->pointAt(*np);
478 bool c1 = true;
479 bool c2 = true;
480 if (being_edited) {
481 /* If the path is being edited, then we should only snap though to stationary pieces of the path
482 * and not to the pieces that are being dragged around. This way we avoid
483 * self-snapping. For this we check whether the nodes at both ends of the current
484 * piece are unselected; if they are then this piece must be stationary
485 */
486 g_assert(unselected_nodes != NULL);
487 Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
488 Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
489 c1 = isUnselectedNode(start_pt, unselected_nodes);
490 c2 = isUnselectedNode(end_pt, unselected_nodes);
491 /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
492 * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
493 * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
494 * used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
495 * should be in the exact same order for both classes, so we can index them
496 * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
497 */
498 }
500 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
501 if (!being_edited || (c1 && c2)) {
502 Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
503 if (dist < getSnapperTolerance()) {
504 sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, source_type, it_p->second));
505 }
506 }
507 }
508 } // End of: for (Geom::PathVector::iterator ....)
509 }
510 }
512 /* Returns true if point is coincident with one of the unselected nodes */
513 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<std::pair<Geom::Point, int> > const *unselected_nodes) const
514 {
515 if (unselected_nodes == NULL) {
516 return false;
517 }
519 if (unselected_nodes->size() == 0) {
520 return false;
521 }
523 for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
524 if (Geom::L2(point - (*i).first) < 1e-4) {
525 return true;
526 }
527 }
529 return false;
530 }
532 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
533 Inkscape::SnapPreferences::PointType const &t,
534 Geom::Point const &p,
535 SnapSourceType const source_type,
536 bool const &first_point,
537 ConstraintLine const &c) const
538 {
540 _collectPaths(t, first_point);
542 // Now we can finally do the real snapping, using the paths collected above
544 g_assert(_snapmanager->getDesktop() != NULL);
545 Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
547 Geom::Point direction_vector = c.getDirection();
548 if (!is_zero(direction_vector)) {
549 direction_vector = Geom::unit_vector(direction_vector);
550 }
552 Geom::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
553 Geom::Point const p2_on_cl = p1_on_cl + direction_vector;
555 // The intersection point of the constraint line with any path,
556 // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
557 // The distance between those points is twice the snapping tolerance
558 Geom::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
559 Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);
560 Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
562 Geom::Path cl;
563 std::vector<Geom::Path> clv;
564 cl.start(p_min_on_cl);
565 cl.appendNew<Geom::LineSegment>(p_max_on_cl);
566 clv.push_back(cl);
568 for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
569 if (k->first) {
570 Geom::CrossingSet cs = Geom::crossings(clv, *(k->first));
571 if (cs.size() > 0) {
572 // We need only the first element of cs, because cl is only a single straight linesegment
573 // This first element contains a vector filled with crossings of cl with k->first
574 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {
575 if ((*m).ta >= 0 && (*m).ta <= 1 ) {
576 // Reconstruct the point of intersection
577 Geom::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
578 // When it's within snapping range, then return it
579 // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)
580 Geom::Coord dist = Geom::L2(_snapmanager->getDesktop()->dt2doc(p_proj_on_cl) - p_inters);
581 SnappedPoint s(_snapmanager->getDesktop()->doc2dt(p_inters), source_type, k->second, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
582 sc.points.push_back(s);
583 }
584 }
585 }
586 }
587 }
588 }
591 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
592 Inkscape::SnapPreferences::PointType const &t,
593 Geom::Point const &p,
594 SnapSourceType const &source_type,
595 bool const &first_point,
596 Geom::OptRect const &bbox_to_snap,
597 std::vector<SPItem const *> const *it,
598 std::vector<std::pair<Geom::Point, int> > *unselected_nodes) const
599 {
600 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false ) {
601 return;
602 }
604 /* Get a list of all the SPItems that we will try to snap to */
605 if (first_point) {
606 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
607 _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
608 }
610 if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
611 || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
612 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
613 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
614 || _snapmanager->snapprefs.getIncludeItemCenter()) {
615 _snapNodes(sc, t, p, source_type, first_point, unselected_nodes);
616 }
618 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
619 unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
620 if (n > 0) {
621 /* While editing a path in the node tool, findCandidates must ignore that path because
622 * of the node snapping requirements (i.e. only unselected nodes must be snapable).
623 * That path must not be ignored however when snapping to the paths, so we add it here
624 * manually when applicable
625 */
626 SPPath *path = NULL;
627 if (it != NULL) {
628 g_assert(SP_IS_PATH(*it->begin()));
629 g_assert(it->size() == 1);
630 path = SP_PATH(*it->begin());
631 }
632 _snapPaths(sc, t, p, source_type, first_point, unselected_nodes, path);
633 } else {
634 _snapPaths(sc, t, p, source_type, first_point, NULL, NULL);
635 }
636 }
637 }
639 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
640 Inkscape::SnapPreferences::PointType const &t,
641 Geom::Point const &p,
642 SnapSourceType const &source_type,
643 bool const &first_point,
644 Geom::OptRect const &bbox_to_snap,
645 ConstraintLine const &c,
646 std::vector<SPItem const *> const *it) const
647 {
648 if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false) {
649 return;
650 }
652 /* Get a list of all the SPItems that we will try to snap to */
653 if (first_point) {
654 Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
655 _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
656 }
658 // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
659 // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
660 // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
662 // When snapping to objects, we either snap to their nodes or their paths. It is however very
663 // unlikely that any node will be exactly at the constrained line, so for a constrained snap
664 // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
665 // so we will more or less snap to them anyhow.
667 if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
668 _snapPathsConstrained(sc, t, p, source_type, first_point, c);
669 }
670 }
673 // This method is used to snap a guide to nodes, while dragging the guide around
674 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
675 Geom::Point const &p,
676 Geom::Point const &guide_normal) const
677 {
678 /* Get a list of all the SPItems that we will try to snap to */
679 std::vector<SPItem*> cand;
680 std::vector<SPItem const *> const it; //just an empty list
682 DimensionToSnap snap_dim;
683 if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
684 snap_dim = GUIDE_TRANSL_SNAP_Y;
685 } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
686 snap_dim = GUIDE_TRANSL_SNAP_X;
687 } else {
688 snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
689 }
691 // We don't support ANGLED_GUIDE_ROT_SNAP yet.
693 // It would be cool to allow the user to rotate a guide by dragging it, instead of
694 // only translating it. (For example when CTRL is pressed). We will need an UI part
695 // for that first; and some important usability choices need to be made:
696 // E.g. which point should be used for pivoting? A previously snapped point,
697 // or a transformation center (which can be moved after clicking for the
698 // second time on an object; but should this point then be constrained to the
699 // line, or can it be located anywhere?)
701 _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
702 _snapTranslatingGuideToNodes(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, guide_normal);
703 // _snapRotatingGuideToNodes has not been implemented yet.
704 }
706 /**
707 * \return true if this Snapper will snap at least one kind of point.
708 */
709 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
710 {
711 bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
712 || _snapmanager->snapprefs.getSnapToItemNode()
713 || _snapmanager->snapprefs.getSnapToBBoxPath()
714 || _snapmanager->snapprefs.getSnapToBBoxNode()
715 || _snapmanager->snapprefs.getSnapToPageBorder()
716 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
717 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
718 || _snapmanager->snapprefs.getIncludeItemCenter();
720 return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
721 }
723 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
724 {
725 bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapToBBoxNode();
726 return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
727 }
729 void Inkscape::ObjectSnapper::_clear_paths() const
730 {
731 for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
732 g_free(k->first);
733 }
734 _paths_to_snap_to->clear();
735 }
737 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
738 {
739 Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
740 return _getPathvFromRect(border_rect);
741 }
743 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
744 {
745 SPCurve const *border_curve = SPCurve::new_from_rect(rect);
746 if (border_curve) {
747 Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
748 return dummy;
749 } else {
750 return NULL;
751 }
752 }
754 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<std::pair<Geom::Point, int> > *points) const
755 {
756 Geom::Coord w = sp_document_width(_snapmanager->getDocument());
757 Geom::Coord h = sp_document_height(_snapmanager->getDocument());
758 points->push_back(std::make_pair(Geom::Point(0,0), SNAPTARGET_PAGE_CORNER));
759 points->push_back(std::make_pair(Geom::Point(0,h), SNAPTARGET_PAGE_CORNER));
760 points->push_back(std::make_pair(Geom::Point(w,h), SNAPTARGET_PAGE_CORNER));
761 points->push_back(std::make_pair(Geom::Point(w,0), SNAPTARGET_PAGE_CORNER));
762 }
764 void Inkscape::getBBoxPoints(Geom::OptRect const bbox, std::vector<std::pair<Geom::Point, int> > *points, bool const isTarget, bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints)
765 {
766 if (bbox) {
767 // collect the corners of the bounding box
768 for ( unsigned k = 0 ; k < 4 ; k++ ) {
769 if (includeCorners) {
770 points->push_back(std::make_pair((bbox->corner(k)), isTarget ? int(Inkscape::SNAPTARGET_BBOX_CORNER) : int(Inkscape::SNAPSOURCE_BBOX_CORNER)));
771 }
772 // optionally, collect the midpoints of the bounding box's edges too
773 if (includeLineMidpoints) {
774 points->push_back(std::make_pair((bbox->corner(k) + bbox->corner((k+1) % 4))/2, isTarget ? int(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT) : int(Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT)));
775 }
776 }
777 if (includeObjectMidpoints) {
778 points->push_back(std::make_pair(bbox->midpoint(), isTarget ? int(Inkscape::SNAPTARGET_BBOX_MIDPOINT) : int(Inkscape::SNAPSOURCE_BBOX_MIDPOINT)));
779 }
780 }
781 }
783 /*
784 Local Variables:
785 mode:c++
786 c-file-style:"stroustrup"
787 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
788 indent-tabs-mode:nil
789 fill-column:99
790 End:
791 */
792 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :