Code

Major simplification of 3D box code.
[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-2009 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 "sp-guide.h"
34 #include "preferences.h"
35 #include "event-context.h"
36 using std::vector;
38 /**
39  *  Construct a SnapManager for a SPNamedView.
40  *
41  *  \param v `Owning' SPNamedView.
42  */
44 SnapManager::SnapManager(SPNamedView const *v) :
45     guide(this, 0),
46     object(this, 0),
47     snapprefs(),
48     _named_view(v)
49 {
50 }
52 /**
53  *  \brief Return a list of snappers
54  *
55  *  Inkscape snaps to objects, grids, and guides. For each of these snap targets a
56  *  separate class is used, which has been derived from the base Snapper class. The
57  *  getSnappers() method returns a list of pointers to instances of this class. This
58  *  list contains exactly one instance of the guide snapper and of the object snapper
59  *  class, but any number of grid snappers (because each grid has its own snapper
60  *  instance)
61  *
62  *  \return List of snappers that we use.
63  */
64 SnapManager::SnapperList
65 SnapManager::getSnappers() const
66 {
67     SnapManager::SnapperList s;
68     s.push_back(&guide);
69     s.push_back(&object);
71     SnapManager::SnapperList gs = getGridSnappers();
72     s.splice(s.begin(), gs);
74     return s;
75 }
77 /**
78  *  \brief Return a list of gridsnappers
79  *
80  *  Each grid has its own instance of the snapper class. This way snapping can
81  *  be enabled per grid individually. A list will be returned containing the
82  *  pointers to these instances, but only for grids that are being displayed
83  *  and for which snapping is enabled.
84  *
85  *  \return List of gridsnappers that we use.
86  */
87 SnapManager::SnapperList
88 SnapManager::getGridSnappers() const
89 {
90     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;
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
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());
128 /**
129  * \return true if one of the grids might be snapped to.
130  */
132 bool SnapManager::gridSnapperMightSnap() const
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());
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: SnapManager::setup() must have been called before calling this method,
162  *  but only once for a set of points
163  *
164  *  \param point_type Category of points to which the source point belongs: node, guide or bounding box
165  *  \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
166  *  \param source_type Detailed description of the source type, will be used by the snap indicator
167  *  \param source_num Sequence number of the source point within the set of points that is to be snapped. Starting at zero
168  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
169  */
171 void SnapManager::freeSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
172                                       Geom::Point &p,
173                                       Inkscape::SnapSourceType const source_type,
174                                       long source_num,
175                                       Geom::OptRect const &bbox_to_snap) const
177     //TODO: PointType and source_type are somewhat redundant; can't we get rid of the point_type parameter?
178     Inkscape::SnappedPoint const s = freeSnap(point_type, p, source_type, source_num, bbox_to_snap);
179     s.getPoint(p);
183 /**
184  *  \brief Try to snap a point to grids, guides or objects.
185  *
186  *  Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
187  *  i.e. snap in any direction on the two dimensional canvas to the nearest
188  *  snap target. freeSnap() is equal in snapping behavior to
189  *  freeSnapReturnByRef(). Please read the comments of the latter for more details
190  *
191  *  PS: SnapManager::setup() must have been called before calling this method,
192  *  but only once for a set of points
193  *
194  *  \param point_type Category of points to which the source point belongs: node, guide or bounding box
195  *  \param p Current position of the snap source
196  *  \param source_type Detailed description of the source type, will be used by the snap indicator
197  *  \param source_num Sequence number of the source point within the set of points that is to be snapped. Starting at zero
198  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
199  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
200  */
203 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapPreferences::PointType point_type,
204                                              Geom::Point const &p,
205                                              Inkscape::SnapSourceType const &source_type,
206                                              long source_num,
207                                              Geom::OptRect const &bbox_to_snap) const
209     if (!someSnapperMightSnap()) {
210         return Inkscape::SnappedPoint(p, source_type, 0, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
211     }
213     std::vector<SPItem const *> *items_to_ignore;
214     if (_item_to_ignore) { // If we have only a single item to ignore
215         // then build a list containing this single item;
216         // This single-item list will prevail over any other _items_to_ignore list, should that exist
217         items_to_ignore = new std::vector<SPItem const *>;
218         items_to_ignore->push_back(_item_to_ignore);
219     } else {
220         items_to_ignore = _items_to_ignore;
221     }
223     SnappedConstraints sc;
224     SnapperList const snappers = getSnappers();
226     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
227         (*i)->freeSnap(sc, point_type, p, source_type, source_num, bbox_to_snap, items_to_ignore, _unselected_nodes);
228     }
230     if (_item_to_ignore) {
231         delete items_to_ignore;
232     }
234     return findBestSnap(p, source_type, sc, false);
237 /**
238  * \brief Snap to the closest multiple of a grid pitch
239  *
240  * When pasting, we would like to snap to the grid. Problem is that we don't know which
241  * nodes were aligned to the grid at the time of copying, so we don't know which nodes
242  * to snap. If we'd snap an unaligned node to the grid, previously aligned nodes would
243  * become unaligned. That's undesirable. Instead we will make sure that the offset
244  * between the source and its pasted copy is a multiple of the grid pitch. If the source
245  * was aligned, then the copy will therefore also be aligned.
246  *
247  * PS: Whether we really find a multiple also depends on the snapping range! Most users
248  * will have "always snap" enabled though, in which case a multiple will always be found.
249  * PS2: When multiple grids are present then the result will become ambiguous. There is no
250  * way to control to which grid this method will snap.
251  *
252  * \param t Vector that represents the offset of the pasted copy with respect to the original
253  * \return Offset vector after snapping to the closest multiple of a grid pitch
254  */
256 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
258     if (!snapprefs.getSnapEnabledGlobally()) // No need to check for snapprefs.getSnapPostponedGlobally() here
259         return t;
261     if (_desktop && _desktop->gridsEnabled()) {
262         bool success = false;
263         Geom::Point nearest_multiple;
264         Geom::Coord nearest_distance = NR_HUGE;
266         // It will snap to the grid for which we find the closest snap. This might be a different
267         // grid than to which the objects were initially aligned. I don't see an easy way to fix
268         // this, so when using multiple grids one can get unexpected results
270         // Cannot use getGridSnappers() because we need both the grids AND their snappers
271         // Therefore we iterate through all grids manually
272         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
273             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
274             const Inkscape::Snapper* snapper = grid->snapper;
275             if (snapper && snapper->ThisSnapperMightSnap()) {
276                 // To find the nearest multiple of the grid pitch for a given translation t, we
277                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
278                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
279                 // in the translation t
280                 Geom::Point const t_offset = t + grid->origin;
281                 SnappedConstraints sc;
282                 // Only the first three parameters are being used for grid snappers
283                 snapper->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_NODE, t_offset, Inkscape::SNAPSOURCE_UNDEFINED, 0, Geom::OptRect(), NULL, NULL);
284                 // Find the best snap for this grid, including intersections of the grid-lines
285                 Inkscape::SnappedPoint s = findBestSnap(t_offset, Inkscape::SNAPSOURCE_UNDEFINED, sc, false);
286                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
287                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
288                     // doesn't tell us anything about which node to snap
289                     success = true;
290                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
291                     nearest_distance = s.getSnapDistance();
292                 }
293             }
294         }
296         if (success)
297             return nearest_multiple;
298     }
300     return t;
303 /**
304  *  \brief Try to snap a point along a constraint line to grids, guides or objects.
305  *
306  *  Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
307  *  i.e. snap in a specific direction on the two dimensional canvas to the nearest
308  *  snap target.
309  *
310  *  constrainedSnapReturnByRef() is equal in snapping behavior to
311  *  constrainedSnap(), but the former returns the snapped point trough the referenced
312  *  parameter p. This parameter p initially contains the position of the snap
313  *  source and will we overwritten by the target position if snapping has occurred.
314  *  This makes snapping transparent to the calling code. If this is not desired
315  *  because either the calling code must know whether snapping has occurred, or
316  *  because the original position should not be touched, then constrainedSnap() should
317  *  be called instead.
318  *
319  *  PS: SnapManager::setup() must have been called before calling this method,
320  *  but only once for a set of points
321  *
322  *  \param point_type Category of points to which the source point belongs: node, guide or bounding box
323  *  \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
324  *  \param source_type Detailed description of the source type, will be used by the snap indicator
325  *  \param constraint The direction or line along which snapping must occur
326  *  \param source_num Sequence number of the source point within the set of points that is to be snapped. Starting at zero
327  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
328  */
330 void SnapManager::constrainedSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
331                                              Geom::Point &p,
332                                              Inkscape::SnapSourceType const source_type,
333                                              Inkscape::Snapper::ConstraintLine const &constraint,
334                                              long source_num,
335                                              Geom::OptRect const &bbox_to_snap) const
337     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, source_type, constraint, source_num, bbox_to_snap);
338     s.getPoint(p);
341 /**
342  *  \brief Try to snap a point along a constraint line to grids, guides or objects.
343  *
344  *  Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
345  *  i.e. snap in a specific direction on the two dimensional canvas to the nearest
346  *  snap target. constrainedSnap is equal in snapping behavior to
347  *  constrainedSnapReturnByRef(). Please read the comments of the latter for more details.
348  *
349  *  PS: SnapManager::setup() must have been called before calling this method,
350  *  but only once for a set of points
351  *
352  *  \param point_type Category of points to which the source point belongs: node, guide or bounding box
353  *  \param p Current position of the snap source
354  *  \param source_type Detailed description of the source type, will be used by the snap indicator
355  *  \param constraint The direction or line along which snapping must occur
356  *  \param source_num Sequence number of the source point within the set of points that is to be snapped. Starting at zero
357  *  \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
358  */
360 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapPreferences::PointType point_type,
361                                                     Geom::Point const &p,
362                                                     Inkscape::SnapSourceType const &source_type,
363                                                     Inkscape::Snapper::ConstraintLine const &constraint,
364                                                     long source_num,
365                                                     Geom::OptRect const &bbox_to_snap) const
367     if (!someSnapperMightSnap()) {
368         return Inkscape::SnappedPoint(p, source_type, 0, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
369     }
371     std::vector<SPItem const *> *items_to_ignore;
372     if (_item_to_ignore) { // If we have only a single item to ignore
373         // then build a list containing this single item;
374         // This single-item list will prevail over any other _items_to_ignore list, should that exist
375         items_to_ignore = new std::vector<SPItem const *>;
376         items_to_ignore->push_back(_item_to_ignore);
377     } else {
378         items_to_ignore = _items_to_ignore;
379     }
382     // First project the mouse pointer onto the constraint
383     Geom::Point pp = constraint.projection(p);
384     // Then try to snap the projected point
386     SnappedConstraints sc;
387     SnapperList const snappers = getSnappers();
388     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
389         (*i)->constrainedSnap(sc, point_type, pp, source_type, source_num, bbox_to_snap, constraint, items_to_ignore);
390     }
392     if (_item_to_ignore) {
393         delete items_to_ignore;
394     }
396     return findBestSnap(pp, source_type, sc, true);
399 /**
400  *  \brief Try to snap a point of a guide to another guide or to a node
401  *
402  *  Try to snap a point of a guide to another guide or to a node in two degrees-
403  *  of-freedom, i.e. snap in any direction on the two dimensional canvas to the
404  *  nearest snap target. This method is used when dragging or rotating a guide
405  *
406  *  PS: SnapManager::setup() must have been called before calling this method,
407  *
408  *  \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
409  *  \param guide_normal Vector normal to the guide line
410  */
411 void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point const &guide_normal, SPGuideDragType drag_type) const
413     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
414         return;
415     }
417     if (!(object.GuidesMightSnap() || snapprefs.getSnapToGuides())) {
418         return;
419     }
421     Inkscape::SnapSourceType source_type = Inkscape::SNAPSOURCE_GUIDE_ORIGIN;
422     if (drag_type == SP_DRAG_ROTATE) {
423         source_type = Inkscape::SNAPSOURCE_GUIDE;
424     }
426     // Snap to nodes
427     SnappedConstraints sc;
428     if (object.GuidesMightSnap()) {
429         object.guideFreeSnap(sc, p, guide_normal);
430     }
432     // Snap to guides & grid lines
433     SnapperList snappers = getGridSnappers();
434     snappers.push_back(&guide);
435     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
436         (*i)->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, source_type, 0, Geom::OptRect(), NULL, NULL);
437     }
439     // Snap to intersections of curves, but not to the curves themselves! (see _snapTranslatingGuideToNodes in object-snapper.cpp)
440     Inkscape::SnappedPoint const s = findBestSnap(p, source_type, sc, false, true);
442     s.getPoint(p);
445 /**
446  *  \brief Try to snap a point on a guide to the intersection with another guide or a path
447  *
448  *  Try to snap a point on a guide to the intersection of that guide with another
449  *  guide or with a path. The snapped point will lie somewhere on the guide-line,
450  *  making this is a constrained snap, i.e. in only one degree-of-freedom.
451  *  This method is used when dragging the origin of the guide along the guide itself.
452  *
453  *  PS: SnapManager::setup() must have been called before calling this method,
454  *
455  *  \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
456  *  \param guide_normal Vector normal to the guide line
457  */
459 void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const
461     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
462         return;
463     }
465     if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
466         return;
467     }
469     Inkscape::SnapSourceType source_type = Inkscape::SNAPSOURCE_GUIDE_ORIGIN;
471     // Snap to nodes or paths
472     SnappedConstraints sc;
473     Inkscape::Snapper::ConstraintLine cl(guideline.point_on_line, Geom::rot90(guideline.normal_to_line));
474     if (object.ThisSnapperMightSnap()) {
475         object.constrainedSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, source_type, 0, Geom::OptRect(), cl, NULL);
476     }
478     // Snap to guides & grid lines
479     SnapperList snappers = getGridSnappers();
480     snappers.push_back(&guide);
481     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
482         (*i)->constrainedSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, source_type, 0, Geom::OptRect(), cl, NULL);
483     }
485     Inkscape::SnappedPoint const s = findBestSnap(p, source_type, sc, false);
486     s.getPoint(p);
489 /**
490  *  \brief Method for snapping sets of points while they are being transformed
491  *
492  *  Method for snapping sets of points while they are being transformed, when using
493  *  for example the selector tool. This method is for internal use only, and should
494  *  not have to be called directly. Use freeSnapTransalation(), constrainedSnapScale(),
495  *  etc. instead.
496  *
497  *  This is what is being done in this method: transform each point, find out whether
498  *  a free snap or constrained snap is more appropriate, do the snapping, calculate
499  *  some metrics to quantify the snap "distance", and see if it's better than the
500  *  previous snap. Finally, the best ("nearest") snap from all these points is returned.
501  *
502  *  \param type Category of points to which the source point belongs: node or bounding box.
503  *  \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.
504  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
505  *  \param constrained true if the snap is constrained, e.g. for stretching or for purely horizontal translation.
506  *  \param constraint The direction or line along which snapping must occur, if 'constrained' is true; otherwise undefined.
507  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
508  *  \param transformation Description of the transformation; details depend on the type.
509  *  \param origin Origin of the transformation, if applicable.
510  *  \param dim Dimension to which the transformation applies, if applicable.
511  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
512  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
513  */
515 Inkscape::SnappedPoint SnapManager::_snapTransformed(
516     Inkscape::SnapPreferences::PointType type,
517     std::vector<std::pair<Geom::Point, int> > const &points,
518     Geom::Point const &pointer,
519     bool constrained,
520     Inkscape::Snapper::ConstraintLine const &constraint,
521     Transformation transformation_type,
522     Geom::Point const &transformation,
523     Geom::Point const &origin,
524     Geom::Dim2 dim,
525     bool uniform) const
527     /* We have a list of points, which we are proposing to transform in some way.  We need to see
528     ** if any of these points, when transformed, snap to anything.  If they do, we return the
529     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
530     */
532     /* Quick check to see if we have any snappers that are enabled
533     ** Also used to globally disable all snapping
534     */
535     if (someSnapperMightSnap() == false) {
536         return Inkscape::SnappedPoint();
537     }
539     std::vector<std::pair<Geom::Point, int> > transformed_points;
540     Geom::Rect bbox;
542     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
544         /* Work out the transformed version of this point */
545         Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
547         // add the current transformed point to the box hulling all transformed points
548         if (i == points.begin()) {
549             bbox = Geom::Rect(transformed, transformed);
550         } else {
551             bbox.expandTo(transformed);
552         }
554         transformed_points.push_back(std::make_pair(transformed, (*i).second));
555     }
557     /* The current best transformation */
558     Geom::Point best_transformation = transformation;
560     /* The current best metric for the best transformation; lower is better, NR_HUGE
561     ** means that we haven't snapped anything.
562     */
563     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
564     Inkscape::SnappedPoint best_snapped_point;
565     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
566     g_assert(best_snapped_point.getAtIntersection() == false);
568     std::vector<std::pair<Geom::Point, int> >::const_iterator j = transformed_points.begin();
569     long source_num = 0;
571     // std::cout << std::endl;
572     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
574         /* Snap it */
575         Inkscape::SnappedPoint snapped_point;
576         Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
577         Geom::Point const b = ((*i).first - origin); // vector to original point
579         if (constrained) {
580             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
581                 // When uniformly scaling, each point will have its own unique constraint line,
582                 // running from the scaling origin to the original untransformed point. We will
583                 // calculate that line here
584                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, b);
585             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
586                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i).first, component_vectors[dim]);
587             } else if (transformation_type == TRANSLATION) {
588                 // When doing a constrained translation, all points will move in the same direction, i.e.
589                 // either horizontally or vertically. The lines along which they move are therefore all
590                 // parallel, but might not be colinear. Therefore we will have to set the point through
591                 // which the constraint-line runs here, for each point individually.
592                 dedicated_constraint.setPoint((*i).first);
593             } // else: leave the original constraint, e.g. for skewing
594             if (transformation_type == SCALE && !uniform) {
595                 g_warning("Non-uniform constrained scaling is not supported!");
596             }
597             snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, source_num, bbox);
598         } else {
599             bool const c1 = fabs(b[Geom::X]) < 1e-6;
600             bool const c2 = fabs(b[Geom::Y]) < 1e-6;
601             if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
602                 // When scaling, a point aligned either horizontally or vertically with the origin can only
603                 // move in that specific direction; therefore it should only snap in that direction, otherwise
604                 // we will get snapped points with an invalid transformation
605                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, component_vectors[c1]);
606                 snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, source_num, bbox);
607             } else {
608                 snapped_point = freeSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), source_num, bbox);
609             }
610         }
611         // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
612         snapped_point.setPointerDistance(Geom::L2(pointer - (*i).first));
614         Geom::Point result;
615         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
617         if (snapped_point.getSnapped()) {
618             /* We snapped.  Find the transformation that describes where the snapped point has
619             ** ended up, and also the metric for this transformation.
620             */
621             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
622             //Geom::Point const b = (*i - origin); // vector to original point
624             switch (transformation_type) {
625                 case TRANSLATION:
626                     result = snapped_point.getPoint() - (*i).first;
627                     /* Consider the case in which a box is almost aligned with a grid in both
628                      * horizontal and vertical directions. The distance to the intersection of
629                      * the grid lines will always be larger then the distance to a single grid
630                      * line. If we prefer snapping to an intersection instead of to a single
631                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
632                      * snapped distance will be used as a metric. Please note that the snapped
633                      * distance is defined as the distance to the nearest line of the intersection,
634                      * and not to the intersection itself!
635                      */
636                     // Only for translations, the relevant metric will be the real snapped distance,
637                     // so we don't have to do anything special here
638                     break;
639                 case SCALE:
640                 {
641                     result = Geom::Point(NR_HUGE, NR_HUGE);
642                     // If this point *i is horizontally or vertically aligned with
643                     // the origin of the scaling, then it will scale purely in X or Y
644                     // We can therefore only calculate the scaling in this direction
645                     // and the scaling factor for the other direction should remain
646                     // untouched (unless scaling is uniform ofcourse)
647                     for (int index = 0; index < 2; index++) {
648                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
649                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
650                                 result[index] = a[index] / b[index]; // then calculate it!
651                             }
652                             // we might leave result[1-index] = NR_HUGE
653                             // if scaling didn't occur in the other direction
654                         }
655                     }
656                     // Compare the resulting scaling with the desired scaling
657                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
658                     break;
659                 }
660                 case STRETCH:
661                     result = Geom::Point(NR_HUGE, NR_HUGE);
662                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
663                         result[dim] = a[dim] / b[dim];
664                         result[1-dim] = uniform ? result[dim] : 1;
665                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
666                         if (uniform && fabs(b[1-dim]) > 1e-6) {
667                            result[1-dim] = a[1-dim] / b[1-dim];
668                            result[dim] = result[1-dim];
669                         }
670                     }
671                     // Store the metric for this transformation as a virtual distance
672                     snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
673                     snapped_point.setSecondSnapDistance(NR_HUGE);
674                     break;
675                 case SKEW:
676                     result[0] = (snapped_point.getPoint()[dim] - ((*i).first)[dim]) / (((*i).first)[1 - dim] - origin[1 - dim]); // skew factor
677                     result[1] = transformation[1]; // scale factor
678                     // Store the metric for this transformation as a virtual distance
679                     snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
680                     snapped_point.setSecondSnapDistance(NR_HUGE);
681                     break;
682                 default:
683                     g_assert_not_reached();
684             }
686             // When scaling, we're considering the best transformation in each direction separately. We will have a metric in each
687             // direction, whereas for all other transformation we only a single one-dimensional metric. That's why we need to handle
688             // the scaling metric differently
689             if (transformation_type == SCALE) {
690                 for (int index = 0; index < 2; index++) {
691                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
692                         best_transformation[index] = result[index];
693                         best_scale_metric[index] = fabs(scale_metric[index]);
694                         // When scaling, we're considering the best transformation in each direction separately
695                         // Therefore two different snapped points might together make a single best transformation
696                         // We will however return only a single snapped point (e.g. to display the snapping indicator)
697                         best_snapped_point = snapped_point;
698                         // std::cout << "SEL ";
699                     } // else { std::cout << "    ";}
700                 }
701                 if (uniform) {
702                     if (best_scale_metric[0] < best_scale_metric[1]) {
703                         best_transformation[1] = best_transformation[0];
704                         best_scale_metric[1] = best_scale_metric[0];
705                     } else {
706                         best_transformation[0] = best_transformation[1];
707                         best_scale_metric[0] = best_scale_metric[1];
708                     }
709                 }
710             } else { // For all transformations other than scaling
711                 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
712                     best_transformation = result;
713                     best_snapped_point = snapped_point;
714                 }
715             }
716         }
718         j++;
719         source_num++;
720     }
722     Geom::Coord best_metric;
723     if (transformation_type == SCALE) {
724         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
725         for (int index = 0; index < 2; index++) {
726             if (best_transformation[index] == NR_HUGE) {
727                 if (uniform && best_transformation[1-index] < NR_HUGE) {
728                     best_transformation[index] = best_transformation[1-index];
729                 } else {
730                     best_transformation[index] = transformation[index];
731                 }
732             }
733         }
734         best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
735     } else { // For all transformations other than scaling
736         best_metric = best_snapped_point.getSnapDistance();
737     }
739     best_snapped_point.setTransformation(best_transformation);
740     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
741     // These rounding errors might be caused by NRRects, see bug #1584301
742     best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
743     return best_snapped_point;
747 /**
748  *  \brief Apply a translation to a set of points and try to snap freely in 2 degrees-of-freedom
749  *
750  *  \param point_type Category of points to which the source point belongs: node or bounding box.
751  *  \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.
752  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
753  *  \param tr Proposed translation; the final translation can only be calculated after snapping has occurred
754  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
755  */
757 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
758                                                         std::vector<std::pair<Geom::Point, int> > const &p,
759                                                         Geom::Point const &pointer,
760                                                         Geom::Point const &tr) const
762     if (p.size() == 1) {
763         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
764     }
766     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
769 /**
770  *  \brief Apply a translation to a set of points and try to snap along a constraint
771  *
772  *  \param point_type Category of points to which the source point belongs: node or bounding box.
773  *  \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.
774  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
775  *  \param constraint The direction or line along which snapping must occur.
776  *  \param tr Proposed translation; the final translation can only be calculated after snapping has occurred.
777  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
778  */
780 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
781                                                                std::vector<std::pair<Geom::Point, int> > const &p,
782                                                                Geom::Point const &pointer,
783                                                                Inkscape::Snapper::ConstraintLine const &constraint,
784                                                                Geom::Point const &tr) const
786     if (p.size() == 1) {
787         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
788     }
790     return _snapTransformed(point_type, p, pointer, true, constraint, TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
794 /**
795  *  \brief Apply a scaling to a set of points and try to snap freely in 2 degrees-of-freedom
796  *
797  *  \param point_type Category of points to which the source point belongs: node or bounding box.
798  *  \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.
799  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
800  *  \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
801  *  \param o Origin of the scaling
802  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
803  */
805 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::SnapPreferences::PointType point_type,
806                                                   std::vector<std::pair<Geom::Point, int> > const &p,
807                                                   Geom::Point const &pointer,
808                                                   Geom::Scale const &s,
809                                                   Geom::Point const &o) const
811     if (p.size() == 1) {
812         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false), (p.at(0)).second));
813     }
815     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
819 /**
820  *  \brief Apply a scaling to a set of points and snap such that the aspect ratio of the selection is preserved
821  *
822  *  \param point_type Category of points to which the source point belongs: node or bounding box.
823  *  \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.
824  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
825  *  \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
826  *  \param o Origin of the scaling
827  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
828  */
830 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::SnapPreferences::PointType point_type,
831                                                          std::vector<std::pair<Geom::Point, int> > const &p,
832                                                          Geom::Point const &pointer,
833                                                          Geom::Scale const &s,
834                                                          Geom::Point const &o) const
836     // When constrained scaling, only uniform scaling is supported.
837     if (p.size() == 1) {
838         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true), (p.at(0)).second));
839     }
841     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
844 /**
845  *  \brief Apply a stretch to a set of points and snap such that the direction of the stretch is preserved
846  *
847  *  \param point_type Category of points to which the source point belongs: node or bounding box.
848  *  \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.
849  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
850  *  \param s Proposed stretch; the final stretch can only be calculated after snapping has occurred
851  *  \param o Origin of the stretching
852  *  \param d Dimension in which to apply proposed stretch.
853  *  \param u true if the stretch should be uniform (i.e. to be applied equally in both dimensions)
854  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
855  */
857 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::SnapPreferences::PointType point_type,
858                                                             std::vector<std::pair<Geom::Point, int> > const &p,
859                                                             Geom::Point const &pointer,
860                                                             Geom::Coord const &s,
861                                                             Geom::Point const &o,
862                                                             Geom::Dim2 d,
863                                                             bool u) const
865     if (p.size() == 1) {
866         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u), (p.at(0)).second));
867     }
869     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
872 /**
873  *  \brief Apply a skew to a set of points and snap such that the direction of the skew is preserved
874  *
875  *  \param point_type Category of points to which the source point belongs: node or bounding box.
876  *  \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.
877  *  \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
878  *  \param constraint The direction or line along which snapping must occur.
879  *  \param s Proposed skew; the final skew can only be calculated after snapping has occurred
880  *  \param o Origin of the proposed skew
881  *  \param d Dimension in which to apply proposed skew.
882  *  \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
883  */
885 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::SnapPreferences::PointType point_type,
886                                                  std::vector<std::pair<Geom::Point, int> > const &p,
887                                                  Geom::Point const &pointer,
888                                                  Inkscape::Snapper::ConstraintLine const &constraint,
889                                                  Geom::Point const &s,
890                                                  Geom::Point const &o,
891                                                  Geom::Dim2 d) const
893     // "s" contains skew factor in s[0], and scale factor in s[1]
895     // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
896     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
897     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
898     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
899     // of bounding boxes is not allowed here.
900     g_assert(!(point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX));
902     if (p.size() == 1) {
903         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SKEW, s, o, d, false), (p.at(0)).second));
904     }
906     return _snapTransformed(point_type, p, pointer, true, constraint, SKEW, s, o, d, false);
909 /**
910  * \brief Given a set of possible snap targets, find the best target (which is not necessarily
911  * also the nearest target), and show the snap indicator if requested
912  *
913  * \param p Current position of the snap source
914  * \param source_type Detailed description of the source type, will be used by the snap indicator
915  * \param sc A structure holding all snap targets that have been found so far
916  * \param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation.
917  * \param noCurves If true, then do consider snapping to intersections of curves, but not to the curves themself
918  * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
919  */
921 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p,
922                                                  Inkscape::SnapSourceType const source_type,
923                                                  SnappedConstraints &sc,
924                                                  bool constrained,
925                                                  bool noCurves) const
928     /*
929     std::cout << "Type and number of snapped constraints: " << std::endl;
930     std::cout << "  Points      : " << sc.points.size() << std::endl;
931     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
932     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
933     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
934     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
935     */
937     // Store all snappoints
938     std::list<Inkscape::SnappedPoint> sp_list;
940     // search for the closest snapped point
941     Inkscape::SnappedPoint closestPoint;
942     if (getClosestSP(sc.points, closestPoint)) {
943         sp_list.push_back(closestPoint);
944     }
946     // search for the closest snapped curve
947     if (!noCurves) {
948         Inkscape::SnappedCurve closestCurve;
949         if (getClosestCurve(sc.curves, closestCurve)) {
950             sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
951         }
952     }
954     if (snapprefs.getSnapIntersectionCS()) {
955         // search for the closest snapped intersection of curves
956         Inkscape::SnappedPoint closestCurvesIntersection;
957         if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection, _desktop->dt2doc())) {
958             closestCurvesIntersection.setSource(source_type);
959             sp_list.push_back(closestCurvesIntersection);
960         }
961     }
963     // search for the closest snapped grid line
964     Inkscape::SnappedLine closestGridLine;
965     if (getClosestSL(sc.grid_lines, closestGridLine)) {
966         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
967     }
969     // search for the closest snapped guide line
970     Inkscape::SnappedLine closestGuideLine;
971     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
972         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
973     }
975     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
976     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
978     // When doing a constrained snap however, we're already at an intersection of the constrained line and
979     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
980     // no need to look for additional intersections
981     if (!constrained) {
982         // search for the closest snapped intersection of grid lines
983         Inkscape::SnappedPoint closestGridPoint;
984         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
985             closestGridPoint.setSource(source_type);
986             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
987             sp_list.push_back(closestGridPoint);
988         }
990         // search for the closest snapped intersection of guide lines
991         Inkscape::SnappedPoint closestGuidePoint;
992         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
993             closestGuidePoint.setSource(source_type);
994             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
995             sp_list.push_back(closestGuidePoint);
996         }
998         // search for the closest snapped intersection of grid with guide lines
999         if (snapprefs.getSnapIntersectionGG()) {
1000             Inkscape::SnappedPoint closestGridGuidePoint;
1001             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
1002                 closestGridGuidePoint.setSource(source_type);
1003                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
1004                 sp_list.push_back(closestGridGuidePoint);
1005             }
1006         }
1007     }
1009     // now let's see which snapped point gets a thumbs up
1010     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPSOURCE_UNDEFINED, 0, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
1011     // std::cout << "Finding the best snap..." << std::endl;
1012     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
1013         // first find out if this snapped point is within snapping range
1014         // std::cout << "sp = " << from_2geom((*i).getPoint());
1015         if ((*i).getSnapDistance() <= (*i).getTolerance()) {
1016             // if it's the first point, or if it is closer than the best snapped point so far
1017             if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
1018                 // then prefer this point over the previous one
1019                 bestSnappedPoint = *i;
1020             }
1021         }
1022         // std::cout << std::endl;
1023     }
1025     // Update the snap indicator, if requested
1026     if (_snapindicator) {
1027         if (bestSnappedPoint.getSnapped()) {
1028             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
1029         } else {
1030             _desktop->snapindicator->remove_snaptarget();
1031         }
1032     }
1034     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
1035     return bestSnappedPoint;
1038 /**
1039  * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1040  * to ignore and toggling the snap indicator
1041  *
1042  * There are two overloaded setup() methods, of which this one only allows for a single item to be ignored
1043  * whereas the other one will take a list of items to ignore
1044  *
1045  * \param desktop Reference to the desktop to which this snap manager is attached
1046  * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1047  * \param item_to_ignore This item will not be snapped to, e.g. the item that is currently being dragged. This avoids "self-snapping"
1048  * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1049  * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1050  * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1051  * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1052  */
1054 void SnapManager::setup(SPDesktop const *desktop,
1055                         bool snapindicator,
1056                         SPItem const *item_to_ignore,
1057                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
1058                         SPGuide *guide_to_ignore)
1060     g_assert(desktop != NULL);
1061     _item_to_ignore = item_to_ignore;
1062     _items_to_ignore = NULL;
1063     _desktop = desktop;
1064     _snapindicator = snapindicator;
1065     _unselected_nodes = unselected_nodes;
1066     _guide_to_ignore = guide_to_ignore;
1069 /**
1070  * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1071  * to ignore and toggling the snap indicator
1072  *
1073  * There are two overloaded setup() methods, of which the other one only allows for a single item to be ignored
1074  * whereas this one will take a list of items to ignore
1075  *
1076  * \param desktop Reference to the desktop to which this snap manager is attached
1077  * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1078  * \param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping"
1079  * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1080  * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1081  * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1082  * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1083  */
1085 void SnapManager::setup(SPDesktop const *desktop,
1086                         bool snapindicator,
1087                         std::vector<SPItem const *> &items_to_ignore,
1088                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
1089                         SPGuide *guide_to_ignore)
1091     g_assert(desktop != NULL);
1092     _item_to_ignore = NULL;
1093     _items_to_ignore = &items_to_ignore;
1094     _desktop = desktop;
1095     _snapindicator = snapindicator;
1096     _unselected_nodes = unselected_nodes;
1097     _guide_to_ignore = guide_to_ignore;
1100 SPDocument *SnapManager::getDocument() const
1102     return _named_view->document;
1105 /**
1106  * \brief Takes an untransformed point, applies the given transformation, and returns the transformed point. Eliminates lots of duplicated code
1107  *
1108  * \param p The untransformed position of the point, paired with an identifier of the type of the snap source.
1109  * \param transformation_type Type of transformation to apply.
1110  * \param transformation Mathematical description of the transformation; details depend on the type.
1111  * \param origin Origin of the transformation, if applicable.
1112  * \param dim Dimension to which the transformation applies, if applicable.
1113  * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
1114  * \return The position of the point after transformation
1115  */
1117 Geom::Point SnapManager::_transformPoint(std::pair<Geom::Point, int> const &p,
1118                                         Transformation const transformation_type,
1119                                         Geom::Point const &transformation,
1120                                         Geom::Point const &origin,
1121                                         Geom::Dim2 const dim,
1122                                         bool const uniform) const
1124     /* Work out the transformed version of this point */
1125     Geom::Point transformed;
1126     switch (transformation_type) {
1127         case TRANSLATION:
1128             transformed = p.first + transformation;
1129             break;
1130         case SCALE:
1131             transformed = (p.first - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
1132             break;
1133         case STRETCH:
1134         {
1135             Geom::Scale s(1, 1);
1136             if (uniform)
1137                 s[Geom::X] = s[Geom::Y] = transformation[dim];
1138             else {
1139                 s[dim] = transformation[dim];
1140                 s[1 - dim] = 1;
1141             }
1142             transformed = ((p.first - origin) * s) + origin;
1143             break;
1144         }
1145         case SKEW:
1146             // Apply the skew factor
1147             transformed[dim] = (p.first)[dim] + transformation[0] * ((p.first)[1 - dim] - origin[1 - dim]);
1148             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
1149             // Apply that scale factor here
1150             transformed[1-dim] = (p.first - origin)[1 - dim] * transformation[1] + origin[1 - dim];
1151             break;
1152         default:
1153             g_assert_not_reached();
1154     }
1156     return transformed;
1159 /**
1160  * \brief Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol
1161  *
1162  * \param point_type Category of points to which the source point belongs: node, guide or bounding box
1163  * \param p The transformed position of the source point, paired with an identifier of the type of the snap source.
1164  */
1166 void SnapManager::_displaySnapsource(Inkscape::SnapPreferences::PointType point_type, std::pair<Geom::Point, int> const &p) const {
1168     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1169     if (prefs->getBool("/options/snapclosestonly/value")) {
1170         bool p_is_a_node = point_type & Inkscape::SnapPreferences::SNAPPOINT_NODE;
1171         bool p_is_a_bbox = point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
1172         if (snapprefs.getSnapEnabledGlobally() && ((p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
1173             _desktop->snapindicator->set_new_snapsource(p);
1174         } else {
1175             _desktop->snapindicator->remove_snapsource();
1176         }
1177     }
1180 /*
1181   Local Variables:
1182   mode:c++
1183   c-file-style:"stroustrup"
1184   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1185   indent-tabs-mode:nil
1186   fill-column:99
1187   End:
1188 */
1189 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :