Code

394bc7f912bb6ba5b2ea524481806b1eaceee763
[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-2008 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 <libnr/nr-point-fns.h>
29 #include <libnr/nr-scale-ops.h>
30 #include <libnr/nr-values.h>
32 #include "display/canvas-grid.h"
33 #include "display/snap-indicator.h"
35 #include "inkscape.h"
36 #include "desktop.h"
37 #include "sp-guide.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     _named_view(v),
50     _include_item_center(false),
51     _snap_enabled_globally(true)
52 {    
53 }
56 /**
57  *  \return List of snappers that we use.
58  */
59 SnapManager::SnapperList 
60 SnapManager::getSnappers() const
61 {
62     SnapManager::SnapperList s;
63     s.push_back(&guide);
64     s.push_back(&object);
66     SnapManager::SnapperList gs = getGridSnappers();
67     s.splice(s.begin(), gs);
69     return s;
70 }
72 /**
73  *  \return List of gridsnappers that we use.
74  */
75 SnapManager::SnapperList 
76 SnapManager::getGridSnappers() const
77 {
78     SnapperList s;
80     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
81     SPDesktop* desktop = SP_ACTIVE_DESKTOP;
82     if (desktop && desktop->gridsEnabled()) {
83         for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
84             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
85             s.push_back(grid->snapper);
86         }
87     }
89     return s;
90 }
92 /**
93  * \return true if one of the snappers will try to snap something.
94  */
96 bool SnapManager::SomeSnapperMightSnap() const
97 {
98     if (!_snap_enabled_globally) {
99         return false;
100     }
101     
102     SnapperList const s = getSnappers();
103     SnapperList::const_iterator i = s.begin();
104     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
105         i++;
106     }
107     
108     return (i != s.end());
111 /*
112  *  The snappers have too many parameters to adjust individually. Therefore only
113  *  two snapping modes are presented to the user: snapping bounding box corners (to 
114  *  other bounding boxes, grids or guides), and/or snapping nodes (to other nodes,
115  *  paths, grids or guides). To select either of these modes (or both), use the 
116  *  methods defined below: setSnapModeBBox() and setSnapModeNode().
117  * 
118  * */
121 void SnapManager::setSnapModeBBox(bool enabled)
123     //The default values are being set in sp_namedview_set() (in sp-namedview.cpp)
124     guide.setSnapFrom(Inkscape::Snapper::SNAPPOINT_BBOX, enabled);
125     
126     for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
127         Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
128         grid->snapper->setSnapFrom(Inkscape::Snapper::SNAPPOINT_BBOX, enabled);
129     }
130     
131     object.setSnapFrom(Inkscape::Snapper::SNAPPOINT_BBOX, enabled);
132     //object.setSnapToBBoxNode(enabled); // On second thought, these should be controlled
133     //object.setSnapToBBoxPath(enabled); // separately by the snapping prefs dialog
134     object.setStrictSnapping(true); //don't snap bboxes to nodes/paths and vice versa    
137 bool SnapManager::getSnapModeBBox() const
139     return guide.getSnapFrom(Inkscape::Snapper::SNAPPOINT_BBOX);
142 void SnapManager::setSnapModeNode(bool enabled)
144     guide.setSnapFrom(Inkscape::Snapper::SNAPPOINT_NODE, enabled);
145     
146     for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
147         Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
148         grid->snapper->setSnapFrom(Inkscape::Snapper::SNAPPOINT_NODE, enabled);
149     }
150         
151     object.setSnapFrom(Inkscape::Snapper::SNAPPOINT_NODE, enabled);
152     //object.setSnapToItemNode(enabled); // On second thought, these should be controlled
153     //object.setSnapToItemPath(enabled); // separately by the snapping prefs dialog 
154     object.setStrictSnapping(true);
157 bool SnapManager::getSnapModeNode() const
159     return guide.getSnapFrom(Inkscape::Snapper::SNAPPOINT_NODE);
162 void SnapManager::setSnapModeGuide(bool enabled)
164     object.setSnapFrom(Inkscape::Snapper::SNAPPOINT_GUIDE, enabled);
167 bool SnapManager::getSnapModeGuide() const
169     return object.getSnapFrom(Inkscape::Snapper::SNAPPOINT_GUIDE);
172 /**
173  *  Try to snap a point to any of the specified snappers.
174  *
175  *  \param point_type Type of point.
176  *  \param p Point.
177  *  \param first_point If true then this point is the first one from a whole bunch of points 
178  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation 
179  *  \param snappers List of snappers to try to snap to
180  *  \return Snapped point.
181  */
183 void SnapManager::freeSnapReturnByRef(Inkscape::Snapper::PointType point_type,
184                                              Geom::Point &p,
185                                              bool first_point,
186                                              boost::optional<Geom::Rect> const &bbox_to_snap) const
188     Inkscape::SnappedPoint const s = freeSnap(point_type, p, first_point, bbox_to_snap);                                                            
189     s.getPoint(p);
192 /**
193  *  Try to snap a point to any of the specified snappers.
194  *
195  *  \param point_type Type of point.
196  *  \param p Point.
197  *  \param first_point If true then this point is the first one from a whole bunch of points 
198  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation 
199  *  \param snappers List of snappers to try to snap to
200  *  \return Snapped point.
201  */
203 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::Snapper::PointType point_type,
204                                              Geom::Point const &p,
205                                              bool first_point,
206                                              boost::optional<Geom::Rect> const &bbox_to_snap) const
208     if (!SomeSnapperMightSnap()) {
209         return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
210     }
211     
212     std::vector<SPItem const *> *items_to_ignore;
213     if (_item_to_ignore) { // If we have only a single item to ignore 
214         // then build a list containing this single item; 
215         // This single-item list will prevail over any other _items_to_ignore list, should that exist
216         items_to_ignore = new std::vector<SPItem const *>;
217         items_to_ignore->push_back(_item_to_ignore);
218     } else {
219         items_to_ignore = _items_to_ignore;
220     }
221     
222     SnappedConstraints sc;
223     SnapperList const snappers = getSnappers();
224     
225     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
226         (*i)->freeSnap(sc, point_type, p, first_point, bbox_to_snap, items_to_ignore, _unselected_nodes);
227     }
228     
229     if (_item_to_ignore) {
230         delete items_to_ignore;   
231     }
232     
233     return findBestSnap(p, sc, false);
236 // When pasting, we would like to snap to the grid. Problem is that we don't know which nodes were
237 // aligned to the grid at the time of copying, so we don't know which nodes to snap. If we'd snap an
238 // unaligned node to the grid, previously aligned nodes would become unaligned. That's undesirable.
239 // Instead we will make sure that the offset between the source and the copy is a multiple of the grid
240 // pitch. If the source was aligned, then the copy will therefore also be aligned
241 // PS: Wether we really find a multiple also depends on the snapping range!
242 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
244     if (!_snap_enabled_globally) 
245         return t;
246     
247     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
248     SPDesktop* desktop = SP_ACTIVE_DESKTOP;
249     
250     if (desktop && desktop->gridsEnabled()) {
251         bool success = false;
252         Geom::Point nearest_multiple; 
253         Geom::Coord nearest_distance = NR_HUGE;
254         
255         // It will snap to the grid for which we find the closest snap. This might be a different
256         // grid than to which the objects were initially aligned. I don't see an easy way to fix 
257         // this, so when using multiple grids one can get unexpected results 
258         
259         // Cannot use getGridSnappers() because we need both the grids AND their snappers
260         // Therefor we iterate through all grids manually        
261         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
262             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
263             const Inkscape::Snapper* snapper = grid->snapper; 
264             if (snapper && snapper->ThisSnapperMightSnap()) {
265                 // To find the nearest multiple of the grid pitch for a given translation t, we 
266                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
267                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
268                 // in the translation t
269                 Geom::Point const t_offset = from_2geom(t) + grid->origin;
270                 SnappedConstraints sc;    
271                 // Only the first three parameters are being used for grid snappers
272                 snapper->freeSnap(sc, Inkscape::Snapper::SNAPPOINT_NODE, t_offset, TRUE, boost::optional<Geom::Rect>(), NULL, NULL);
273                 // Find the best snap for this grid, including intersections of the grid-lines
274                 Inkscape::SnappedPoint s = findBestSnap(t_offset, sc, false);
275                 if (s.getSnapped() && (s.getDistance() < nearest_distance)) {
276                     success = true;
277                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
278                     nearest_distance = s.getDistance();
279                 }
280             }
281         }
282         
283         if (success) 
284             return nearest_multiple;
285     }
286     
287     return t;
290 /**
291  *  Try to snap a point to any interested snappers.  A snap will only occur along
292  *  a line described by a Inkscape::Snapper::ConstraintLine.
293  *
294  *  \param point_type Type of point.
295  *  \param p Point.
296  *  \param first_point If true then this point is the first one from a whole bunch of points 
297  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation 
298  *  \param constraint Constraint line.
299  *  \return Snapped point.
300  */
302 void SnapManager::constrainedSnapReturnByRef(Inkscape::Snapper::PointType point_type,
303                                                     Geom::Point &p,
304                                                     Inkscape::Snapper::ConstraintLine const &constraint,
305                                                     bool first_point,
306                                                     boost::optional<Geom::Rect> const &bbox_to_snap) const
308     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, constraint, first_point, bbox_to_snap);                                                            
309     s.getPoint(p);
312 /**
313  *  Try to snap a point to any interested snappers.  A snap will only occur along
314  *  a line described by a Inkscape::Snapper::ConstraintLine.
315  *
316  *  \param point_type Type of point.
317  *  \param p Point.
318  *  \param first_point If true then this point is the first one from a whole bunch of points 
319  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation 
320  *  \param constraint Constraint line.
321  *  \return Snapped point.
322  */
324 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::Snapper::PointType point_type,
325                                                     Geom::Point const &p,
326                                                     Inkscape::Snapper::ConstraintLine const &constraint,
327                                                     bool first_point,
328                                                     boost::optional<Geom::Rect> const &bbox_to_snap) const
330     if (!SomeSnapperMightSnap()) {
331         return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
332     }
333     
334     std::vector<SPItem const *> *items_to_ignore;
335     if (_item_to_ignore) { // If we have only a single item to ignore 
336         // then build a list containing this single item; 
337         // This single-item list will prevail over any other _items_to_ignore list, should that exist
338         items_to_ignore = new std::vector<SPItem const *>;
339         items_to_ignore->push_back(_item_to_ignore);
340     } else {
341         items_to_ignore = _items_to_ignore;
342     }
343     
344     SnappedConstraints sc;    
345     SnapperList const snappers = getSnappers();
346     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
347         (*i)->constrainedSnap(sc, point_type, p, first_point, bbox_to_snap, constraint, items_to_ignore);
348     }
349     
350     if (_item_to_ignore) {
351         delete items_to_ignore;   
352     }
353     
354     return findBestSnap(p, sc, true);
357 void SnapManager::guideSnap(Geom::Point &p, Geom::Point const &guide_normal) const
359     // This method is used to snap a guide to nodes, while dragging the guide around
360     
361     if (!(object.GuidesMightSnap() && _snap_enabled_globally)) {
362         return;
363     }
364     
365     SnappedConstraints sc;
366     object.guideSnap(sc, p, guide_normal);
367     
368     Inkscape::SnappedPoint const s = findBestSnap(p, sc, false);
369     s.getPoint(p);
373 /**
374  *  Main internal snapping method, which is called by the other, friendlier, public
375  *  methods.  It's a bit hairy as it has lots of parameters, but it saves on a lot
376  *  of duplicated code.
377  *
378  *  \param type Type of points being snapped.
379  *  \param points List of points to snap.
380  *  \param constrained true if the snap is constrained.
381  *  \param constraint Constraint line to use, if `constrained' is true, otherwise undefined.
382  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
383  *  \param transformation Description of the transformation; details depend on the type.
384  *  \param origin Origin of the transformation, if applicable.
385  *  \param dim Dimension of the transformation, if applicable.
386  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
387  */
389 Inkscape::SnappedPoint SnapManager::_snapTransformed(
390     Inkscape::Snapper::PointType type,
391     std::vector<Geom::Point> const &points,
392     bool constrained,
393     Inkscape::Snapper::ConstraintLine const &constraint,
394     Transformation transformation_type,
395     Geom::Point const &transformation,
396     Geom::Point const &origin,
397     Geom::Dim2 dim,
398     bool uniform) const
400     /* We have a list of points, which we are proposing to transform in some way.  We need to see
401     ** if any of these points, when transformed, snap to anything.  If they do, we return the
402     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
403     */
405     /* Quick check to see if we have any snappers that are enabled
406     ** Also used to globally disable all snapping 
407     */
408     if (SomeSnapperMightSnap() == false) {
409         g_assert(points.size() > 0);
410         return Inkscape::SnappedPoint();
411     }
412     
413     std::vector<Geom::Point> transformed_points;
414     Geom::Rect bbox;
415     
416     for (std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
418         /* Work out the transformed version of this point */
419         Geom::Point transformed;
420         switch (transformation_type) {
421             case TRANSLATION:
422                 transformed = *i + transformation;
423                 break;
424             case SCALE:
425                 transformed = (*i - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
426                 break;
427             case STRETCH:
428             {
429                 Geom::Scale s(1, 1);
430                 if (uniform)
431                     s[Geom::X] = s[Geom::Y] = transformation[dim];
432                 else {
433                     s[dim] = transformation[dim];
434                     s[1 - dim] = 1;
435                 }
436                 transformed = ((*i - origin) * s) + origin;
437                 break;
438             }
439             case SKEW:
440                 // Apply the skew factor
441                 transformed[dim] = (*i)[dim] + transformation[0] * ((*i)[1 - dim] - origin[1 - dim]);
442                 // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
443                 // Apply that scale factor here
444                 transformed[1-dim] = (*i - origin)[1 - dim] * transformation[1] + origin[1 - dim];
445                 break;
446             default:
447                 g_assert_not_reached();
448         }
449         
450         // add the current transformed point to the box hulling all transformed points
451         if (i == points.begin()) {
452             bbox = Geom::Rect(transformed, transformed);    
453         } else {
454             bbox.expandTo(transformed);
455         }
456         
457         transformed_points.push_back(transformed);
458     }    
459     
460     /* The current best transformation */
461     Geom::Point best_transformation = transformation;
463     /* The current best metric for the best transformation; lower is better, NR_HUGE
464     ** means that we haven't snapped anything.
465     */
466     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
467     Inkscape::SnappedPoint best_snapped_point;
468     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
469     g_assert(best_snapped_point.getAtIntersection() == false);
471     std::vector<Geom::Point>::const_iterator j = transformed_points.begin();
473     // std::cout << std::endl;
474     for (std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
475         
476         /* Snap it */        
477         Inkscape::SnappedPoint snapped_point;
478                 
479         if (constrained) {    
480             Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
481             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
482                 // When uniformly scaling, each point will have its own unique constraint line,
483                 // running from the scaling origin to the original untransformed point. We will
484                 // calculate that line here 
485                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, (*i) - origin);
486             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
487                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i), component_vectors[dim]);
488             } else if (transformation_type == TRANSLATION) {
489                 // When doing a constrained translation, all points will move in the same direction, i.e.
490                 // either horizontally or vertically. The lines along which they move are therefore all
491                 // parallel, but might not be colinear. Therefore we will have to set the point through
492                 // which the constraint-line runs here, for each point individually. 
493                 dedicated_constraint.setPoint(*i);
494             } // else: leave the original constraint, e.g. for skewing 
495             if (transformation_type == SCALE && !uniform) {
496                 g_warning("Non-uniform constrained scaling is not supported!");   
497             }
498             snapped_point = constrainedSnap(type, *j, dedicated_constraint, i == points.begin(), bbox);
499         } else {
500             snapped_point = freeSnap(type, *j, i == points.begin(), bbox);
501         }
503         Geom::Point result;
504         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
505         
506         if (snapped_point.getSnapped()) {
507             /* We snapped.  Find the transformation that describes where the snapped point has
508             ** ended up, and also the metric for this transformation.
509             */
510             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
511             Geom::Point const b = (*i - origin); // vector to original point
512             
513             switch (transformation_type) {
514                 case TRANSLATION:
515                     result = snapped_point.getPoint() - *i;
516                     /* Consider the case in which a box is almost aligned with a grid in both 
517                      * horizontal and vertical directions. The distance to the intersection of
518                      * the grid lines will always be larger then the distance to a single grid
519                      * line. If we prefer snapping to an intersection instead of to a single 
520                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
521                      * snapped distance will be used as a metric. Please note that the snapped
522                      * distance is defined as the distance to the nearest line of the intersection,
523                      * and not to the intersection itself! 
524                      */
525                     // Only for translations, the relevant metric will be the real snapped distance,
526                     // so we don't have to do anything special here
527                     break;
528                 case SCALE:
529                 {
530                     result = Geom::Point(NR_HUGE, NR_HUGE);
531                     // If this point *i is horizontally or vertically aligned with
532                     // the origin of the scaling, then it will scale purely in X or Y 
533                     // We can therefore only calculate the scaling in this direction
534                     // and the scaling factor for the other direction should remain
535                     // untouched (unless scaling is uniform ofcourse)
536                     for (int index = 0; index < 2; index++) {
537                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
538                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
539                                 result[index] = a[index] / b[index]; // then calculate it!
540                             }
541                             // we might leave result[1-index] = NR_HUGE
542                             // if scaling didn't occur in the other direction
543                         }
544                     }
545                     // Compare the resulting scaling with the desired scaling
546                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
547                     break;
548                 }
549                 case STRETCH:
550                     result = Geom::Point(NR_HUGE, NR_HUGE);
551                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
552                         result[dim] = a[dim] / b[dim];
553                         result[1-dim] = uniform ? result[dim] : 1;
554                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
555                         if (uniform && fabs(b[1-dim]) > 1e-6) {
556                            result[1-dim] = a[1-dim] / b[1-dim];
557                            result[dim] = result[1-dim];
558                         }
559                     }
560                     // Store the metric for this transformation as a virtual distance
561                     snapped_point.setDistance(std::abs(result[dim] - transformation[dim]));
562                     snapped_point.setSecondDistance(NR_HUGE);
563                     break;
564                 case SKEW:
565                     result[0] = (snapped_point.getPoint()[dim] - (*i)[dim]) / ((*i)[1 - dim] - origin[1 - dim]); // skew factor
566                     result[1] = transformation[1]; // scale factor
567                     // Store the metric for this transformation as a virtual distance
568                     snapped_point.setDistance(std::abs(result[0] - transformation[0])); 
569                     snapped_point.setSecondDistance(NR_HUGE);
570                     break;
571                 default:
572                     g_assert_not_reached();
573             }
574             
575             // When scaling, we're considering the best transformation in each direction separately. We will have a metric in each
576             // direction, whereas for all other transformation we only a single one-dimensional metric. That's why we need to handle
577             // the scaling metric differently
578             if (transformation_type == SCALE) {
579                 for (int index = 0; index < 2; index++) {
580                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
581                         best_transformation[index] = result[index];
582                         best_scale_metric[index] = fabs(scale_metric[index]);
583                         // When scaling, we're considering the best transformation in each direction separately
584                         // Therefore two different snapped points might together make a single best transformation
585                         // We will however return only a single snapped point (e.g. to display the snapping indicator)   
586                         best_snapped_point = snapped_point;
587                         // std::cout << "SEL ";
588                     } // else { std::cout << "    ";}
589                 }
590                 if (uniform) {
591                     if (best_scale_metric[0] < best_scale_metric[1]) {
592                         best_transformation[1] = best_transformation[0];
593                         best_scale_metric[1] = best_scale_metric[0]; 
594                     } else {
595                         best_transformation[0] = best_transformation[1];
596                         best_scale_metric[0] = best_scale_metric[1];
597                     }
598                 }
599             } else { // For all transformations other than scaling
600                 if (best_snapped_point.isOtherOneBetter(snapped_point)) {
601                     best_transformation = result;
602                     best_snapped_point = snapped_point;                    
603                 }                
604             }
605         }
606         
607         j++;
608     }
609     
610     Geom::Coord best_metric;
611     if (transformation_type == SCALE) {
612         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
613         for (int index = 0; index < 2; index++) {
614             if (best_transformation[index] == NR_HUGE) {
615                 if (uniform && best_transformation[1-index] < NR_HUGE) {
616                     best_transformation[index] = best_transformation[1-index];
617                 } else {
618                     best_transformation[index] = transformation[index];    
619                 }
620             }
621         }
622         best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
623     } else { // For all transformations other than scaling
624         best_metric = best_snapped_point.getDistance();        
625     }
626     
627     best_snapped_point.setTransformation(best_transformation);
628     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
629     // These rounding errors might be caused by NRRects, see bug #1584301    
630     best_snapped_point.setDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
631     return best_snapped_point;
635 /**
636  *  Try to snap a list of points to any interested snappers after they have undergone
637  *  a translation.
638  *
639  *  \param point_type Type of points.
640  *  \param p Points.
641  *  \param tr Proposed translation.
642  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
643  */
645 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::Snapper::PointType point_type,
646                                                         std::vector<Geom::Point> const &p,
647                                                         Geom::Point const &tr) const
649     return _snapTransformed(point_type, p, false, Geom::Point(), TRANSLATION, tr, Geom::Point(), Geom::X, false);
653 /**
654  *  Try to snap a list of points to any interested snappers after they have undergone a
655  *  translation.  A snap will only occur along a line described by a
656  *  Inkscape::Snapper::ConstraintLine.
657  *
658  *  \param point_type Type of points.
659  *  \param p Points.
660  *  \param constraint Constraint line.
661  *  \param tr Proposed translation.
662  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
663  */
665 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::Snapper::PointType point_type,
666                                                                std::vector<Geom::Point> const &p,
667                                                                Inkscape::Snapper::ConstraintLine const &constraint,
668                                                                Geom::Point const &tr) const
670     return _snapTransformed(point_type, p, true, constraint, TRANSLATION, tr, Geom::Point(), Geom::X, false);
674 /**
675  *  Try to snap a list of points to any interested snappers after they have undergone
676  *  a scale.
677  *
678  *  \param point_type Type of points.
679  *  \param p Points.
680  *  \param s Proposed scale.
681  *  \param o Origin of proposed scale.
682  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
683  */
685 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::Snapper::PointType point_type,
686                                                   std::vector<Geom::Point> const &p,
687                                                   Geom::Scale const &s,
688                                                   Geom::Point const &o) const
690     return _snapTransformed(point_type, p, false, Geom::Point(), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
694 /**
695  *  Try to snap a list of points to any interested snappers after they have undergone
696  *  a scale.  A snap will only occur along a line described by a
697  *  Inkscape::Snapper::ConstraintLine.
698  *
699  *  \param point_type Type of points.
700  *  \param p Points.
701  *  \param s Proposed scale.
702  *  \param o Origin of proposed scale.
703  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
704  */
706 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::Snapper::PointType point_type,
707                                                          std::vector<Geom::Point> const &p,
708                                                          Geom::Scale const &s,
709                                                          Geom::Point const &o) const
711     // When constrained scaling, only uniform scaling is supported.
712     return _snapTransformed(point_type, p, true, Geom::Point(), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
716 /**
717  *  Try to snap a list of points to any interested snappers after they have undergone
718  *  a stretch.
719  *
720  *  \param point_type Type of points.
721  *  \param p Points.
722  *  \param s Proposed stretch.
723  *  \param o Origin of proposed stretch.
724  *  \param d Dimension in which to apply proposed stretch.
725  *  \param u true if the stretch should be uniform (ie to be applied equally in both dimensions)
726  *  \return Snapped stretch, if a snap occurred, and a flag indicating whether a snap occurred.
727  */
729 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::Snapper::PointType point_type,
730                                                             std::vector<Geom::Point> const &p,
731                                                             Geom::Coord const &s,
732                                                             Geom::Point const &o,
733                                                             Geom::Dim2 d,
734                                                             bool u) const
736    return _snapTransformed(point_type, p, true, Geom::Point(), STRETCH, Geom::Point(s, s), o, d, u);
740 /**
741  *  Try to snap a list of points to any interested snappers after they have undergone
742  *  a skew.
743  *
744  *  \param point_type Type of points.
745  *  \param p Points.
746  *  \param s Proposed skew.
747  *  \param o Origin of proposed skew.
748  *  \param d Dimension in which to apply proposed skew.
749  *  \return Snapped skew, if a snap occurred, and a flag indicating whether a snap occurred.
750  */
752 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::Snapper::PointType point_type,
753                                                  std::vector<Geom::Point> const &p,
754                                                  Inkscape::Snapper::ConstraintLine const &constraint,
755                                                  Geom::Point const &s,  
756                                                  Geom::Point const &o,
757                                                  Geom::Dim2 d) const
759    // "s" contains skew factor in s[0], and scale factor in s[1]
760    return _snapTransformed(point_type, p, true, constraint, SKEW, s, o, d, false);
763 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p, SnappedConstraints &sc, bool constrained) const
765     
766     /*
767     std::cout << "Type and number of snapped constraints: " << std::endl;
768     std::cout << "  Points      : " << sc.points.size() << std::endl;
769     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
770     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
771     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
772     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
773     */
774     
775     // Store all snappoints
776     std::list<Inkscape::SnappedPoint> sp_list;
777     
778     // search for the closest snapped point
779     Inkscape::SnappedPoint closestPoint;
780     if (getClosestSP(sc.points, closestPoint)) {
781         sp_list.push_back(closestPoint);
782     } 
783     
784     // search for the closest snapped curve
785     Inkscape::SnappedCurve closestCurve;
786     if (getClosestCurve(sc.curves, closestCurve)) {    
787         sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
788     }
789     
790     if (_intersectionCS) {
791         // search for the closest snapped intersection of curves
792         Inkscape::SnappedPoint closestCurvesIntersection;
793         if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection)) {
794             sp_list.push_back(closestCurvesIntersection);
795         }
796     }    
798     // search for the closest snapped grid line
799     Inkscape::SnappedLine closestGridLine;
800     if (getClosestSL(sc.grid_lines, closestGridLine)) {    
801         closestGridLine.setTarget(Inkscape::SNAPTARGET_GRID);
802         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
803     }
804     
805     // search for the closest snapped guide line
806     Inkscape::SnappedLine closestGuideLine;
807     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
808         closestGuideLine.setTarget(Inkscape::SNAPTARGET_GUIDE);
809         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
810     }
811     
812     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
813     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path 
814     
815     // When doing a constrained snap however, we're already at an intersection of the constrained line and
816     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
817     // no need to look for additional intersections
818     if (!constrained) {
819         // search for the closest snapped intersection of grid lines
820         Inkscape::SnappedPoint closestGridPoint;
821         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
822             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
823             sp_list.push_back(closestGridPoint);
824         }
825         
826         // search for the closest snapped intersection of guide lines
827         Inkscape::SnappedPoint closestGuidePoint;
828         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
829             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
830             sp_list.push_back(closestGuidePoint);
831         }
832         
833         // search for the closest snapped intersection of grid with guide lines
834         if (_intersectionGG) {
835             Inkscape::SnappedPoint closestGridGuidePoint;
836             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
837                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
838                 sp_list.push_back(closestGridGuidePoint);
839             }
840         }
841     }
842     
843     // now let's see which snapped point gets a thumbs up
844     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
845     // std::cout << "Finding the best snap..." << std::endl;
846     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
847         // first find out if this snapped point is within snapping range
848         // std::cout << "sp = " << from_2geom((*i).getPoint());
849         if ((*i).getDistance() <= (*i).getTolerance()) {
850             // if it's the first point, or if it is closer than the best snapped point so far
851             if (i == sp_list.begin() || bestSnappedPoint.isOtherOneBetter(*i)) { 
852                 // then prefer this point over the previous one
853                 bestSnappedPoint = *i;
854             }
855         }
856         // std::cout << std::endl;
857     }    
858     
859     // Update the snap indicator, if requested
860     if (_snapindicator) {
861         if (bestSnappedPoint.getSnapped()) {
862             _desktop->snapindicator->set_new_snappoint(bestSnappedPoint);
863         } else {
864             _desktop->snapindicator->remove_snappoint();
865         }
866     }
867     
868     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << std::endl;
869     return bestSnappedPoint;         
872 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, SPItem const *item_to_ignore, std::vector<Geom::Point> *unselected_nodes)
874     g_assert(desktop != NULL);
875     _item_to_ignore = item_to_ignore;
876     _items_to_ignore = NULL;
877     _desktop = desktop;
878     _snapindicator = snapindicator;
879     _unselected_nodes = unselected_nodes;
882 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, std::vector<SPItem const *> &items_to_ignore, std::vector<Geom::Point> *unselected_nodes)
884     g_assert(desktop != NULL);
885     _item_to_ignore = NULL;
886     _items_to_ignore = &items_to_ignore;
887     _desktop = desktop;
888     _snapindicator = snapindicator;
889     _unselected_nodes = unselected_nodes;   
892 SPDocument *SnapManager::getDocument() const
894     return _named_view->document;
897 /*
898   Local Variables:
899   mode:c++
900   c-file-style:"stroustrup"
901   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
902   indent-tabs-mode:nil
903   fill-column:99
904   End:
905 */
906 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :