Code

Eliminate SP_ACTIVE_DESKTOP in the object-snapper
[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(v, 0),
48     object(v, 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);
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);
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::Coord best_metric = NR_HUGE;
467     Geom::Coord best_second_metric = NR_HUGE;
468     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
469     Inkscape::SnappedPoint best_snapped_point;
470     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
471     g_assert(best_snapped_point.getAtIntersection() == false);
473     std::vector<Geom::Point>::const_iterator j = transformed_points.begin();
475     // std::cout << std::endl;
476     for (std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
477         
478         /* Snap it */        
479         Inkscape::SnappedPoint snapped_point;
480                 
481         if (constrained) {    
482             Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
483             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
484                 // When uniformly scaling, each point will have its own unique constraint line,
485                 // running from the scaling origin to the original untransformed point. We will
486                 // calculate that line here 
487                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, (*i) - origin);
488             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
489                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i), component_vectors[dim]);
490             } else if (transformation_type == TRANSLATION) {
491                 // When doing a constrained translation, all points will move in the same direction, i.e.
492                 // either horizontally or vertically. The lines along which they move are therefore all
493                 // parallel, but might not be colinear. Therefore we will have to set the point through
494                 // which the constraint-line runs here, for each point individually. 
495                 dedicated_constraint.setPoint(*i);
496             } // else: leave the original constraint, e.g. for skewing 
497             if (transformation_type == SCALE && !uniform) {
498                 g_warning("Non-uniform constrained scaling is not supported!");   
499             }
500             snapped_point = constrainedSnap(type, *j, dedicated_constraint, i == points.begin(), bbox);
501         } else {
502             snapped_point = freeSnap(type, *j, i == points.begin(), bbox);
503         }
505         Geom::Point result;
506         Geom::Coord metric = NR_HUGE;
507         Geom::Coord second_metric = NR_HUGE;
508         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
509         
510         if (snapped_point.getSnapped()) {
511             /* We snapped.  Find the transformation that describes where the snapped point has
512             ** ended up, and also the metric for this transformation.
513             */
514             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
515             Geom::Point const b = (*i - origin); // vector to original point
516             
517             switch (transformation_type) {
518                 case TRANSLATION:
519                     result = snapped_point.getPoint() - *i;
520                     /* Consider the case in which a box is almost aligned with a grid in both 
521                      * horizontal and vertical directions. The distance to the intersection of
522                      * the grid lines will always be larger then the distance to a single grid
523                      * line. If we prefer snapping to an intersection instead of to a single 
524                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
525                      * snapped distance will be used as a metric. Please note that the snapped
526                      * distance is defined as the distance to the nearest line of the intersection,
527                      * and not to the intersection itself! 
528                      */
529                     metric = snapped_point.getDistance(); //used to be: metric = Geom::L2(result);
530                     second_metric = snapped_point.getSecondDistance();
531                     break;
532                 case SCALE:
533                 {
534                     result = Geom::Point(NR_HUGE, NR_HUGE);
535                     // If this point *i is horizontally or vertically aligned with
536                     // the origin of the scaling, then it will scale purely in X or Y 
537                     // We can therefore only calculate the scaling in this direction
538                     // and the scaling factor for the other direction should remain
539                     // untouched (unless scaling is uniform ofcourse)
540                     for (int index = 0; index < 2; index++) {
541                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
542                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
543                                 result[index] = a[index] / b[index]; // then calculate it!
544                             }
545                             // we might leave result[1-index] = NR_HUGE
546                             // if scaling didn't occur in the other direction
547                         }
548                     }
549                     // Compare the resulting scaling with the desired scaling
550                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
551                     break;
552                 }
553                 case STRETCH:
554                     result = Geom::Point(NR_HUGE, NR_HUGE);
555                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
556                         result[dim] = a[dim] / b[dim];
557                         result[1-dim] = uniform ? result[dim] : 1;
558                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
559                         if (uniform && fabs(b[1-dim]) > 1e-6) {
560                            result[1-dim] = a[1-dim] / b[1-dim];
561                            result[dim] = result[1-dim];
562                         }
563                     }
564                     metric = std::abs(result[dim] - transformation[dim]);
565                     break;
566                 case SKEW:
567                     result[0] = (snapped_point.getPoint()[dim] - (*i)[dim]) / ((*i)[1 - dim] - origin[1 - dim]); // skew factor
568                     result[1] = transformation[1]; // scale factor
569                     metric = std::abs(result[0] - transformation[0]);
570                     break;
571                 default:
572                     g_assert_not_reached();
573             }
574             
575             /* Note it if it's the best so far */
576             if (transformation_type == SCALE) {
577                 for (int index = 0; index < 2; index++) {
578                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
579                         best_transformation[index] = result[index];
580                         best_scale_metric[index] = fabs(scale_metric[index]);
581                         // When scaling, we're considering the best transformation in each direction separately
582                         // Therefore two different snapped points might together make a single best transformation
583                         // We will however return only a single snapped point (e.g. to display the snapping indicator)   
584                         best_snapped_point = snapped_point;
585                         // std::cout << "SEL ";
586                     } // else { std::cout << "    ";}
587                 }
588                 if (uniform) {
589                     if (best_scale_metric[0] < best_scale_metric[1]) {
590                         best_transformation[1] = best_transformation[0];
591                         best_scale_metric[1] = best_scale_metric[0]; 
592                     } else {
593                         best_transformation[0] = best_transformation[1];
594                         best_scale_metric[0] = best_scale_metric[1];
595                     }
596                 }
597                 best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
598                 // std::cout << "P_orig = " << (*i) << " | scale_metric = " << scale_metric << " | distance = " << snapped_point.getDistance() << " | P_snap = " << snapped_point.getPoint() << std::endl;
599             } else {
600                 bool const c1 = metric < best_metric;
601                 bool const c2 = metric == best_metric && snapped_point.getAtIntersection() == true && best_snapped_point.getAtIntersection() == false;
602                         bool const c3a = metric == best_metric && snapped_point.getAtIntersection() == true && best_snapped_point.getAtIntersection() == true;
603                 bool const c3b = second_metric < best_second_metric;
604                 bool const c4 = snapped_point.getAlwaysSnap() == true && best_snapped_point.getAlwaysSnap() == false;
605                 bool const c4n = snapped_point.getAlwaysSnap() == false && best_snapped_point.getAlwaysSnap() == true;
606                 
607                 if ((c1 || c2 || (c3a && c3b) || c4) && !c4n) {
608                     best_transformation = result;
609                     best_metric = metric;
610                     best_second_metric = second_metric;
611                     best_snapped_point = snapped_point; 
612                     // std::cout << "SEL ";
613                 } // else { std::cout << "    ";}
614                 // std::cout << "P_orig = " << (*i) << " | metric = " << metric << " | distance = " << snapped_point.getDistance() << " | second metric = " << second_metric << " | P_snap = " << snapped_point.getPoint() << std::endl;
615             }
616         }
617         
618         j++;
619     }
620     
621     if (transformation_type == SCALE) {
622         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
623         for (int index = 0; index < 2; index++) {
624             if (best_transformation[index] == NR_HUGE) {
625                 if (uniform && best_transformation[1-index] < NR_HUGE) {
626                         best_transformation[index] = best_transformation[1-index];
627                 } else {
628                         best_transformation[index] = transformation[index];     
629                 }
630             }
631         }
632     }
633     
634     best_snapped_point.setTransformation(best_transformation);
635     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
636     // These rounding errors might be caused by NRRects, see bug #1584301    
637     best_snapped_point.setDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
638     return best_snapped_point;
642 /**
643  *  Try to snap a list of points to any interested snappers after they have undergone
644  *  a translation.
645  *
646  *  \param point_type Type of points.
647  *  \param p Points.
648  *  \param tr Proposed translation.
649  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
650  */
652 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::Snapper::PointType point_type,
653                                                         std::vector<Geom::Point> const &p,
654                                                         Geom::Point const &tr) const
656     return _snapTransformed(point_type, p, false, Geom::Point(), TRANSLATION, tr, Geom::Point(), Geom::X, false);
660 /**
661  *  Try to snap a list of points to any interested snappers after they have undergone a
662  *  translation.  A snap will only occur along a line described by a
663  *  Inkscape::Snapper::ConstraintLine.
664  *
665  *  \param point_type Type of points.
666  *  \param p Points.
667  *  \param constraint Constraint line.
668  *  \param tr Proposed translation.
669  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
670  */
672 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::Snapper::PointType point_type,
673                                                                std::vector<Geom::Point> const &p,
674                                                                Inkscape::Snapper::ConstraintLine const &constraint,
675                                                                Geom::Point const &tr) const
677     return _snapTransformed(point_type, p, true, constraint, TRANSLATION, tr, Geom::Point(), Geom::X, false);
681 /**
682  *  Try to snap a list of points to any interested snappers after they have undergone
683  *  a scale.
684  *
685  *  \param point_type Type of points.
686  *  \param p Points.
687  *  \param s Proposed scale.
688  *  \param o Origin of proposed scale.
689  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
690  */
692 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::Snapper::PointType point_type,
693                                                   std::vector<Geom::Point> const &p,
694                                                   Geom::Scale const &s,
695                                                   Geom::Point const &o) const
697     return _snapTransformed(point_type, p, false, Geom::Point(), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
701 /**
702  *  Try to snap a list of points to any interested snappers after they have undergone
703  *  a scale.  A snap will only occur along a line described by a
704  *  Inkscape::Snapper::ConstraintLine.
705  *
706  *  \param point_type Type of points.
707  *  \param p Points.
708  *  \param s Proposed scale.
709  *  \param o Origin of proposed scale.
710  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
711  */
713 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::Snapper::PointType point_type,
714                                                          std::vector<Geom::Point> const &p,
715                                                          Geom::Scale const &s,
716                                                          Geom::Point const &o) const
718     // When constrained scaling, only uniform scaling is supported.
719     return _snapTransformed(point_type, p, true, Geom::Point(), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
723 /**
724  *  Try to snap a list of points to any interested snappers after they have undergone
725  *  a stretch.
726  *
727  *  \param point_type Type of points.
728  *  \param p Points.
729  *  \param s Proposed stretch.
730  *  \param o Origin of proposed stretch.
731  *  \param d Dimension in which to apply proposed stretch.
732  *  \param u true if the stretch should be uniform (ie to be applied equally in both dimensions)
733  *  \return Snapped stretch, if a snap occurred, and a flag indicating whether a snap occurred.
734  */
736 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::Snapper::PointType point_type,
737                                                             std::vector<Geom::Point> const &p,
738                                                             Geom::Coord const &s,
739                                                             Geom::Point const &o,
740                                                             Geom::Dim2 d,
741                                                             bool u) const
743    return _snapTransformed(point_type, p, true, Geom::Point(), STRETCH, Geom::Point(s, s), o, d, u);
747 /**
748  *  Try to snap a list of points to any interested snappers after they have undergone
749  *  a skew.
750  *
751  *  \param point_type Type of points.
752  *  \param p Points.
753  *  \param s Proposed skew.
754  *  \param o Origin of proposed skew.
755  *  \param d Dimension in which to apply proposed skew.
756  *  \return Snapped skew, if a snap occurred, and a flag indicating whether a snap occurred.
757  */
759 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::Snapper::PointType point_type,
760                                                  std::vector<Geom::Point> const &p,
761                                                  Inkscape::Snapper::ConstraintLine const &constraint,
762                                                  Geom::Point const &s,  
763                                                  Geom::Point const &o,
764                                                  Geom::Dim2 d) const
766    // "s" contains skew factor in s[0], and scale factor in s[1]
767    return _snapTransformed(point_type, p, true, constraint, SKEW, s, o, d, false);
770 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p, SnappedConstraints &sc, bool constrained) const
772     /*
773     std::cout << "Type and number of snapped constraints: " << std::endl;
774     std::cout << "  Points      : " << sc.points.size() << std::endl;
775     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
776     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
777     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
778     */
779         
780     // Store all snappoints
781     std::list<Inkscape::SnappedPoint> sp_list;
782     
783     // search for the closest snapped point
784     Inkscape::SnappedPoint closestPoint;
785     if (getClosestSP(sc.points, closestPoint)) {
786         sp_list.push_back(closestPoint);
787     } 
788     
789     // search for the closest snapped curve
790     Inkscape::SnappedCurve closestCurve;
791     if (getClosestCurve(sc.curves, closestCurve)) {    
792         sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
793     }
794     
795     if (_intersectionCS) {
796             // search for the closest snapped intersection of curves
797             Inkscape::SnappedPoint closestCurvesIntersection;
798             if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection)) {
799                 sp_list.push_back(closestCurvesIntersection);
800             }
801     }    
803     // search for the closest snapped grid line
804     Inkscape::SnappedLine closestGridLine;
805     if (getClosestSL(sc.grid_lines, closestGridLine)) {    
806         closestGridLine.setTarget(Inkscape::SNAPTARGET_GRID);
807         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
808     }
809     
810     // search for the closest snapped guide line
811     Inkscape::SnappedLine closestGuideLine;
812     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
813         closestGuideLine.setTarget(Inkscape::SNAPTARGET_GUIDE);
814         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
815     }
816     
817     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
818     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path 
819     
820     // When doing a constrained snap however, we're already at an intersection of the constrained line and
821     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
822     // no need to look for additional intersections
823     if (!constrained) {
824         // search for the closest snapped intersection of grid lines
825         Inkscape::SnappedPoint closestGridPoint;
826         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
827             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
828             sp_list.push_back(closestGridPoint);
829         }
830         
831         // search for the closest snapped intersection of guide lines
832         Inkscape::SnappedPoint closestGuidePoint;
833         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
834             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
835             sp_list.push_back(closestGuidePoint);
836         }
837         
838         // search for the closest snapped intersection of grid with guide lines
839         if (_intersectionGG) {
840             Inkscape::SnappedPoint closestGridGuidePoint;
841             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
842                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
843                 sp_list.push_back(closestGridGuidePoint);
844             }
845         }
846     }
847     
848     // now let's see which snapped point gets a thumbs up
849     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false);
850     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
851                 // first find out if this snapped point is within snapping range
852         if ((*i).getDistance() <= (*i).getTolerance()) {
853                 // if it's the first point
854                 bool c1 = (i == sp_list.begin());  
855                 // or, if it's closer
856                 bool c2 = (*i).getDistance() < bestSnappedPoint.getDistance();
857             // or, if it's for a snapper with "always snap" turned on, and the previous wasn't
858             bool c3 = (*i).getAlwaysSnap() && !bestSnappedPoint.getAlwaysSnap();
859                 // But in no case fall back from a snapper with "always snap" on to one with "always snap" off
860             bool c3n = !(*i).getAlwaysSnap() && bestSnappedPoint.getAlwaysSnap();
861             // or, if it's just as close then consider the second distance
862                 // (which is only relevant for points at an intersection)
863                 bool c4a = ((*i).getDistance() == bestSnappedPoint.getDistance()); 
864                 bool c4b = (*i).getSecondDistance() < bestSnappedPoint.getSecondDistance();
865                 // then prefer this point over the previous one
866             if ((c1 || c2 || c3 || (c4a && c4b)) && !c3n) {
867                 bestSnappedPoint = *i;
868             }
869         }
870     }
871     
872     
873     // Update the snap indicator, if requested
874     if (_snapindicator) {
875         if (bestSnappedPoint.getSnapped()) {
876             _desktop->snapindicator->set_new_snappoint(bestSnappedPoint);
877         } else {
878             _desktop->snapindicator->remove_snappoint();
879         }
880     }
881     
882     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << std::endl;
883     return bestSnappedPoint;         
886 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, SPItem const *item_to_ignore, std::vector<Geom::Point> *unselected_nodes)
888     g_assert(desktop != NULL);
889         object.setDesktop(desktop);
890     _item_to_ignore = item_to_ignore;
891     _items_to_ignore = NULL;
892     _desktop = desktop;
893     _snapindicator = snapindicator;
894     _unselected_nodes = unselected_nodes;
897 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, std::vector<SPItem const *> &items_to_ignore, std::vector<Geom::Point> *unselected_nodes)
899         g_assert(desktop != NULL);
900         object.setDesktop(desktop);
901         _item_to_ignore = NULL;
902     _items_to_ignore = &items_to_ignore;
903     _desktop = desktop;
904     _snapindicator = snapindicator;
905     _unselected_nodes = unselected_nodes;   
908 /*
909   Local Variables:
910   mode:c++
911   c-file-style:"stroustrup"
912   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
913   indent-tabs-mode:nil
914   fill-column:99
915   End:
916 */
917 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :