Code

79f398cc54f77df6f4bea68633d4f4f17af384c5
[inkscape.git] / src / snap.cpp
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 #include "util/mathfns.h"
38 using std::vector;
40 /**
41  *  Construct a SnapManager for a SPNamedView.
42  *
43  *  \param v `Owning' SPNamedView.
44  */
46 SnapManager::SnapManager(SPNamedView const *v) :
47     guide(this, 0),
48     object(this, 0),
49     snapprefs(),
50     _named_view(v),
51     _rotation_center_source_items(NULL),
52     _guide_to_ignore(NULL),
53     _desktop(NULL),
54     _unselected_nodes(NULL)
55 {
56 }
58 /**
59  *  \brief Return a list of snappers
60  *
61  *  Inkscape snaps to objects, grids, and guides. For each of these snap targets a
62  *  separate class is used, which has been derived from the base Snapper class. The
63  *  getSnappers() method returns a list of pointers to instances of this class. This
64  *  list contains exactly one instance of the guide snapper and of the object snapper
65  *  class, but any number of grid snappers (because each grid has its own snapper
66  *  instance)
67  *
68  *  \return List of snappers that we use.
69  */
70 SnapManager::SnapperList
71 SnapManager::getSnappers() const
72 {
73     SnapManager::SnapperList s;
74     s.push_back(&guide);
75     s.push_back(&object);
77     SnapManager::SnapperList gs = getGridSnappers();
78     s.splice(s.begin(), gs);
80     return s;
81 }
83 /**
84  *  \brief Return a list of gridsnappers
85  *
86  *  Each grid has its own instance of the snapper class. This way snapping can
87  *  be enabled per grid individually. A list will be returned containing the
88  *  pointers to these instances, but only for grids that are being displayed
89  *  and for which snapping is enabled.
90  *
91  *  \return List of gridsnappers that we use.
92  */
93 SnapManager::SnapperList
94 SnapManager::getGridSnappers() const
95 {
96     SnapperList s;
98     if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
99         for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
100             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
101             s.push_back(grid->snapper);
102         }
103     }
105     return s;
108 /**
109  * \brief Return true if any snapping might occur, whether its to grids, guides or objects
110  *
111  * Each snapper instance handles its own snapping target, e.g. grids, guides or
112  * objects. This method iterates through all these snapper instances and returns
113  * true if any of the snappers might possible snap, considering only the relevant
114  * snapping preferences.
115  *
116  * \return true if one of the snappers will try to snap to something.
117  */
119 bool SnapManager::someSnapperMightSnap() const
121     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
122         return false;
123     }
125     SnapperList const s = getSnappers();
126     SnapperList::const_iterator i = s.begin();
127     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
128         i++;
129     }
131     return (i != s.end());
134 /**
135  * \return true if one of the grids might be snapped to.
136  */
138 bool SnapManager::gridSnapperMightSnap() const
140     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
141         return false;
142     }
144     SnapperList const s = getGridSnappers();
145     SnapperList::const_iterator i = s.begin();
146     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
147         i++;
148     }
150     return (i != s.end());
153 /**
154  *  \brief Try to snap a point to grids, guides or objects.
155  *
156  *  Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
157  *  i.e. snap in any direction on the two dimensional canvas to the nearest
158  *  snap target. freeSnapReturnByRef() is equal in snapping behavior to
159  *  freeSnap(), but the former returns the snapped point trough the referenced
160  *  parameter p. This parameter p initially contains the position of the snap
161  *  source and will we overwritten by the target position if snapping has occurred.
162  *  This makes snapping transparent to the calling code. If this is not desired
163  *  because either the calling code must know whether snapping has occurred, or
164  *  because the original position should not be touched, then freeSnap() should be
165  *  called instead.
166  *
167  *  PS:
168  *  1) SnapManager::setup() must have been called before calling this method,
169  *  but only once for a set of points
170  *  2) Only to be used when a single source point is to be snapped; it assumes
171  *  that source_num = 0, which is inefficient when snapping sets our source points
172  *
173  *  \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
174  *  \param source_type Detailed description of the source type, will be used by the snap indicator
175  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
176  */
178 void SnapManager::freeSnapReturnByRef(Geom::Point &p,
179                                       Inkscape::SnapSourceType const source_type,
180                                       Geom::OptRect const &bbox_to_snap) const
182     Inkscape::SnappedPoint const s = freeSnap(Inkscape::SnapCandidatePoint(p, source_type), bbox_to_snap);
183     s.getPointIfSnapped(p);
187 /**
188  *  \brief Try to snap a point to grids, guides or objects.
189  *
190  *  Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
191  *  i.e. snap in any direction on the two dimensional canvas to the nearest
192  *  snap target. freeSnap() is equal in snapping behavior to
193  *  freeSnapReturnByRef(). Please read the comments of the latter for more details
194  *
195  *  PS: SnapManager::setup() must have been called before calling this method,
196  *  but only once for a set of points
197  *
198  *  \param p Source point to be snapped
199  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
200  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
201  */
204 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapCandidatePoint const &p,
205                                              Geom::OptRect const &bbox_to_snap) const
207     if (!someSnapperMightSnap()) {
208         return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false, false);
209     }
211     SnappedConstraints sc;
212     SnapperList const snappers = getSnappers();
214     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
215         (*i)->freeSnap(sc, p, bbox_to_snap, &_items_to_ignore, _unselected_nodes);
216     }
218     return findBestSnap(p, sc, false);
221 void SnapManager::preSnap(Inkscape::SnapCandidatePoint const &p)
223     // setup() must have been called before calling this method!
225     if (_snapindicator) {
226         _snapindicator = false; // prevent other methods from drawing a snap indicator; we want to control this here
227         Inkscape::SnappedPoint s = freeSnap(p);
228         g_assert(_desktop != NULL);
229         if (s.getSnapped()) {
230             _desktop->snapindicator->set_new_snaptarget(s, true);
231         } else {
232             _desktop->snapindicator->remove_snaptarget(true);
233         }
234         _snapindicator = true; // restore the original value
235     }
238 /**
239  * \brief Snap to the closest multiple of a grid pitch
240  *
241  * When pasting, we would like to snap to the grid. Problem is that we don't know which
242  * nodes were aligned to the grid at the time of copying, so we don't know which nodes
243  * to snap. If we'd snap an unaligned node to the grid, previously aligned nodes would
244  * become unaligned. That's undesirable. Instead we will make sure that the offset
245  * between the source and its pasted copy is a multiple of the grid pitch. If the source
246  * was aligned, then the copy will therefore also be aligned.
247  *
248  * PS: Whether we really find a multiple also depends on the snapping range! Most users
249  * will have "always snap" enabled though, in which case a multiple will always be found.
250  * PS2: When multiple grids are present then the result will become ambiguous. There is no
251  * way to control to which grid this method will snap.
252  *
253  * \param t Vector that represents the offset of the pasted copy with respect to the original
254  * \return Offset vector after snapping to the closest multiple of a grid pitch
255  */
257 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point const &origin)
259     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally())
260         return t;
262     if (_desktop && _desktop->gridsEnabled()) {
263         bool success = false;
264         Geom::Point nearest_multiple;
265         Geom::Coord nearest_distance = NR_HUGE;
266         Inkscape::SnappedPoint bestSnappedPoint(t);
268         // It will snap to the grid for which we find the closest snap. This might be a different
269         // grid than to which the objects were initially aligned. I don't see an easy way to fix
270         // this, so when using multiple grids one can get unexpected results
272         // Cannot use getGridSnappers() because we need both the grids AND their snappers
273         // Therefore we iterate through all grids manually
274         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
275             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
276             const Inkscape::Snapper* snapper = grid->snapper;
277             if (snapper && snapper->ThisSnapperMightSnap()) {
278                 // To find the nearest multiple of the grid pitch for a given translation t, we
279                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
280                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
281                 // in the translation t
282                 Geom::Point const t_offset = t + grid->origin;
283                 SnappedConstraints sc;
284                 // Only the first three parameters are being used for grid snappers
285                 snapper->freeSnap(sc, Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH),Geom::OptRect(), NULL, NULL);
286                 // Find the best snap for this grid, including intersections of the grid-lines
287                 bool old_val = _snapindicator;
288                 _snapindicator = false;
289                 Inkscape::SnappedPoint s = findBestSnap(Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), sc, false, false, true);
290                 _snapindicator = old_val;
291                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
292                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
293                     // doesn't tell us anything about which node to snap
294                     success = true;
295                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
296                     nearest_distance = s.getSnapDistance();
297                     bestSnappedPoint = s;
298                 }
299             }
300         }
302         if (success) {
303             bestSnappedPoint.setPoint(origin + nearest_multiple);
304             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
305             return nearest_multiple;
306         }
307     }
309     return t;
312 /**
313  *  \brief Try to snap a point along a constraint line to grids, guides or objects.
314  *
315  *  Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
316  *  i.e. snap in a specific direction on the two dimensional canvas to the nearest
317  *  snap target.
318  *
319  *  constrainedSnapReturnByRef() is equal in snapping behavior to
320  *  constrainedSnap(), but the former returns the snapped point trough the referenced
321  *  parameter p. This parameter p initially contains the position of the snap
322  *  source and will be overwritten by the target position if snapping has occurred.
323  *  This makes snapping transparent to the calling code. If this is not desired
324  *  because either the calling code must know whether snapping has occurred, or
325  *  because the original position should not be touched, then constrainedSnap() should
326  *  be called instead. If there's nothing to snap to or if snapping has been disabled,
327  *  then this method will still apply the constraint (but without snapping)
328  *
329  *  PS:
330  *  1) SnapManager::setup() must have been called before calling this method,
331  *  but only once for a set of points
332  *  2) Only to be used when a single source point is to be snapped; it assumes
333  *  that source_num = 0, which is inefficient when snapping sets our source points
335  *
336  *  \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
337  *  \param source_type Detailed description of the source type, will be used by the snap indicator
338  *  \param constraint The direction or line along which snapping must occur
339  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
340  */
342 void SnapManager::constrainedSnapReturnByRef(Geom::Point &p,
343                                              Inkscape::SnapSourceType const source_type,
344                                              Inkscape::Snapper::SnapConstraint const &constraint,
345                                              Geom::OptRect const &bbox_to_snap) const
347     Inkscape::SnappedPoint const s = constrainedSnap(Inkscape::SnapCandidatePoint(p, source_type), constraint, bbox_to_snap);
348     p = s.getPoint(); // If we didn't snap, then we will return the point projected onto the constraint
351 /**
352  *  \brief Try to snap a point along a constraint line to grids, guides or objects.
353  *
354  *  Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
355  *  i.e. snap in a specific direction on the two dimensional canvas to the nearest
356  *  snap target. constrainedSnap is equal in snapping behavior to
357  *  constrainedSnapReturnByRef(). Please read the comments of the latter for more details.
358  *
359  *  PS: SnapManager::setup() must have been called before calling this method,
360  *  but only once for a set of points
361  *  PS: If there's nothing to snap to or if snapping has been disabled, then this
362  *  method will still apply the constraint (but without snapping)
363  *
364  *  \param p Source point to be snapped
365  *  \param constraint The direction or line along which snapping must occur
366  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
367  */
369 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint const &p,
370                                                     Inkscape::Snapper::SnapConstraint const &constraint,
371                                                     Geom::OptRect const &bbox_to_snap) const
373     // First project the mouse pointer onto the constraint
374     Geom::Point pp = constraint.projection(p.getPoint());
376     Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(pp, p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
378     if (!someSnapperMightSnap()) {
379         // Always return point on constraint
380         return no_snap;
381     }
383     Inkscape::SnappedPoint result = no_snap;
385     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
386     if ((prefs->getBool("/options/snapmousepointer/value", false)) && p.isSingleHandle()) {
387         // Snapping the mouse pointer instead of the constrained position of the knot allows
388         // to snap to things which don't intersect with the constraint line; this is basically
389         // then just a freesnap with the constraint applied afterwards
390         // We'll only to this if we're dragging a single handle, and for example not when transforming an object in the selector tool
391         result = freeSnap(p, bbox_to_snap);
392         if (result.getSnapped()) {
393             // only change the snap indicator if we really snapped to something
394             if (_snapindicator && _desktop) {
395                 _desktop->snapindicator->set_new_snaptarget(result);
396             }
397             // Apply the constraint
398             result.setPoint(constraint.projection(result.getPoint()));
399             return result;
400         }
401         return no_snap;
402     }
404     SnappedConstraints sc;
405     SnapperList const snappers = getSnappers();
406     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
407         (*i)->constrainedSnap(sc, p, bbox_to_snap, constraint, &_items_to_ignore, _unselected_nodes);
408     }
410     result = findBestSnap(p, sc, true);
412     if (result.getSnapped()) {
413         // only change the snap indicator if we really snapped to something
414         if (_snapindicator && _desktop) {
415             _desktop->snapindicator->set_new_snaptarget(result);
416         }
417         return result;
418     }
419     return no_snap;
422 /* See the documentation for constrainedSnap() directly above for more details.
423  * The difference is that multipleConstrainedSnaps() will take a list of constraints instead of a single one,
424  * and will try to snap the SnapCandidatePoint to all of the provided constraints and see which one fits best
425  *  \param p Source point to be snapped
426  *  \param constraints List of directions or lines along which snapping must occur
427  *  \param dont_snap If true then we will only apply the constraint, without snapping
428  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
429  */
432 Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandidatePoint const &p,
433                                                     std::vector<Inkscape::Snapper::SnapConstraint> const &constraints,
434                                                     bool dont_snap,
435                                                     Geom::OptRect const &bbox_to_snap) const
438     Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(p.getPoint(), p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
439     if (constraints.size() == 0) {
440         return no_snap;
441     }
443     SnappedConstraints sc;
444     SnapperList const snappers = getSnappers();
445     std::vector<Geom::Point> projections;
446     bool snapping_is_futile = !someSnapperMightSnap() || dont_snap;
448     Inkscape::SnappedPoint result = no_snap;
450     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
451     bool snap_mouse = prefs->getBool("/options/snapmousepointer/value", false);
453     for (std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); c != constraints.end(); c++) {
454         // Project the mouse pointer onto the constraint; In case we don't snap then we will
455         // return the projection onto the constraint, such that the constraint is always enforced
456         Geom::Point pp = (*c).projection(p.getPoint());
457         projections.push_back(pp);
458     }
460     if (snap_mouse && p.isSingleHandle() && !dont_snap) {
461         // Snapping the mouse pointer instead of the constrained position of the knot allows
462         // to snap to things which don't intersect with the constraint line; this is basically
463         // then just a freesnap with the constraint applied afterwards
464         // We'll only to this if we're dragging a single handle, and for example not when transforming an object in the selector tool
465         result = freeSnap(p, bbox_to_snap);
466     } else {
467         // Iterate over the constraints
468         for (std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); c != constraints.end(); c++) {
469             // Try to snap to the constraint
470             if (!snapping_is_futile) {
471                 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
472                     (*i)->constrainedSnap(sc, p, bbox_to_snap, *c, &_items_to_ignore,_unselected_nodes);
473                 }
474             }
475         }
476         result = findBestSnap(p, sc, true);
477     }
479     if (result.getSnapped()) {
480         if (snap_mouse) {
481             // If "snap_mouse" then we still have to apply the constraint, because so far we only tried a freeSnap
482             Geom::Point result_closest;
483             for (std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); c != constraints.end(); c++) {
484                 // Project the mouse pointer onto the constraint; In case we don't snap then we will
485                 // return the projection onto the constraint, such that the constraint is always enforced
486                 Geom::Point result_p = (*c).projection(result.getPoint());
487                 if (c == constraints.begin() || (Geom::L2(result_p - p.getPoint()) < Geom::L2(result_closest - p.getPoint()))) {
488                     result_closest = result_p;
489                 }
490             }
491             result.setPoint(result_closest);
492         }
493         return result;
494     }
496     // So we didn't snap, but we still need to return a point on one of the constraints
497     // Find out which of the constraints yielded the closest projection of point p
498     for (std::vector<Geom::Point>::iterator pp = projections.begin(); pp != projections.end(); pp++) {
499         if (pp != projections.begin()) {
500             if (Geom::L2(*pp - p.getPoint()) < Geom::L2(no_snap.getPoint() - p.getPoint())) {
501                 no_snap.setPoint(*pp);
502             }
503         } else {
504             no_snap.setPoint(projections.front());
505         }
506     }
508     return no_snap;
511 /**
512  *  \brief Try to snap a point to something at a specific angle
513  *
514  *  When drawing a straight line or modifying a gradient, it will snap to specific angle increments
515  *  if CTRL is being pressed. This method will enforce this angular constraint (even if there is nothing
516  *  to snap to)
517  *
518  *  \param p Source point to be snapped
519  *  \param p_ref Optional original point, relative to which the angle should be calculated. If empty then
520  *  the angle will be calculated relative to the y-axis
521  *  \param snaps Number of angular increments per PI radians; E.g. if snaps = 2 then we will snap every PI/2 = 90 degrees
522  */
524 Inkscape::SnappedPoint SnapManager::constrainedAngularSnap(Inkscape::SnapCandidatePoint const &p,
525                                                             boost::optional<Geom::Point> const &p_ref,
526                                                             Geom::Point const &o,
527                                                             unsigned const snaps) const
529     Inkscape::SnappedPoint sp;
530     if (snaps > 0) { // 0 means no angular snapping
531         // p is at an arbitrary angle. Now we should snap this angle to specific increments.
532         // For this we'll calculate the closest two angles, one at each side of the current angle
533         Geom::Line y_axis(Geom::Point(0, 0), Geom::Point(0, 1));
534         Geom::Line p_line(o, p.getPoint());
535         double angle = Geom::angle_between(y_axis, p_line);
536         double angle_incr = M_PI / snaps;
537         double angle_offset = 0;
538         if (p_ref) {
539             Geom::Line p_line_ref(o, *p_ref);
540             angle_offset = Geom::angle_between(y_axis, p_line_ref);
541         }
542         double angle_ceil = round_to_upper_multiple_plus(angle, angle_incr, angle_offset);
543         double angle_floor = round_to_lower_multiple_plus(angle, angle_incr, angle_offset);
544         // We have two angles now. The constrained snapper will try each of them and return the closest
546         // Now do the snapping...
547         std::vector<Inkscape::Snapper::SnapConstraint> constraints;
548         constraints.push_back(Inkscape::Snapper::SnapConstraint(Geom::Line(o, angle_ceil - M_PI/2)));
549         constraints.push_back(Inkscape::Snapper::SnapConstraint(Geom::Line(o, angle_floor - M_PI/2)));
550         sp = multipleConstrainedSnaps(p, constraints); // Constraints will always be applied, even if we didn't snap
551         if (!sp.getSnapped()) { // If we haven't snapped then we only had the constraint applied;
552             sp.setTarget(Inkscape::SNAPTARGET_CONSTRAINED_ANGLE);
553         }
554     } else {
555         sp = freeSnap(p);
556     }
557     return sp;
560 /**
561  *  \brief Try to snap a point of a guide to another guide or to a node
562  *
563  *  Try to snap a point of a guide to another guide or to a node in two degrees-
564  *  of-freedom, i.e. snap in any direction on the two dimensional canvas to the
565  *  nearest snap target. This method is used when dragging or rotating a guide
566  *
567  *  PS: SnapManager::setup() must have been called before calling this method,
568  *
569  *  \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
570  *  \param guide_normal Vector normal to the guide line
571  */
572 void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point const &guide_normal, SPGuideDragType drag_type) const
574     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
575         return;
576     }
578     if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
579         return;
580     }
582     Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN);
583     if (drag_type == SP_DRAG_ROTATE) {
584         candidate = Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_GUIDE);
585     }
587     // Snap to nodes
588     SnappedConstraints sc;
589     if (object.ThisSnapperMightSnap()) {
590         object.guideFreeSnap(sc, p, guide_normal);
591     }
593     // Snap to guides & grid lines
594     SnapperList snappers = getGridSnappers();
595     snappers.push_back(&guide);
596     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
597         (*i)->freeSnap(sc, candidate, Geom::OptRect(), NULL, NULL);
598     }
600     Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false, false);
602     s.getPointIfSnapped(p);
605 /**
606  *  \brief Try to snap a point on a guide to the intersection with another guide or a path
607  *
608  *  Try to snap a point on a guide to the intersection of that guide with another
609  *  guide or with a path. The snapped point will lie somewhere on the guide-line,
610  *  making this is a constrained snap, i.e. in only one degree-of-freedom.
611  *  This method is used when dragging the origin of the guide along the guide itself.
612  *
613  *  PS: SnapManager::setup() must have been called before calling this method,
614  *
615  *  \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
616  *  \param guide_normal Vector normal to the guide line
617  */
619 void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const
621     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
622         return;
623     }
625     if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
626         return;
627     }
629     Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN, Inkscape::SNAPTARGET_UNDEFINED);
631     // Snap to nodes or paths
632     SnappedConstraints sc;
633     Inkscape::Snapper::SnapConstraint cl(guideline.point_on_line, Geom::rot90(guideline.normal_to_line));
634     if (object.ThisSnapperMightSnap()) {
635         object.constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL, NULL);
636     }
638     // Snap to guides & grid lines
639     SnapperList snappers = getGridSnappers();
640     snappers.push_back(&guide);
641     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
642         (*i)->constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL, NULL);
643     }
645     Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false);
646     s.getPointIfSnapped(p);
649 /**
650  *  \brief Method for snapping sets of points while they are being transformed
651  *
652  *  Method for snapping sets of points while they are being transformed, when using
653  *  for example the selector tool. This method is for internal use only, and should
654  *  not have to be called directly. Use freeSnapTransalation(), constrainedSnapScale(),
655  *  etc. instead.
656  *
657  *  This is what is being done in this method: transform each point, find out whether
658  *  a free snap or constrained snap is more appropriate, do the snapping, calculate
659  *  some metrics to quantify the snap "distance", and see if it's better than the
660  *  previous snap. Finally, the best ("nearest") snap from all these points is returned.
661  *  If no snap has occurred and we're asked for a constrained snap then the constraint
662  *  will be applied nevertheless
663  *
664  *  \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.
665  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
666  *  \param constrained true if the snap is constrained, e.g. for stretching or for purely horizontal translation.
667  *  \param constraint The direction or line along which snapping must occur, if 'constrained' is true; otherwise undefined.
668  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
669  *  \param transformation Description of the transformation; details depend on the type.
670  *  \param origin Origin of the transformation, if applicable.
671  *  \param dim Dimension to which the transformation applies, if applicable.
672  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
673  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
674  */
676 Inkscape::SnappedPoint SnapManager::_snapTransformed(
677     std::vector<Inkscape::SnapCandidatePoint> const &points,
678     Geom::Point const &pointer,
679     bool constrained,
680     Inkscape::Snapper::SnapConstraint const &constraint,
681     Transformation transformation_type,
682     Geom::Point const &transformation,
683     Geom::Point const &origin,
684     Geom::Dim2 dim,
685     bool uniform) const
687     /* We have a list of points, which we are proposing to transform in some way.  We need to see
688     ** if any of these points, when transformed, snap to anything.  If they do, we return the
689     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
690     */
692     if (points.size() == 0) {
693         return Inkscape::SnappedPoint(pointer);
694     }
696     std::vector<Inkscape::SnapCandidatePoint> transformed_points;
697     Geom::Rect bbox;
699     long source_num = 0;
700     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
702         /* Work out the transformed version of this point */
703         Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
705         // add the current transformed point to the box hulling all transformed points
706         if (i == points.begin()) {
707             bbox = Geom::Rect(transformed, transformed);
708         } else {
709             bbox.expandTo(transformed);
710         }
712         transformed_points.push_back(Inkscape::SnapCandidatePoint(transformed, (*i).getSourceType(), source_num, Inkscape::SNAPTARGET_UNDEFINED, Geom::OptRect()));
713         source_num++;
714     }
716     /* The current best transformation */
717     Geom::Point best_transformation = transformation;
719     /* The current best metric for the best transformation; lower is better, NR_HUGE
720     ** means that we haven't snapped anything.
721     */
722     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
723     Inkscape::SnappedPoint best_snapped_point;
724     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
725     g_assert(best_snapped_point.getAtIntersection() == false);
727     // Warnings for the devs
728     if (constrained && transformation_type == SCALE && !uniform) {
729         g_warning("Non-uniform constrained scaling is not supported!");
730     }
732     if (!constrained && transformation_type == ROTATE) {
733         // We do not yet allow for simultaneous rotation and scaling
734         g_warning("Unconstrained rotation is not supported!");
735     }
737     std::vector<Inkscape::SnapCandidatePoint>::iterator j = transformed_points.begin();
739     // std::cout << std::endl;
740     bool first_free_snap = true;
741     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
743         /* Snap it */
744         Inkscape::SnappedPoint snapped_point;
745         Inkscape::Snapper::SnapConstraint dedicated_constraint = constraint;
746         Geom::Point const b = ((*i).getPoint() - origin); // vector to original point (not the transformed point! required for rotations!)
748         if (constrained) {
749             if (((transformation_type == SCALE || transformation_type == STRETCH) && uniform)) {
750                 // When uniformly scaling, each point will have its own unique constraint line,
751                 // running from the scaling origin to the original untransformed point. We will
752                 // calculate that line here
753                 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b);
754             } else if (transformation_type == ROTATE) {
755                 Geom::Coord r = Geom::L2(b); // the radius of the circular constraint
756                 if (r < 1e-9) { // points too close to the rotation center will not move. Don't try to snap these
757                     // as they will always yield a perfect snap result if they're already snapped beforehand (e.g.
758                     // when the transformation center has been snapped to a grid intersection in the selector tool)
759                     continue; // skip this SnapCandidate and continue with the next one
760                     // PS1: Apparently we don't have to do this for skewing, but why?
761                     // PS2: We cannot easily filter these points upstream, e.g. in the grab() method (seltrans.cpp)
762                     // because the rotation center will change when pressing shift, and grab() won't be recalled.
763                     // Filtering could be done in handleRequest() (again in seltrans.cpp), by iterating through
764                     // the snap candidates. But hey, we're iterating here anyway.
765                 }
766                 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b, r);
767             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
768                 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), component_vectors[dim]);
769             } else if (transformation_type == TRANSLATE) {
770                 // When doing a constrained translation, all points will move in the same direction, i.e.
771                 // either horizontally or vertically. The lines along which they move are therefore all
772                 // parallel, but might not be colinear. Therefore we will have to specify the point through
773                 // which the constraint-line runs here, for each point individually. (we could also have done this
774                 // earlier on, e.g. in seltrans.cpp but we're being lazy there and don't want to add an iteration loop)
775                 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), constraint.getDirection());
776             } // else: leave the original constraint, e.g. for skewing
777             snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
778         } else {
779             bool const c1 = fabs(b[Geom::X]) < 1e-6;
780             bool const c2 = fabs(b[Geom::Y]) < 1e-6;
781             if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
782                 // When scaling, a point aligned either horizontally or vertically with the origin can only
783                 // move in that specific direction; therefore it should only snap in that direction, otherwise
784                 // we will get snapped points with an invalid transformation
785                 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, component_vectors[c1]);
786                 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
787             } else {
788                 // If we have a collection of SnapCandidatePoints, with mixed constrained snapping and free snapping
789                 // requirements, then freeSnap might never see the SnapCandidatePoint with source_num == 0. The freeSnap()
790                 // method in the object snapper depends on this, because only for source-num == 0 the target nodes will
791                 // be collected. Therefore we enforce that the first SnapCandidatePoint that is to be freeSnapped always
792                 // has source_num == 0;
793                 // TODO: This is a bit ugly so fix this; do we need sourcenum for anything else? if we don't then get rid
794                 // of it and explicitely communicate to the object snapper that this is a first point
795                 if (first_free_snap) {
796                     (*j).setSourceNum(0);
797                     first_free_snap = false;
798                 }
799                 snapped_point = freeSnap(*j, bbox);
800             }
801         }
802         // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
803         snapped_point.setPointerDistance(Geom::L2(pointer - (*i).getPoint()));
805         Geom::Point result;
807         /*Find the transformation that describes where the snapped point has
808         ** ended up, and also the metric for this transformation.
809         */
810         Geom::Point const a = snapped_point.getPoint() - origin; // vector to snapped point
811         //Geom::Point const b = (*i - origin); // vector to original point
813         switch (transformation_type) {
814             case TRANSLATE:
815                 result = snapped_point.getPoint() - (*i).getPoint();
816                 /* Consider the case in which a box is almost aligned with a grid in both
817                  * horizontal and vertical directions. The distance to the intersection of
818                  * the grid lines will always be larger then the distance to a single grid
819                  * line. If we prefer snapping to an intersection instead of to a single
820                  * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
821                  * snapped distance will be used as a metric. Please note that the snapped
822                  * distance is defined as the distance to the nearest line of the intersection,
823                  * and not to the intersection itself!
824                  */
825                 // Only for translations, the relevant metric will be the real snapped distance,
826                 // so we don't have to do anything special here
827                 break;
828             case SCALE:
829             {
830                 result = Geom::Point(NR_HUGE, NR_HUGE);
831                 // If this point *i is horizontally or vertically aligned with
832                 // the origin of the scaling, then it will scale purely in X or Y
833                 // We can therefore only calculate the scaling in this direction
834                 // and the scaling factor for the other direction should remain
835                 // untouched (unless scaling is uniform of course)
836                 for (int index = 0; index < 2; index++) {
837                     if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
838                         if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
839                             result[index] = a[index] / b[index]; // then calculate it!
840                         }
841                         // we might leave result[1-index] = NR_HUGE
842                         // if scaling didn't occur in the other direction
843                     }
844                 }
845                 if (uniform) {
846                     if (fabs(result[0]) < fabs(result[1])) {
847                         result[1] = result[0];
848                     } else {
849                         result[0] = result[1];
850                     }
851                 }
852                 // Compare the resulting scaling with the desired scaling
853                 Geom::Point scale_metric = Geom::abs(result - transformation); // One or both of its components might be NR_HUGE
854                 snapped_point.setSnapDistance(std::min(scale_metric[0], scale_metric[1]));
855                 snapped_point.setSecondSnapDistance(std::max(scale_metric[0], scale_metric[1]));
856                 break;
857             }
858             case STRETCH:
859                 result = Geom::Point(NR_HUGE, NR_HUGE);
860                 if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
861                     result[dim] = a[dim] / b[dim];
862                     result[1-dim] = uniform ? result[dim] : 1;
863                 } else { // STRETCHING might occur for this point, but only when the stretching is uniform
864                     if (uniform && fabs(b[1-dim]) > 1e-6) {
865                        result[1-dim] = a[1-dim] / b[1-dim];
866                        result[dim] = result[1-dim];
867                     }
868                 }
869                 // Store the metric for this transformation as a virtual distance
870                 snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
871                 snapped_point.setSecondSnapDistance(NR_HUGE);
872                 break;
873             case SKEW:
874                 result[0] = (snapped_point.getPoint()[dim] - ((*i).getPoint())[dim]) / b[1 - dim]; // skew factor
875                 result[1] = transformation[1]; // scale factor
876                 // Store the metric for this transformation as a virtual distance
877                 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
878                 snapped_point.setSecondSnapDistance(NR_HUGE);
879                 break;
880             case ROTATE:
881                 // a is vector to snapped point; b is vector to original point; now lets calculate angle between a and b
882                 result[0] = atan2(Geom::dot(Geom::rot90(b), a), Geom::dot(b, a));
883                 result[1] = result[1]; // how else should we store an angle in a point ;-)
884                 // Store the metric for this transformation as a virtual distance (we're storing an angle)
885                 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
886                 snapped_point.setSecondSnapDistance(NR_HUGE);
887                 break;
888             default:
889                 g_assert_not_reached();
890         }
892         if (snapped_point.getSnapped()) {
893             // We snapped; keep track of the best snap
894             if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
895                 best_transformation = result;
896                 best_snapped_point = snapped_point;
897             }
898         } else {
899             // So we didn't snap for this point
900             if (!best_snapped_point.getSnapped()) {
901                 // ... and none of the points before snapped either
902                 // We might still need to apply a constraint though, if we tried a constrained snap. And
903                 // in case of a free snap we might have use for the transformed point, so let's return that
904                 // point, whether it's constrained or not
905                 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
906                     // .. so we must keep track of the best non-snapped constrained point
907                     best_transformation = result;
908                     best_snapped_point = snapped_point;
909                 }
910             }
911         }
913         j++;
914     }
916     Geom::Coord best_metric;
917     if (transformation_type == SCALE) {
918         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
919         for (int index = 0; index < 2; index++) {
920             if (best_transformation[index] == NR_HUGE) {
921                 if (uniform && best_transformation[1-index] < NR_HUGE) {
922                     best_transformation[index] = best_transformation[1-index];
923                 } else {
924                     best_transformation[index] = transformation[index];
925                 }
926             }
927         }
928     }
930     best_metric = best_snapped_point.getSnapDistance();
931     best_snapped_point.setTransformation(best_transformation);
932     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
933     // These rounding errors might be caused by NRRects, see bug #1584301
934     best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
935     return best_snapped_point;
939 /**
940  *  \brief Apply a translation to a set of points and try to snap freely in 2 degrees-of-freedom
941  *
942  *  \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.
943  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
944  *  \param tr Proposed translation; the final translation can only be calculated after snapping has occurred
945  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
946  */
948 Inkscape::SnappedPoint SnapManager::freeSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
949                                                         Geom::Point const &pointer,
950                                                         Geom::Point const &tr) const
952     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, false, Geom::Point(0,0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
954     if (p.size() == 1) {
955         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
956     }
958     return result;
961 /**
962  *  \brief Apply a translation to a set of points and try to snap along a constraint
963  *
964  *  \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.
965  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
966  *  \param constraint The direction or line along which snapping must occur.
967  *  \param tr Proposed translation; the final translation can only be calculated after snapping has occurred.
968  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
969  */
971 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
972                                                                Geom::Point const &pointer,
973                                                                Inkscape::Snapper::SnapConstraint const &constraint,
974                                                                Geom::Point const &tr) const
976     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, true, constraint, TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
978     if (p.size() == 1) {
979         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
980     }
982     return result;
986 /**
987  *  \brief Apply a scaling to a set of points and try to snap freely in 2 degrees-of-freedom
988  *
989  *  \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.
990  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
991  *  \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
992  *  \param o Origin of the scaling
993  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
994  */
996 Inkscape::SnappedPoint SnapManager::freeSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
997                                                   Geom::Point const &pointer,
998                                                   Geom::Scale const &s,
999                                                   Geom::Point const &o) const
1001     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
1003     if (p.size() == 1) {
1004         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
1005     }
1007     return result;
1011 /**
1012  *  \brief Apply a scaling to a set of points and snap such that the aspect ratio of the selection is preserved
1013  *
1014  *  \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.
1015  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1016  *  \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
1017  *  \param o Origin of the scaling
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::constrainedSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
1022                                                          Geom::Point const &pointer,
1023                                                          Geom::Scale const &s,
1024                                                          Geom::Point const &o) const
1026     // When constrained scaling, only uniform scaling is supported.
1027     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
1029     if (p.size() == 1) {
1030         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
1031     }
1033     return result;
1036 /**
1037  *  \brief Apply a stretch to a set of points and snap such that the direction of the stretch is preserved
1038  *
1039  *  \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.
1040  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1041  *  \param s Proposed stretch; the final stretch can only be calculated after snapping has occurred
1042  *  \param o Origin of the stretching
1043  *  \param d Dimension in which to apply proposed stretch.
1044  *  \param u true if the stretch should be uniform (i.e. to be applied equally in both dimensions)
1045  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1046  */
1048 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(std::vector<Inkscape::SnapCandidatePoint> const &p,
1049                                                             Geom::Point const &pointer,
1050                                                             Geom::Coord const &s,
1051                                                             Geom::Point const &o,
1052                                                             Geom::Dim2 d,
1053                                                             bool u) const
1055     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
1057     if (p.size() == 1) {
1058         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
1059     }
1061     return result;
1064 /**
1065  *  \brief Apply a skew to a set of points and snap such that the direction of the skew is preserved
1066  *
1067  *  \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.
1068  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1069  *  \param constraint The direction or line along which snapping must occur.
1070  *  \param s Proposed skew; the final skew can only be calculated after snapping has occurred
1071  *  \param o Origin of the proposed skew
1072  *  \param d Dimension in which to apply proposed skew.
1073  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1074  */
1076 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(std::vector<Inkscape::SnapCandidatePoint> const &p,
1077                                                  Geom::Point const &pointer,
1078                                                  Inkscape::Snapper::SnapConstraint const &constraint,
1079                                                  Geom::Point const &s,
1080                                                  Geom::Point const &o,
1081                                                  Geom::Dim2 d) const
1083     // "s" contains skew factor in s[0], and scale factor in s[1]
1085     // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
1086     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
1087     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
1088     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
1089     // of bounding boxes is not allowed here.
1090     if (p.size() > 0) {
1091         g_assert(!(p.at(0).getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY));
1092     }
1094     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, true, constraint, SKEW, s, o, d, false);
1096     if (p.size() == 1) {
1097         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
1098     }
1100     return result;
1103 /**
1104  *  \brief Apply a rotation to a set of points and snap, without scaling
1105  *
1106  *  \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.
1107  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1108  *  \param angle Proposed rotation (in radians); the final rotation can only be calculated after snapping has occurred
1109  *  \param o Origin of the rotation
1110  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1111  */
1113 Inkscape::SnappedPoint SnapManager::constrainedSnapRotate(std::vector<Inkscape::SnapCandidatePoint> const &p,
1114                                                     Geom::Point const &pointer,
1115                                                     Geom::Coord const &angle,
1116                                                     Geom::Point const &o) const
1118     // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
1119     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
1120     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
1121     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
1122     // of bounding boxes is not allowed here.
1124     Inkscape::SnappedPoint result = _snapTransformed(p, pointer, true, Geom::Point(0,0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1126     if (p.size() == 1) {
1127         _displaySnapsource(Inkscape::SnapCandidatePoint(result.getPoint(), p.at(0).getSourceType()));
1128     }
1130     return result;
1134 /**
1135  * \brief Given a set of possible snap targets, find the best target (which is not necessarily
1136  * also the nearest target), and show the snap indicator if requested
1137  *
1138  * \param p Source point to be snapped
1139  * \param sc A structure holding all snap targets that have been found so far
1140  * \param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation.
1141  * \param noCurves If true, then do consider snapping to intersections of curves, but not to the curves themselves
1142  * \param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example when pasting to the grid)
1143  * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
1144  */
1146 Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p,
1147                                                  SnappedConstraints const &sc,
1148                                                  bool constrained,
1149                                                  bool noCurves,
1150                                                  bool allowOffScreen) const
1152     g_assert(_desktop != NULL);
1154     /*
1155     std::cout << "Type and number of snapped constraints: " << std::endl;
1156     std::cout << "  Points      : " << sc.points.size() << std::endl;
1157     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
1158     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
1159     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
1160     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
1161     */
1163     // Store all snappoints
1164     std::list<Inkscape::SnappedPoint> sp_list;
1166     // search for the closest snapped point
1167     Inkscape::SnappedPoint closestPoint;
1168     if (getClosestSP(sc.points, closestPoint)) {
1169         sp_list.push_back(closestPoint);
1170     }
1172     // search for the closest snapped curve
1173     if (!noCurves) {
1174         Inkscape::SnappedCurve closestCurve;
1175         if (getClosestCurve(sc.curves, closestCurve)) {
1176             sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
1177         }
1178     }
1180     if (snapprefs.getSnapIntersectionCS()) {
1181         // search for the closest snapped intersection of curves
1182         Inkscape::SnappedPoint closestCurvesIntersection;
1183         if (getClosestIntersectionCS(sc.curves, p.getPoint(), closestCurvesIntersection, _desktop->dt2doc())) {
1184             closestCurvesIntersection.setSource(p.getSourceType());
1185             sp_list.push_back(closestCurvesIntersection);
1186         }
1187     }
1189     // search for the closest snapped grid line
1190     Inkscape::SnappedLine closestGridLine;
1191     if (getClosestSL(sc.grid_lines, closestGridLine)) {
1192         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
1193     }
1195     // search for the closest snapped guide line
1196     Inkscape::SnappedLine closestGuideLine;
1197     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
1198         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
1199     }
1201     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
1202     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
1204     // When doing a constrained snap however, we're already at an intersection of the constrained line and
1205     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
1206     // no need to look for additional intersections
1207     if (!constrained) {
1208         // search for the closest snapped intersection of grid lines
1209         Inkscape::SnappedPoint closestGridPoint;
1210         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
1211             closestGridPoint.setSource(p.getSourceType());
1212             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
1213             sp_list.push_back(closestGridPoint);
1214         }
1216         // search for the closest snapped intersection of guide lines
1217         Inkscape::SnappedPoint closestGuidePoint;
1218         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
1219             closestGuidePoint.setSource(p.getSourceType());
1220             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
1221             sp_list.push_back(closestGuidePoint);
1222         }
1224         // search for the closest snapped intersection of grid with guide lines
1225         if (snapprefs.getSnapIntersectionGG()) {
1226             Inkscape::SnappedPoint closestGridGuidePoint;
1227             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
1228                 closestGridGuidePoint.setSource(p.getSourceType());
1229                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
1230                 sp_list.push_back(closestGridGuidePoint);
1231             }
1232         }
1233     }
1235     // now let's see which snapped point gets a thumbs up
1236     Inkscape::SnappedPoint bestSnappedPoint(p.getPoint());
1237     // std::cout << "Finding the best snap..." << std::endl;
1238     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
1239         // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << (*i).getTarget();
1240         bool onScreen = _desktop->get_display_area().contains((*i).getPoint());
1241         if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen
1242             if ((*i).getSnapDistance() <= (*i).getTolerance()) { // Only snap to points within snapping range
1243                 // if it's the first point, or if it is closer than the best snapped point so far
1244                 if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
1245                     // then prefer this point over the previous one
1246                     bestSnappedPoint = *i;
1247                 }
1248             }
1249         }
1250         // std::cout << std::endl;
1251     }
1253     // Update the snap indicator, if requested
1254     if (_snapindicator) {
1255         if (bestSnappedPoint.getSnapped()) {
1256             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
1257         } else {
1258             _desktop->snapindicator->remove_snaptarget();
1259         }
1260     }
1262     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
1263     return bestSnappedPoint;
1266 /// Convenience shortcut when there is only one item to ignore
1267 void SnapManager::setup(SPDesktop const *desktop,
1268                         bool snapindicator,
1269                         SPItem const *item_to_ignore,
1270                         std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1271                         SPGuide *guide_to_ignore)
1273     g_assert(desktop != NULL);
1274     if (_desktop != NULL) {
1275         g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1276     }
1277     _items_to_ignore.clear();
1278     _items_to_ignore.push_back(item_to_ignore);
1279     _desktop = desktop;
1280     _snapindicator = snapindicator;
1281     _unselected_nodes = unselected_nodes;
1282     _guide_to_ignore = guide_to_ignore;
1283     _rotation_center_source_items = NULL;
1286 /**
1287  * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1288  * to ignore and toggling the snap indicator
1289  *
1290  * There are two overloaded setup() methods, of which the other one only allows for a single item to be ignored
1291  * whereas this one will take a list of items to ignore
1292  *
1293  * \param desktop Reference to the desktop to which this snap manager is attached
1294  * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1295  * \param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping"
1296  * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1297  * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1298  * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1299  * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1300  */
1302 void SnapManager::setup(SPDesktop const *desktop,
1303                         bool snapindicator,
1304                         std::vector<SPItem const *> &items_to_ignore,
1305                         std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1306                         SPGuide *guide_to_ignore)
1308     g_assert(desktop != NULL);
1309     if (_desktop != NULL) {
1310         g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1311     }
1312     _items_to_ignore = items_to_ignore;
1313     _desktop = desktop;
1314     _snapindicator = snapindicator;
1315     _unselected_nodes = unselected_nodes;
1316     _guide_to_ignore = guide_to_ignore;
1317     _rotation_center_source_items = NULL;
1320 /// Setup, taking the list of items to ignore from the desktop's selection.
1321 void SnapManager::setupIgnoreSelection(SPDesktop const *desktop,
1322                                       bool snapindicator,
1323                                       std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1324                                       SPGuide *guide_to_ignore)
1326     g_assert(desktop != NULL);
1327     if (_desktop != NULL) {
1328         // Someone has been naughty here! This is dangerous
1329         g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1330     }
1331     _desktop = desktop;
1332     _snapindicator = snapindicator;
1333     _unselected_nodes = unselected_nodes;
1334     _guide_to_ignore = guide_to_ignore;
1335     _rotation_center_source_items = NULL;
1336     _items_to_ignore.clear();
1338     Inkscape::Selection *sel = _desktop->selection;
1339     GSList const *items = sel->itemList();
1340     for (GSList *i = const_cast<GSList*>(items); i; i = i->next) {
1341         _items_to_ignore.push_back(static_cast<SPItem const *>(i->data));
1342     }
1345 SPDocument *SnapManager::getDocument() const
1347     return _named_view->document;
1350 /**
1351  * \brief Takes an untransformed point, applies the given transformation, and returns the transformed point. Eliminates lots of duplicated code
1352  *
1353  * \param p The untransformed position of the point, paired with an identifier of the type of the snap source.
1354  * \param transformation_type Type of transformation to apply.
1355  * \param transformation Mathematical description of the transformation; details depend on the type.
1356  * \param origin Origin of the transformation, if applicable.
1357  * \param dim Dimension to which the transformation applies, if applicable.
1358  * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
1359  * \return The position of the point after transformation
1360  */
1362 Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p,
1363                                         Transformation const transformation_type,
1364                                         Geom::Point const &transformation,
1365                                         Geom::Point const &origin,
1366                                         Geom::Dim2 const dim,
1367                                         bool const uniform) const
1369     /* Work out the transformed version of this point */
1370     Geom::Point transformed;
1371     switch (transformation_type) {
1372         case TRANSLATE:
1373             transformed = p.getPoint() + transformation;
1374             break;
1375         case SCALE:
1376             transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
1377             break;
1378         case STRETCH:
1379         {
1380             Geom::Scale s(1, 1);
1381             if (uniform)
1382                 s[Geom::X] = s[Geom::Y] = transformation[dim];
1383             else {
1384                 s[dim] = transformation[dim];
1385                 s[1 - dim] = 1;
1386             }
1387             transformed = ((p.getPoint() - origin) * s) + origin;
1388             break;
1389         }
1390         case SKEW:
1391             // Apply the skew factor
1392             transformed[dim] = (p.getPoint())[dim] + transformation[0] * ((p.getPoint())[1 - dim] - origin[1 - dim]);
1393             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
1394             // Apply that scale factor here
1395             transformed[1-dim] = (p.getPoint() - origin)[1 - dim] * transformation[1] + origin[1 - dim];
1396             break;
1397         case ROTATE:
1398             // for rotations: transformation[0] stores the angle in radians
1399             transformed = (p.getPoint() - origin) * Geom::Rotate(transformation[0]) + origin;
1400             break;
1401         default:
1402             g_assert_not_reached();
1403     }
1405     return transformed;
1408 /**
1409  * \brief Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol
1410  *
1411  * \param point_type Category of points to which the source point belongs: node, guide or bounding box
1412  * \param p The transformed position of the source point, paired with an identifier of the type of the snap source.
1413  */
1415 void SnapManager::_displaySnapsource(Inkscape::SnapCandidatePoint const &p) const {
1417     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1418     if (prefs->getBool("/options/snapclosestonly/value")) {
1419         bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
1420         bool p_is_a_bbox = p.getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
1421         bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
1423         g_assert(_desktop != NULL);
1424         if (snapprefs.getSnapEnabledGlobally() && (p_is_other || (p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
1425             _desktop->snapindicator->set_new_snapsource(p);
1426         } else {
1427             _desktop->snapindicator->remove_snapsource();
1428         }
1429     }
1432 /*
1433   Local Variables:
1434   mode:c++
1435   c-file-style:"stroustrup"
1436   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1437   indent-tabs-mode:nil
1438   fill-column:99
1439   End:
1440 */
1441 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :