Code

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