1 #define __SP_DESKTOP_SNAP_C__
3 /**
4 * \file snap.cpp
5 * \brief SnapManager class.
6 *
7 * Authors:
8 * Lauris Kaplinski <lauris@kaplinski.com>
9 * Frank Felfe <innerspace@iname.com>
10 * Nathan Hurst <njh@njhurst.com>
11 * Carl Hetherington <inkscape@carlh.net>
12 * Diederik van Lierop <mail@diedenrezi.nl>
13 *
14 * Copyright (C) 2006-2007 Johan Engelen <johan@shouraizou.nl>
15 * Copyrigth (C) 2004 Nathan Hurst
16 * Copyright (C) 1999-2010 Authors
17 *
18 * Released under GNU GPL, read the file 'COPYING' for more information
19 */
21 #include <utility>
23 #include "sp-namedview.h"
24 #include "snap.h"
25 #include "snapped-line.h"
26 #include "snapped-curve.h"
28 #include "display/canvas-grid.h"
29 #include "display/snap-indicator.h"
31 #include "inkscape.h"
32 #include "desktop.h"
33 #include "selection.h"
34 #include "sp-guide.h"
35 #include "preferences.h"
36 #include "event-context.h"
37 using std::vector;
39 /**
40 * Construct a SnapManager for a SPNamedView.
41 *
42 * \param v `Owning' SPNamedView.
43 */
45 SnapManager::SnapManager(SPNamedView const *v) :
46 guide(this, 0),
47 object(this, 0),
48 snapprefs(),
49 _named_view(v)
50 {
51 }
53 /**
54 * \brief Return a list of snappers
55 *
56 * Inkscape snaps to objects, grids, and guides. For each of these snap targets a
57 * separate class is used, which has been derived from the base Snapper class. The
58 * getSnappers() method returns a list of pointers to instances of this class. This
59 * list contains exactly one instance of the guide snapper and of the object snapper
60 * class, but any number of grid snappers (because each grid has its own snapper
61 * instance)
62 *
63 * \return List of snappers that we use.
64 */
65 SnapManager::SnapperList
66 SnapManager::getSnappers() const
67 {
68 SnapManager::SnapperList s;
69 s.push_back(&guide);
70 s.push_back(&object);
72 SnapManager::SnapperList gs = getGridSnappers();
73 s.splice(s.begin(), gs);
75 return s;
76 }
78 /**
79 * \brief Return a list of gridsnappers
80 *
81 * Each grid has its own instance of the snapper class. This way snapping can
82 * be enabled per grid individually. A list will be returned containing the
83 * pointers to these instances, but only for grids that are being displayed
84 * and for which snapping is enabled.
85 *
86 * \return List of gridsnappers that we use.
87 */
88 SnapManager::SnapperList
89 SnapManager::getGridSnappers() const
90 {
91 SnapperList s;
92 if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
93 for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
94 Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
95 s.push_back(grid->snapper);
96 }
97 }
99 return s;
100 }
102 /**
103 * \brief Return true if any snapping might occur, whether its to grids, guides or objects
104 *
105 * Each snapper instance handles its own snapping target, e.g. grids, guides or
106 * objects. This method iterates through all these snapper instances and returns
107 * true if any of the snappers might possible snap, considering only the relevant
108 * snapping preferences.
109 *
110 * \return true if one of the snappers will try to snap to something.
111 */
113 bool SnapManager::someSnapperMightSnap() const
114 {
115 if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
116 return false;
117 }
119 SnapperList const s = getSnappers();
120 SnapperList::const_iterator i = s.begin();
121 while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
122 i++;
123 }
125 return (i != s.end());
126 }
128 /**
129 * \return true if one of the grids might be snapped to.
130 */
132 bool SnapManager::gridSnapperMightSnap() const
133 {
134 if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
135 return false;
136 }
138 SnapperList const s = getGridSnappers();
139 SnapperList::const_iterator i = s.begin();
140 while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
141 i++;
142 }
144 return (i != s.end());
145 }
147 /**
148 * \brief Try to snap a point to grids, guides or objects.
149 *
150 * Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
151 * i.e. snap in any direction on the two dimensional canvas to the nearest
152 * snap target. freeSnapReturnByRef() is equal in snapping behavior to
153 * freeSnap(), but the former returns the snapped point trough the referenced
154 * parameter p. This parameter p initially contains the position of the snap
155 * source and will we overwritten by the target position if snapping has occurred.
156 * This makes snapping transparent to the calling code. If this is not desired
157 * because either the calling code must know whether snapping has occurred, or
158 * because the original position should not be touched, then freeSnap() should be
159 * called instead.
160 *
161 * PS:
162 * 1) SnapManager::setup() must have been called before calling this method,
163 * but only once for a set of points
164 * 2) Only to be used when a single source point is to be snapped; it assumes
165 * that source_num = 0, which is inefficient when snapping sets our source points
166 *
167 * \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
168 * \param source_type Detailed description of the source type, will be used by the snap indicator
169 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
170 */
172 void SnapManager::freeSnapReturnByRef(Geom::Point &p,
173 Inkscape::SnapSourceType const source_type,
174 Geom::OptRect const &bbox_to_snap) const
175 {
176 Inkscape::SnappedPoint const s = freeSnap(Inkscape::SnapCandidatePoint(p, source_type), bbox_to_snap);
177 s.getPoint(p);
178 }
181 /**
182 * \brief Try to snap a point to grids, guides or objects.
183 *
184 * Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
185 * i.e. snap in any direction on the two dimensional canvas to the nearest
186 * snap target. freeSnap() is equal in snapping behavior to
187 * freeSnapReturnByRef(). Please read the comments of the latter for more details
188 *
189 * PS: SnapManager::setup() must have been called before calling this method,
190 * but only once for a set of points
191 *
192 * \param p Source point to be snapped
193 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
194 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
195 */
198 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapCandidatePoint const &p,
199 Geom::OptRect const &bbox_to_snap) const
200 {
201 if (!someSnapperMightSnap()) {
202 return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false, false);
203 }
205 SnappedConstraints sc;
206 SnapperList const snappers = getSnappers();
208 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
209 (*i)->freeSnap(sc, p, bbox_to_snap, &_items_to_ignore, _unselected_nodes);
210 }
212 return findBestSnap(p, sc, false);
213 }
215 void SnapManager::preSnap(Inkscape::SnapCandidatePoint const &p)
216 {
217 // setup() must have been called before calling this method!
219 if (_snapindicator) {
220 _snapindicator = false; // prevent other methods from drawing a snap indicator; we want to control this here
221 Inkscape::SnappedPoint s = freeSnap(p);
222 if (s.getSnapped()) {
223 _desktop->snapindicator->set_new_snaptarget(s, true);
224 } else {
225 _desktop->snapindicator->remove_snaptarget(true);
226 }
227 _snapindicator = true; // restore the original value
228 }
229 }
231 /**
232 * \brief Snap to the closest multiple of a grid pitch
233 *
234 * When pasting, we would like to snap to the grid. Problem is that we don't know which
235 * nodes were aligned to the grid at the time of copying, so we don't know which nodes
236 * to snap. If we'd snap an unaligned node to the grid, previously aligned nodes would
237 * become unaligned. That's undesirable. Instead we will make sure that the offset
238 * between the source and its pasted copy is a multiple of the grid pitch. If the source
239 * was aligned, then the copy will therefore also be aligned.
240 *
241 * PS: Whether we really find a multiple also depends on the snapping range! Most users
242 * will have "always snap" enabled though, in which case a multiple will always be found.
243 * PS2: When multiple grids are present then the result will become ambiguous. There is no
244 * way to control to which grid this method will snap.
245 *
246 * \param t Vector that represents the offset of the pasted copy with respect to the original
247 * \return Offset vector after snapping to the closest multiple of a grid pitch
248 */
250 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point const &origin)
251 {
252 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally())
253 return t;
255 if (_desktop && _desktop->gridsEnabled()) {
256 bool success = false;
257 Geom::Point nearest_multiple;
258 Geom::Coord nearest_distance = NR_HUGE;
259 Inkscape::SnappedPoint bestSnappedPoint(t);
261 // It will snap to the grid for which we find the closest snap. This might be a different
262 // grid than to which the objects were initially aligned. I don't see an easy way to fix
263 // this, so when using multiple grids one can get unexpected results
265 // Cannot use getGridSnappers() because we need both the grids AND their snappers
266 // Therefore we iterate through all grids manually
267 for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
268 Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
269 const Inkscape::Snapper* snapper = grid->snapper;
270 if (snapper && snapper->ThisSnapperMightSnap()) {
271 // To find the nearest multiple of the grid pitch for a given translation t, we
272 // will use the grid snapper. Simply snapping the value t to the grid will do, but
273 // only if the origin of the grid is at (0,0). If it's not then compensate for this
274 // in the translation t
275 Geom::Point const t_offset = t + grid->origin;
276 SnappedConstraints sc;
277 // Only the first three parameters are being used for grid snappers
278 snapper->freeSnap(sc, Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH),Geom::OptRect(), NULL, NULL);
279 // Find the best snap for this grid, including intersections of the grid-lines
280 bool old_val = _snapindicator;
281 _snapindicator = false;
282 Inkscape::SnappedPoint s = findBestSnap(Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), sc, false, false, true);
283 _snapindicator = old_val;
284 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
285 // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
286 // doesn't tell us anything about which node to snap
287 success = true;
288 nearest_multiple = s.getPoint() - to_2geom(grid->origin);
289 nearest_distance = s.getSnapDistance();
290 bestSnappedPoint = s;
291 }
292 }
293 }
295 if (success) {
296 bestSnappedPoint.setPoint(origin + nearest_multiple);
297 _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
298 return nearest_multiple;
299 }
300 }
302 return t;
303 }
305 /**
306 * \brief Try to snap a point along a constraint line to grids, guides or objects.
307 *
308 * Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
309 * i.e. snap in a specific direction on the two dimensional canvas to the nearest
310 * snap target.
311 *
312 * constrainedSnapReturnByRef() is equal in snapping behavior to
313 * constrainedSnap(), but the former returns the snapped point trough the referenced
314 * parameter p. This parameter p initially contains the position of the snap
315 * source and will we overwritten by the target position if snapping has occurred.
316 * This makes snapping transparent to the calling code. If this is not desired
317 * because either the calling code must know whether snapping has occurred, or
318 * because the original position should not be touched, then constrainedSnap() should
319 * be called instead.
320 *
321 * PS:
322 * 1) SnapManager::setup() must have been called before calling this method,
323 * but only once for a set of points
324 * 2) Only to be used when a single source point is to be snapped; it assumes
325 * that source_num = 0, which is inefficient when snapping sets our source points
327 *
328 * \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
329 * \param source_type Detailed description of the source type, will be used by the snap indicator
330 * \param constraint The direction or line along which snapping must occur
331 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
332 */
334 void SnapManager::constrainedSnapReturnByRef(Geom::Point &p,
335 Inkscape::SnapSourceType const source_type,
336 Inkscape::Snapper::SnapConstraint const &constraint,
337 Geom::OptRect const &bbox_to_snap) const
338 {
339 Inkscape::SnappedPoint const s = constrainedSnap(Inkscape::SnapCandidatePoint(p, source_type, 0), constraint, bbox_to_snap);
340 s.getPoint(p);
341 }
343 /**
344 * \brief Try to snap a point along a constraint line to grids, guides or objects.
345 *
346 * Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
347 * i.e. snap in a specific direction on the two dimensional canvas to the nearest
348 * snap target. constrainedSnap is equal in snapping behavior to
349 * constrainedSnapReturnByRef(). Please read the comments of the latter for more details.
350 *
351 * PS: SnapManager::setup() must have been called before calling this method,
352 * but only once for a set of points
353 *
354 * \param p Source point to be snapped
355 * \param constraint The direction or line along which snapping must occur
356 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
357 */
359 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint const &p,
360 Inkscape::Snapper::SnapConstraint const &constraint,
361 Geom::OptRect const &bbox_to_snap) const
362 {
363 // First project the mouse pointer onto the constraint
364 Geom::Point pp = constraint.projection(p.getPoint());
366 Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(pp, p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
368 if (!someSnapperMightSnap()) {
369 // Always return point on constraint
370 return no_snap;
371 }
373 SnappedConstraints sc;
374 SnapperList const snappers = getSnappers();
375 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
376 (*i)->constrainedSnap(sc, p, bbox_to_snap, constraint, &_items_to_ignore, _unselected_nodes);
377 }
379 Inkscape::SnappedPoint result = findBestSnap(p, sc, true);
381 if (result.getSnapped()) {
382 // only change the snap indicator if we really snapped to something
383 if (_snapindicator) {
384 _desktop->snapindicator->set_new_snaptarget(result);
385 }
386 return result;
387 }
388 return no_snap;
389 }
391 /* See the documentation for constrainedSnap() directly above for more details.
392 * The difference is that multipleConstrainedSnaps() will take a list of constraints instead of a single one,
393 * and will try to snap the SnapCandidatePoint to all of the provided constraints and see which one fits best
394 * \param p Source point to be snapped
395 * \param constraints List of directions or lines along which snapping must occur
396 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
397 */
400 Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandidatePoint const &p,
401 std::vector<Inkscape::Snapper::SnapConstraint> const &constraints,
402 Geom::OptRect const &bbox_to_snap) const
403 {
405 Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(p.getPoint(), p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
406 if (constraints.size() == 0) {
407 return no_snap;
408 }
410 SnappedConstraints sc;
411 SnapperList const snappers = getSnappers();
412 std::vector<Geom::Point> projections;
413 bool snapping_is_futile = !someSnapperMightSnap();
415 // Iterate over the constraints
416 for (std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); c != constraints.end(); c++) {
417 // Project the mouse pointer onto the constraint; In case we don't snap then we will
418 // return the projection onto the constraint, such that the constraint is always enforced
419 Geom::Point pp = (*c).projection(p.getPoint());
420 projections.push_back(pp);
421 // Try to snap to the constraint
422 if (!snapping_is_futile) {
423 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
424 (*i)->constrainedSnap(sc, p, bbox_to_snap, *c, &_items_to_ignore,_unselected_nodes);
425 }
426 }
427 }
429 Inkscape::SnappedPoint result = findBestSnap(p, sc, true);
431 if (result.getSnapped()) {
432 // only change the snap indicator if we really snapped to something
433 if (_snapindicator) {
434 _desktop->snapindicator->set_new_snaptarget(result);
435 }
436 return result;
437 }
439 // So we didn't snap, but we still need to return a point on one of the constraints
440 // Find out which of the constraints yielded the closest projection of point p
441 no_snap.setPoint(projections.front());
442 for (std::vector<Geom::Point>::iterator pp = projections.begin(); pp != projections.end(); pp++) {
443 if (pp != projections.begin()) {
444 if (Geom::L2(*pp - p.getPoint()) < Geom::L2(no_snap.getPoint() - p.getPoint())) {
445 no_snap.setPoint(*pp);
446 }
447 }
448 }
450 return no_snap;
451 }
453 /**
454 * \brief Try to snap a point of a guide to another guide or to a node
455 *
456 * Try to snap a point of a guide to another guide or to a node in two degrees-
457 * of-freedom, i.e. snap in any direction on the two dimensional canvas to the
458 * nearest snap target. This method is used when dragging or rotating a guide
459 *
460 * PS: SnapManager::setup() must have been called before calling this method,
461 *
462 * \param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred
463 * \param guide_normal Vector normal to the guide line
464 */
465 void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point const &guide_normal, SPGuideDragType drag_type) const
466 {
467 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
468 return;
469 }
471 if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
472 return;
473 }
475 Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN);
476 if (drag_type == SP_DRAG_ROTATE) {
477 candidate = Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_GUIDE);
478 }
480 // Snap to nodes
481 SnappedConstraints sc;
482 if (object.ThisSnapperMightSnap()) {
483 object.guideFreeSnap(sc, p, guide_normal);
484 }
486 // Snap to guides & grid lines
487 SnapperList snappers = getGridSnappers();
488 snappers.push_back(&guide);
489 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
490 (*i)->freeSnap(sc, candidate, Geom::OptRect(), NULL, NULL);
491 }
493 Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false, false);
495 s.getPoint(p);
496 }
498 /**
499 * \brief Try to snap a point on a guide to the intersection with another guide or a path
500 *
501 * Try to snap a point on a guide to the intersection of that guide with another
502 * guide or with a path. The snapped point will lie somewhere on the guide-line,
503 * making this is a constrained snap, i.e. in only one degree-of-freedom.
504 * This method is used when dragging the origin of the guide along the guide itself.
505 *
506 * PS: SnapManager::setup() must have been called before calling this method,
507 *
508 * \param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred
509 * \param guide_normal Vector normal to the guide line
510 */
512 void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const
513 {
514 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
515 return;
516 }
518 if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
519 return;
520 }
522 Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN, Inkscape::SNAPTARGET_UNDEFINED);
524 // Snap to nodes or paths
525 SnappedConstraints sc;
526 Inkscape::Snapper::SnapConstraint cl(guideline.point_on_line, Geom::rot90(guideline.normal_to_line));
527 if (object.ThisSnapperMightSnap()) {
528 object.constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL, NULL);
529 }
531 // Snap to guides & grid lines
532 SnapperList snappers = getGridSnappers();
533 snappers.push_back(&guide);
534 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
535 (*i)->constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL, NULL);
536 }
538 Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false);
539 s.getPoint(p);
540 }
542 /**
543 * \brief Method for snapping sets of points while they are being transformed
544 *
545 * Method for snapping sets of points while they are being transformed, when using
546 * for example the selector tool. This method is for internal use only, and should
547 * not have to be called directly. Use freeSnapTransalation(), constrainedSnapScale(),
548 * etc. instead.
549 *
550 * This is what is being done in this method: transform each point, find out whether
551 * a free snap or constrained snap is more appropriate, do the snapping, calculate
552 * some metrics to quantify the snap "distance", and see if it's better than the
553 * previous snap. Finally, the best ("nearest") snap from all these points is returned.
554 *
555 * \param points Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
556 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
557 * \param constrained true if the snap is constrained, e.g. for stretching or for purely horizontal translation.
558 * \param constraint The direction or line along which snapping must occur, if 'constrained' is true; otherwise undefined.
559 * \param transformation_type Type of transformation to apply to points before trying to snap them.
560 * \param transformation Description of the transformation; details depend on the type.
561 * \param origin Origin of the transformation, if applicable.
562 * \param dim Dimension to which the transformation applies, if applicable.
563 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
564 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
565 */
567 Inkscape::SnappedPoint SnapManager::_snapTransformed(
568 std::vector<Inkscape::SnapCandidatePoint> const &points,
569 Geom::Point const &pointer,
570 bool constrained,
571 Inkscape::Snapper::SnapConstraint const &constraint,
572 Transformation transformation_type,
573 Geom::Point const &transformation,
574 Geom::Point const &origin,
575 Geom::Dim2 dim,
576 bool uniform) const
577 {
578 /* We have a list of points, which we are proposing to transform in some way. We need to see
579 ** if any of these points, when transformed, snap to anything. If they do, we return the
580 ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
581 */
583 /* Quick check to see if we have any snappers that are enabled
584 ** Also used to globally disable all snapping
585 */
586 if (someSnapperMightSnap() == false || points.size() == 0) {
587 return Inkscape::SnappedPoint(pointer);
588 }
590 std::vector<Inkscape::SnapCandidatePoint> transformed_points;
591 Geom::Rect bbox;
593 long source_num = 0;
594 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
596 /* Work out the transformed version of this point */
597 Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
599 // add the current transformed point to the box hulling all transformed points
600 if (i == points.begin()) {
601 bbox = Geom::Rect(transformed, transformed);
602 } else {
603 bbox.expandTo(transformed);
604 }
606 transformed_points.push_back(Inkscape::SnapCandidatePoint(transformed, (*i).getSourceType(), source_num));
607 source_num++;
608 }
610 /* The current best transformation */
611 Geom::Point best_transformation = transformation;
613 /* The current best metric for the best transformation; lower is better, NR_HUGE
614 ** means that we haven't snapped anything.
615 */
616 Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
617 Inkscape::SnappedPoint best_snapped_point;
618 g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
619 g_assert(best_snapped_point.getAtIntersection() == false);
621 // Warnings for the devs
622 if (constrained && transformation_type == SCALE && !uniform) {
623 g_warning("Non-uniform constrained scaling is not supported!");
624 }
626 if (!constrained && transformation_type == ROTATE) {
627 // We do not yet allow for simultaneous rotation and scaling
628 g_warning("Unconstrained rotation is not supported!");
629 }
631 std::vector<Inkscape::SnapCandidatePoint>::iterator j = transformed_points.begin();
633 // std::cout << std::endl;
634 bool first_free_snap = true;
635 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
637 /* Snap it */
638 Inkscape::SnappedPoint snapped_point;
639 Inkscape::Snapper::SnapConstraint dedicated_constraint = constraint;
640 Geom::Point const b = ((*i).getPoint() - origin); // vector to original point (not the transformed point! required for rotations!)
642 if (constrained) {
643 if (((transformation_type == SCALE || transformation_type == STRETCH) && uniform)) {
644 // When uniformly scaling, each point will have its own unique constraint line,
645 // running from the scaling origin to the original untransformed point. We will
646 // calculate that line here
647 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b);
648 } else if (transformation_type == ROTATE) {
649 Geom::Coord r = Geom::L2(b); // the radius of the circular constraint
650 if (r < 1e-9) { // points too close to the rotation center will not move. Don't try to snap these
651 // as they will always yield a perfect snap result if they're already snapped beforehand (e.g.
652 // when the transformation center has been snapped to a grid intersection in the selector tool)
653 continue; // skip this SnapCandidate and continue with the next one
654 // PS1: Apparently we don't have to do this for skewing, but why?
655 // PS2: We cannot easily filter these points upstream, e.g. in the grab() method (seltrans.cpp)
656 // because the rotation center will change when pressing shift, and grab() won't be recalled.
657 // Filtering could be done in handleRequest() (again in seltrans.cpp), by iterating through
658 // the snap candidates. But hey, we're iterating here anyway.
659 }
660 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b, r);
661 } else if (transformation_type == STRETCH) { // when non-uniform stretching {
662 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), component_vectors[dim]);
663 } else if (transformation_type == TRANSLATE) {
664 // When doing a constrained translation, all points will move in the same direction, i.e.
665 // either horizontally or vertically. The lines along which they move are therefore all
666 // parallel, but might not be colinear. Therefore we will have to specify the point through
667 // which the constraint-line runs here, for each point individually. (we could also have done this
668 // earlier on, e.g. in seltrans.cpp but we're being lazy there and don't want to add an iteration loop)
669 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), constraint.getDirection());
670 } // else: leave the original constraint, e.g. for skewing
671 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
672 } else {
673 bool const c1 = fabs(b[Geom::X]) < 1e-6;
674 bool const c2 = fabs(b[Geom::Y]) < 1e-6;
675 if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
676 // When scaling, a point aligned either horizontally or vertically with the origin can only
677 // move in that specific direction; therefore it should only snap in that direction, otherwise
678 // we will get snapped points with an invalid transformation
679 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, component_vectors[c1]);
680 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
681 } else {
682 // If we have a collection of SnapCandidatePoints, with mixed constrained snapping and free snapping
683 // requirements, then freeSnap might never see the SnapCandidatePoint with source_num == 0. The freeSnap()
684 // method in the object snapper depends on this, because only for source-num == 0 the target nodes will
685 // be collected. Therefore we enforce that the first SnapCandidatePoint that is to be freeSnapped always
686 // has source_num == 0;
687 // TODO: This is a bit ugly so fix this; do we need sourcenum for anything else? if we don't then get rid
688 // of it and explicitely communicate to the object snapper that this is a first point
689 if (first_free_snap) {
690 (*j).setSourceNum(0);
691 first_free_snap = false;
692 }
693 snapped_point = freeSnap(*j, bbox);
694 }
695 }
696 // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
697 snapped_point.setPointerDistance(Geom::L2(pointer - (*i).getPoint()));
699 Geom::Point result;
701 if (snapped_point.getSnapped()) {
702 /* We snapped. Find the transformation that describes where the snapped point has
703 ** ended up, and also the metric for this transformation.
704 */
705 Geom::Point const a = snapped_point.getPoint() - origin; // vector to snapped point
706 //Geom::Point const b = (*i - origin); // vector to original point
708 switch (transformation_type) {
709 case TRANSLATE:
710 result = snapped_point.getPoint() - (*i).getPoint();
711 /* Consider the case in which a box is almost aligned with a grid in both
712 * horizontal and vertical directions. The distance to the intersection of
713 * the grid lines will always be larger then the distance to a single grid
714 * line. If we prefer snapping to an intersection instead of to a single
715 * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
716 * snapped distance will be used as a metric. Please note that the snapped
717 * distance is defined as the distance to the nearest line of the intersection,
718 * and not to the intersection itself!
719 */
720 // Only for translations, the relevant metric will be the real snapped distance,
721 // so we don't have to do anything special here
722 break;
723 case SCALE:
724 {
725 result = Geom::Point(NR_HUGE, NR_HUGE);
726 // If this point *i is horizontally or vertically aligned with
727 // the origin of the scaling, then it will scale purely in X or Y
728 // We can therefore only calculate the scaling in this direction
729 // and the scaling factor for the other direction should remain
730 // untouched (unless scaling is uniform of course)
731 for (int index = 0; index < 2; index++) {
732 if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
733 if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
734 result[index] = a[index] / b[index]; // then calculate it!
735 }
736 // we might leave result[1-index] = NR_HUGE
737 // if scaling didn't occur in the other direction
738 }
739 }
740 if (uniform) {
741 if (fabs(result[0]) < fabs(result[1])) {
742 result[1] = result[0];
743 } else {
744 result[0] = result[1];
745 }
746 }
747 // Compare the resulting scaling with the desired scaling
748 Geom::Point scale_metric = Geom::abs(result - transformation); // One or both of its components might be NR_HUGE
749 snapped_point.setSnapDistance(std::min(scale_metric[0], scale_metric[1]));
750 snapped_point.setSecondSnapDistance(std::max(scale_metric[0], scale_metric[1]));
751 break;
752 }
753 case STRETCH:
754 result = Geom::Point(NR_HUGE, NR_HUGE);
755 if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
756 result[dim] = a[dim] / b[dim];
757 result[1-dim] = uniform ? result[dim] : 1;
758 } else { // STRETCHING might occur for this point, but only when the stretching is uniform
759 if (uniform && fabs(b[1-dim]) > 1e-6) {
760 result[1-dim] = a[1-dim] / b[1-dim];
761 result[dim] = result[1-dim];
762 }
763 }
764 // Store the metric for this transformation as a virtual distance
765 snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
766 snapped_point.setSecondSnapDistance(NR_HUGE);
767 break;
768 case SKEW:
769 result[0] = (snapped_point.getPoint()[dim] - ((*i).getPoint())[dim]) / b[1 - dim]; // skew factor
770 result[1] = transformation[1]; // scale factor
771 // Store the metric for this transformation as a virtual distance
772 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
773 snapped_point.setSecondSnapDistance(NR_HUGE);
774 break;
775 case ROTATE:
776 // a is vector to snapped point; b is vector to original point; now lets calculate angle between a and b
777 result[0] = atan2(Geom::dot(Geom::rot90(b), a), Geom::dot(b, a));
778 result[1] = result[1]; // how else should we store an angle in a point ;-)
779 // Store the metric for this transformation as a virtual distance (we're storing an angle)
780 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
781 snapped_point.setSecondSnapDistance(NR_HUGE);
782 break;
783 default:
784 g_assert_not_reached();
785 }
787 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
788 best_transformation = result;
789 best_snapped_point = snapped_point;
790 }
791 }
793 j++;
794 }
796 Geom::Coord best_metric;
797 if (transformation_type == SCALE) {
798 // When scaling, don't ever exit with one of scaling components set to NR_HUGE
799 for (int index = 0; index < 2; index++) {
800 if (best_transformation[index] == NR_HUGE) {
801 if (uniform && best_transformation[1-index] < NR_HUGE) {
802 best_transformation[index] = best_transformation[1-index];
803 } else {
804 best_transformation[index] = transformation[index];
805 }
806 }
807 }
808 }
810 best_metric = best_snapped_point.getSnapDistance();
811 best_snapped_point.setTransformation(best_transformation);
812 // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
813 // These rounding errors might be caused by NRRects, see bug #1584301
814 best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
815 return best_snapped_point;
816 }
819 /**
820 * \brief Apply a translation to a set of points and try to snap freely in 2 degrees-of-freedom
821 *
822 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
823 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
824 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred
825 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
826 */
828 Inkscape::SnappedPoint SnapManager::freeSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
829 Geom::Point const &pointer,
830 Geom::Point const &tr) const
831 {
832 if (p.size() == 1) {
833 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
834 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
835 }
839 return _snapTransformed(p, pointer, false, Geom::Point(0,0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
840 }
842 /**
843 * \brief Apply a translation to a set of points and try to snap along a constraint
844 *
845 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
846 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
847 * \param constraint The direction or line along which snapping must occur.
848 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred.
849 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
850 */
852 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
853 Geom::Point const &pointer,
854 Inkscape::Snapper::SnapConstraint const &constraint,
855 Geom::Point const &tr) const
856 {
857 if (p.size() == 1) {
858 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
859 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
860 }
862 return _snapTransformed(p, pointer, true, constraint, TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
863 }
866 /**
867 * \brief Apply a scaling to a set of points and try to snap freely in 2 degrees-of-freedom
868 *
869 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
870 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
871 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
872 * \param o Origin of the scaling
873 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
874 */
876 Inkscape::SnappedPoint SnapManager::freeSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
877 Geom::Point const &pointer,
878 Geom::Scale const &s,
879 Geom::Point const &o) const
880 {
881 if (p.size() == 1) {
882 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
883 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
884 }
886 return _snapTransformed(p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
887 }
890 /**
891 * \brief Apply a scaling to a set of points and snap such that the aspect ratio of the selection is preserved
892 *
893 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
894 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
895 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
896 * \param o Origin of the scaling
897 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
898 */
900 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
901 Geom::Point const &pointer,
902 Geom::Scale const &s,
903 Geom::Point const &o) const
904 {
905 // When constrained scaling, only uniform scaling is supported.
906 if (p.size() == 1) {
907 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
908 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
909 }
911 return _snapTransformed(p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
912 }
914 /**
915 * \brief Apply a stretch to a set of points and snap such that the direction of the stretch is preserved
916 *
917 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
918 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
919 * \param s Proposed stretch; the final stretch can only be calculated after snapping has occurred
920 * \param o Origin of the stretching
921 * \param d Dimension in which to apply proposed stretch.
922 * \param u true if the stretch should be uniform (i.e. to be applied equally in both dimensions)
923 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
924 */
926 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(std::vector<Inkscape::SnapCandidatePoint> const &p,
927 Geom::Point const &pointer,
928 Geom::Coord const &s,
929 Geom::Point const &o,
930 Geom::Dim2 d,
931 bool u) const
932 {
933 if (p.size() == 1) {
934 Geom::Point pt = _transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u);
935 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
936 }
938 return _snapTransformed(p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
939 }
941 /**
942 * \brief Apply a skew to a set of points and snap such that the direction of the skew is preserved
943 *
944 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
945 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
946 * \param constraint The direction or line along which snapping must occur.
947 * \param s Proposed skew; the final skew can only be calculated after snapping has occurred
948 * \param o Origin of the proposed skew
949 * \param d Dimension in which to apply proposed skew.
950 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
951 */
953 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(std::vector<Inkscape::SnapCandidatePoint> const &p,
954 Geom::Point const &pointer,
955 Inkscape::Snapper::SnapConstraint const &constraint,
956 Geom::Point const &s,
957 Geom::Point const &o,
958 Geom::Dim2 d) const
959 {
960 // "s" contains skew factor in s[0], and scale factor in s[1]
962 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
963 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
964 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
965 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
966 // of bounding boxes is not allowed here.
967 if (p.size() > 0) {
968 g_assert(!(p.at(0).getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY));
969 }
971 if (p.size() == 1) {
972 Geom::Point pt = _transformPoint(p.at(0), SKEW, s, o, d, false);
973 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
974 }
976 return _snapTransformed(p, pointer, true, constraint, SKEW, s, o, d, false);
977 }
979 /**
980 * \brief Apply a rotation to a set of points and snap, without scaling
981 *
982 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
983 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
984 * \param angle Proposed rotation (in radians); the final rotation can only be calculated after snapping has occurred
985 * \param o Origin of the rotation
986 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
987 */
989 Inkscape::SnappedPoint SnapManager::constrainedSnapRotate(std::vector<Inkscape::SnapCandidatePoint> const &p,
990 Geom::Point const &pointer,
991 Geom::Coord const &angle,
992 Geom::Point const &o) const
993 {
994 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
995 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
996 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
997 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
998 // of bounding boxes is not allowed here.
1000 if (p.size() == 1) {
1001 Geom::Point pt = _transformPoint(p.at(0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1002 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1003 }
1005 return _snapTransformed(p, pointer, true, Geom::Point(0,0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1007 }
1009 /**
1010 * \brief Given a set of possible snap targets, find the best target (which is not necessarily
1011 * also the nearest target), and show the snap indicator if requested
1012 *
1013 * \param p Source point to be snapped
1014 * \param sc A structure holding all snap targets that have been found so far
1015 * \param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation.
1016 * \param noCurves If true, then do consider snapping to intersections of curves, but not to the curves themselves
1017 * \param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example when pasting to the grid)
1018 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
1019 */
1021 Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p,
1022 SnappedConstraints const &sc,
1023 bool constrained,
1024 bool noCurves,
1025 bool allowOffScreen) const
1026 {
1029 /*
1030 std::cout << "Type and number of snapped constraints: " << std::endl;
1031 std::cout << " Points : " << sc.points.size() << std::endl;
1032 std::cout << " Lines : " << sc.lines.size() << std::endl;
1033 std::cout << " Grid lines : " << sc.grid_lines.size()<< std::endl;
1034 std::cout << " Guide lines : " << sc.guide_lines.size()<< std::endl;
1035 std::cout << " Curves : " << sc.curves.size()<< std::endl;
1036 */
1038 // Store all snappoints
1039 std::list<Inkscape::SnappedPoint> sp_list;
1041 // search for the closest snapped point
1042 Inkscape::SnappedPoint closestPoint;
1043 if (getClosestSP(sc.points, closestPoint)) {
1044 sp_list.push_back(closestPoint);
1045 }
1047 // search for the closest snapped curve
1048 if (!noCurves) {
1049 Inkscape::SnappedCurve closestCurve;
1050 if (getClosestCurve(sc.curves, closestCurve)) {
1051 sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
1052 }
1053 }
1055 if (snapprefs.getSnapIntersectionCS()) {
1056 // search for the closest snapped intersection of curves
1057 Inkscape::SnappedPoint closestCurvesIntersection;
1058 if (getClosestIntersectionCS(sc.curves, p.getPoint(), closestCurvesIntersection, _desktop->dt2doc())) {
1059 closestCurvesIntersection.setSource(p.getSourceType());
1060 sp_list.push_back(closestCurvesIntersection);
1061 }
1062 }
1064 // search for the closest snapped grid line
1065 Inkscape::SnappedLine closestGridLine;
1066 if (getClosestSL(sc.grid_lines, closestGridLine)) {
1067 sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
1068 }
1070 // search for the closest snapped guide line
1071 Inkscape::SnappedLine closestGuideLine;
1072 if (getClosestSL(sc.guide_lines, closestGuideLine)) {
1073 sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
1074 }
1076 // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
1077 // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
1079 // When doing a constrained snap however, we're already at an intersection of the constrained line and
1080 // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
1081 // no need to look for additional intersections
1082 if (!constrained) {
1083 // search for the closest snapped intersection of grid lines
1084 Inkscape::SnappedPoint closestGridPoint;
1085 if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
1086 closestGridPoint.setSource(p.getSourceType());
1087 closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
1088 sp_list.push_back(closestGridPoint);
1089 }
1091 // search for the closest snapped intersection of guide lines
1092 Inkscape::SnappedPoint closestGuidePoint;
1093 if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
1094 closestGuidePoint.setSource(p.getSourceType());
1095 closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
1096 sp_list.push_back(closestGuidePoint);
1097 }
1099 // search for the closest snapped intersection of grid with guide lines
1100 if (snapprefs.getSnapIntersectionGG()) {
1101 Inkscape::SnappedPoint closestGridGuidePoint;
1102 if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
1103 closestGridGuidePoint.setSource(p.getSourceType());
1104 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
1105 sp_list.push_back(closestGridGuidePoint);
1106 }
1107 }
1108 }
1110 // now let's see which snapped point gets a thumbs up
1111 Inkscape::SnappedPoint bestSnappedPoint(p.getPoint());
1112 // std::cout << "Finding the best snap..." << std::endl;
1113 for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
1114 // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << (*i).getTarget();
1115 bool onScreen = _desktop->get_display_area().contains((*i).getPoint());
1116 if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen
1117 if ((*i).getSnapDistance() <= (*i).getTolerance()) { // Only snap to points within snapping range
1118 // if it's the first point, or if it is closer than the best snapped point so far
1119 if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
1120 // then prefer this point over the previous one
1121 bestSnappedPoint = *i;
1122 }
1123 }
1124 }
1125 // std::cout << std::endl;
1126 }
1128 // Update the snap indicator, if requested
1129 if (_snapindicator) {
1130 if (bestSnappedPoint.getSnapped()) {
1131 _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
1132 } else {
1133 _desktop->snapindicator->remove_snaptarget();
1134 }
1135 }
1137 // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
1138 return bestSnappedPoint;
1139 }
1141 /// Convenience shortcut when there is only one item to ignore
1142 void SnapManager::setup(SPDesktop const *desktop,
1143 bool snapindicator,
1144 SPItem const *item_to_ignore,
1145 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1146 SPGuide *guide_to_ignore)
1147 {
1148 g_assert(desktop != NULL);
1149 _items_to_ignore.clear();
1150 _items_to_ignore.push_back(item_to_ignore);
1151 _desktop = desktop;
1152 _snapindicator = snapindicator;
1153 _unselected_nodes = unselected_nodes;
1154 _guide_to_ignore = guide_to_ignore;
1155 _rotation_center_source_item = NULL;
1156 }
1158 /**
1159 * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1160 * to ignore and toggling the snap indicator
1161 *
1162 * There are two overloaded setup() methods, of which the other one only allows for a single item to be ignored
1163 * whereas this one will take a list of items to ignore
1164 *
1165 * \param desktop Reference to the desktop to which this snap manager is attached
1166 * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1167 * \param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping"
1168 * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1169 * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1170 * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1171 * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1172 */
1174 void SnapManager::setup(SPDesktop const *desktop,
1175 bool snapindicator,
1176 std::vector<SPItem const *> &items_to_ignore,
1177 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1178 SPGuide *guide_to_ignore)
1179 {
1180 g_assert(desktop != NULL);
1181 _items_to_ignore = items_to_ignore;
1182 _desktop = desktop;
1183 _snapindicator = snapindicator;
1184 _unselected_nodes = unselected_nodes;
1185 _guide_to_ignore = guide_to_ignore;
1186 _rotation_center_source_item = NULL;
1187 }
1189 /// Setup, taking the list of items to ignore from the desktop's selection.
1190 void SnapManager::setupIgnoreSelection(SPDesktop const *desktop,
1191 bool snapindicator,
1192 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1193 SPGuide *guide_to_ignore)
1194 {
1195 _desktop = desktop;
1196 _snapindicator = snapindicator;
1197 _unselected_nodes = unselected_nodes;
1198 _guide_to_ignore = guide_to_ignore;
1199 _rotation_center_source_item = NULL;
1200 _items_to_ignore.clear();
1202 Inkscape::Selection *sel = _desktop->selection;
1203 GSList const *items = sel->itemList();
1204 for (GSList *i = const_cast<GSList*>(items); i; i = i->next) {
1205 _items_to_ignore.push_back(static_cast<SPItem const *>(i->data));
1206 }
1207 }
1209 SPDocument *SnapManager::getDocument() const
1210 {
1211 return _named_view->document;
1212 }
1214 /**
1215 * \brief Takes an untransformed point, applies the given transformation, and returns the transformed point. Eliminates lots of duplicated code
1216 *
1217 * \param p The untransformed position of the point, paired with an identifier of the type of the snap source.
1218 * \param transformation_type Type of transformation to apply.
1219 * \param transformation Mathematical description of the transformation; details depend on the type.
1220 * \param origin Origin of the transformation, if applicable.
1221 * \param dim Dimension to which the transformation applies, if applicable.
1222 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
1223 * \return The position of the point after transformation
1224 */
1226 Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p,
1227 Transformation const transformation_type,
1228 Geom::Point const &transformation,
1229 Geom::Point const &origin,
1230 Geom::Dim2 const dim,
1231 bool const uniform) const
1232 {
1233 /* Work out the transformed version of this point */
1234 Geom::Point transformed;
1235 switch (transformation_type) {
1236 case TRANSLATE:
1237 transformed = p.getPoint() + transformation;
1238 break;
1239 case SCALE:
1240 transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
1241 break;
1242 case STRETCH:
1243 {
1244 Geom::Scale s(1, 1);
1245 if (uniform)
1246 s[Geom::X] = s[Geom::Y] = transformation[dim];
1247 else {
1248 s[dim] = transformation[dim];
1249 s[1 - dim] = 1;
1250 }
1251 transformed = ((p.getPoint() - origin) * s) + origin;
1252 break;
1253 }
1254 case SKEW:
1255 // Apply the skew factor
1256 transformed[dim] = (p.getPoint())[dim] + transformation[0] * ((p.getPoint())[1 - dim] - origin[1 - dim]);
1257 // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
1258 // Apply that scale factor here
1259 transformed[1-dim] = (p.getPoint() - origin)[1 - dim] * transformation[1] + origin[1 - dim];
1260 break;
1261 case ROTATE:
1262 // for rotations: transformation[0] stores the angle in radians
1263 transformed = (p.getPoint() - origin) * Geom::Rotate(transformation[0]) + origin;
1264 break;
1265 default:
1266 g_assert_not_reached();
1267 }
1269 return transformed;
1270 }
1272 /**
1273 * \brief Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol
1274 *
1275 * \param point_type Category of points to which the source point belongs: node, guide or bounding box
1276 * \param p The transformed position of the source point, paired with an identifier of the type of the snap source.
1277 */
1279 void SnapManager::_displaySnapsource(Inkscape::SnapCandidatePoint const &p) const {
1281 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1282 if (prefs->getBool("/options/snapclosestonly/value")) {
1283 bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
1284 bool p_is_a_bbox = p.getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
1285 bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
1287 if (snapprefs.getSnapEnabledGlobally() && (p_is_other || (p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
1288 _desktop->snapindicator->set_new_snapsource(p);
1289 } else {
1290 _desktop->snapindicator->remove_snapsource();
1291 }
1292 }
1293 }
1295 /*
1296 Local Variables:
1297 mode:c++
1298 c-file-style:"stroustrup"
1299 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1300 indent-tabs-mode:nil
1301 fill-column:99
1302 End:
1303 */
1304 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :