Code

part of bug #339660; can not use Add/Rename dialog to create layer with no proper...
[inkscape.git] / src / snap.cpp
1 #define __SP_DESKTOP_SNAP_C__
3 /**
4  * \file snap.cpp
5  * \brief SnapManager class.
6  *
7  * Authors:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   Frank Felfe <innerspace@iname.com>
10  *   Nathan Hurst <njh@njhurst.com>
11  *   Carl Hetherington <inkscape@carlh.net>
12  *   Diederik van Lierop <mail@diedenrezi.nl>
13  *
14  * Copyright (C) 2006-2007 Johan Engelen <johan@shouraizou.nl>
15  * Copyrigth (C) 2004      Nathan Hurst
16  * Copyright (C) 1999-2009 Authors
17  *
18  * Released under GNU GPL, read the file 'COPYING' for more information
19  */
21 #include <utility>
23 #include "sp-namedview.h"
24 #include "snap.h"
25 #include "snapped-line.h"
26 #include "snapped-curve.h"
28 #include <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 #include "preferences.h"
39 using std::vector;
41 /**
42  *  Construct a SnapManager for a SPNamedView.
43  *
44  *  \param v `Owning' SPNamedView.
45  */
47 SnapManager::SnapManager(SPNamedView const *v) :
48     guide(this, 0),
49     object(this, 0),
50     snapprefs(),
51     _named_view(v)
52 {
53 }
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     if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
81         for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
82             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
83             s.push_back(grid->snapper);
84         }
85     }
87     return s;
88 }
90 /**
91  * \return true if one of the snappers will try to snap something.
92  */
94 bool SnapManager::someSnapperMightSnap() const
95 {
96     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
97         return false;
98     }
100     SnapperList const s = getSnappers();
101     SnapperList::const_iterator i = s.begin();
102     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
103         i++;
104     }
106     return (i != s.end());
109 /**
110  * \return true if one of the snappers will try to snap something.
111  */
113 bool SnapManager::gridSnapperMightSnap() const
115     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
116         return false;
117     }
119     SnapperList const s = getGridSnappers();
120     SnapperList::const_iterator i = s.begin();
121     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
122         i++;
123     }
125     return (i != s.end());
128 /**
129  *  Try to snap a point to any of the specified snappers.
130  *
131  *  \param point_type Type of point.
132  *  \param p Point.
133  *  \param first_point If true then this point is the first one from a whole bunch of points
134  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
135  *  \param snappers List of snappers to try to snap to
136  *  \return Snapped point.
137  */
139 void SnapManager::freeSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
140                                                                                          Geom::Point &p,
141                                                                                          Inkscape::SnapSourceType const source_type,
142                                                                                          bool first_point,
143                                              Geom::OptRect const &bbox_to_snap) const
145     Inkscape::SnappedPoint const s = freeSnap(point_type, p, source_type, first_point, bbox_to_snap);
146     s.getPoint(p);
150 /**
151  *  Try to snap a point to any of the specified snappers.
152  *
153  *  \param point_type Type of point.
154  *  \param p Point.
155  *  \param first_point If true then this point is the first one from a whole bunch of points
156  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
157  *  \param snappers List of snappers to try to snap to
158  *  \return Snapped point.
159  */
161 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapPreferences::PointType point_type,
162                                                                                          Geom::Point const &p,
163                                                                                          Inkscape::SnapSourceType const &source_type,
164                                                                                          bool first_point,
165                                              Geom::OptRect const &bbox_to_snap) const
167         if (_desktop->canvas->context_snap_delay_active == false) {
168                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
169                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
170         }
172         if (!someSnapperMightSnap()) {
173         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
174     }
176     std::vector<SPItem const *> *items_to_ignore;
177     if (_item_to_ignore) { // If we have only a single item to ignore
178         // then build a list containing this single item;
179         // This single-item list will prevail over any other _items_to_ignore list, should that exist
180         items_to_ignore = new std::vector<SPItem const *>;
181         items_to_ignore->push_back(_item_to_ignore);
182     } else {
183         items_to_ignore = _items_to_ignore;
184     }
186     SnappedConstraints sc;
187     SnapperList const snappers = getSnappers();
189     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
190         (*i)->freeSnap(sc, point_type, p, source_type, first_point, bbox_to_snap, items_to_ignore, _unselected_nodes);
191     }
193     if (_item_to_ignore) {
194         delete items_to_ignore;
195     }
197     return findBestSnap(p, source_type, sc, false);
200 // When pasting, we would like to snap to the grid. Problem is that we don't know which nodes were
201 // aligned to the grid at the time of copying, so we don't know which nodes to snap. If we'd snap an
202 // unaligned node to the grid, previously aligned nodes would become unaligned. That's undesirable.
203 // Instead we will make sure that the offset between the source and the copy is a multiple of the grid
204 // pitch. If the source was aligned, then the copy will therefore also be aligned
205 // PS: Whether we really find a multiple also depends on the snapping range!
206 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
208     if (!snapprefs.getSnapEnabledGlobally()) // No need to check for snapprefs.getSnapPostponedGlobally() here
209         return t;
211     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
213     if (_desktop && _desktop->gridsEnabled()) {
214         bool success = false;
215         Geom::Point nearest_multiple;
216         Geom::Coord nearest_distance = NR_HUGE;
218         // It will snap to the grid for which we find the closest snap. This might be a different
219         // grid than to which the objects were initially aligned. I don't see an easy way to fix
220         // this, so when using multiple grids one can get unexpected results
222         // Cannot use getGridSnappers() because we need both the grids AND their snappers
223         // Therefore we iterate through all grids manually
224         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
225             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
226             const Inkscape::Snapper* snapper = grid->snapper;
227             if (snapper && snapper->ThisSnapperMightSnap()) {
228                 // To find the nearest multiple of the grid pitch for a given translation t, we
229                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
230                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
231                 // in the translation t
232                 Geom::Point const t_offset = t + grid->origin;
233                 SnappedConstraints sc;
234                 // Only the first three parameters are being used for grid snappers
235                 snapper->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_NODE, t_offset, Inkscape::SNAPSOURCE_UNDEFINED, TRUE, Geom::OptRect(), NULL, NULL);
236                 // Find the best snap for this grid, including intersections of the grid-lines
237                 Inkscape::SnappedPoint s = findBestSnap(t_offset, Inkscape::SNAPSOURCE_UNDEFINED, sc, false);
238                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
239                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
240                     // doesn't tell us anything about which node to snap
241                     success = true;
242                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
243                     nearest_distance = s.getSnapDistance();
244                 }
245             }
246         }
248         if (success)
249             return nearest_multiple;
250     }
252     return t;
255 /**
256  *  Try to snap a point to any interested snappers.  A snap will only occur along
257  *  a line described by a Inkscape::Snapper::ConstraintLine.
258  *
259  *  \param point_type Type of point.
260  *  \param p Point.
261  *  \param first_point If true then this point is the first one from a whole bunch of points
262  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
263  *  \param constraint Constraint line.
264  *  \return Snapped point.
265  */
267 void SnapManager::constrainedSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
268                                                                                                         Geom::Point &p,
269                                                                                                         Inkscape::SnapSourceType const source_type,
270                                                     Inkscape::Snapper::ConstraintLine const &constraint,
271                                                     bool first_point,
272                                                     Geom::OptRect const &bbox_to_snap) const
274     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, source_type, constraint, first_point, bbox_to_snap);
275     s.getPoint(p);
279 /**
280  *  Try to snap a point to any interested snappers.  A snap will only occur along
281  *  a line described by a Inkscape::Snapper::ConstraintLine.
282  *
283  *  \param point_type Type of point.
284  *  \param p Point.
285  *  \param first_point If true then this point is the first one from a whole bunch of points
286  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
287  *  \param constraint Constraint line.
288  *  \return Snapped point.
289  */
291 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapPreferences::PointType point_type,
292                                                                                                         Geom::Point const &p,
293                                                                                                         Inkscape::SnapSourceType const &source_type,
294                                                     Inkscape::Snapper::ConstraintLine const &constraint,
295                                                     bool first_point,
296                                                     Geom::OptRect const &bbox_to_snap) const
298         if (_desktop->canvas->context_snap_delay_active == false) {
299                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
300                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
301         }
303         if (!someSnapperMightSnap()) {
304         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
305     }
307     std::vector<SPItem const *> *items_to_ignore;
308     if (_item_to_ignore) { // If we have only a single item to ignore
309         // then build a list containing this single item;
310         // This single-item list will prevail over any other _items_to_ignore list, should that exist
311         items_to_ignore = new std::vector<SPItem const *>;
312         items_to_ignore->push_back(_item_to_ignore);
313     } else {
314         items_to_ignore = _items_to_ignore;
315     }
317     SnappedConstraints sc;
318     SnapperList const snappers = getSnappers();
319     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
320         (*i)->constrainedSnap(sc, point_type, p, source_type, first_point, bbox_to_snap, constraint, items_to_ignore);
321     }
323     if (_item_to_ignore) {
324         delete items_to_ignore;
325     }
327     return findBestSnap(p, source_type, sc, true);
330 void SnapManager::guideSnap(Geom::Point &p, Geom::Point const &guide_normal) const
332     // This method is used to snap a guide to nodes or to other guides, while dragging the guide around. Will not snap to grids!
334         if (_desktop->canvas->context_snap_delay_active == false) {
335                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
336                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
337         }
339     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
340         return;
341     }
343     if (!(object.GuidesMightSnap() || snapprefs.getSnapToGuides())) {
344         return;
345     }
347     // Snap to nodes
348     SnappedConstraints sc;
349     if (object.GuidesMightSnap()) {
350         object.guideSnap(sc, p, guide_normal);
351     }
353     // Snap to guides
354     if (snapprefs.getSnapToGuides()) {
355         guide.freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, Inkscape::SNAPSOURCE_GUIDE, true, Geom::OptRect(), NULL, NULL);
356     }
358     // We won't snap to grids, what's the use?
360     Inkscape::SnappedPoint const s = findBestSnap(p, Inkscape::SNAPSOURCE_GUIDE, sc, false);
361     s.getPoint(p);
365 /**
366  *  Main internal snapping method, which is called by the other, friendlier, public
367  *  methods.  It's a bit hairy as it has lots of parameters, but it saves on a lot
368  *  of duplicated code.
369  *
370  *  \param type Type of points being snapped.
371  *  \param points List of points to snap (i.e. untransformed).
372  *  \param pointer Location of the mouse pointer, at the time when dragging started (i.e. "untransformed")
373  *  \param constrained true if the snap is constrained.
374  *  \param constraint Constraint line to use, if `constrained' is true, otherwise undefined.
375  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
376  *  \param transformation Description of the transformation; details depend on the type.
377  *  \param origin Origin of the transformation, if applicable.
378  *  \param dim Dimension of the transformation, if applicable.
379  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
380  */
382 Inkscape::SnappedPoint SnapManager::_snapTransformed(
383     Inkscape::SnapPreferences::PointType type,
384     std::vector<std::pair<Geom::Point, int> > const &points,
385     Geom::Point const &pointer,
386     bool constrained,
387     Inkscape::Snapper::ConstraintLine const &constraint,
388     Transformation transformation_type,
389     Geom::Point const &transformation,
390     Geom::Point const &origin,
391     Geom::Dim2 dim,
392     bool uniform) const
394     /* We have a list of points, which we are proposing to transform in some way.  We need to see
395     ** if any of these points, when transformed, snap to anything.  If they do, we return the
396     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
397     */
399     /* Quick check to see if we have any snappers that are enabled
400     ** Also used to globally disable all snapping
401     */
402     if (someSnapperMightSnap() == false) {
403         return Inkscape::SnappedPoint();
404     }
406     std::vector<std::pair<Geom::Point, int> > transformed_points;
407     Geom::Rect bbox;
409     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
411         /* Work out the transformed version of this point */
412         Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
414         // add the current transformed point to the box hulling all transformed points
415         if (i == points.begin()) {
416             bbox = Geom::Rect(transformed, transformed);
417         } else {
418             bbox.expandTo(transformed);
419         }
421         transformed_points.push_back(std::make_pair(transformed, (*i).second));
422     }
424     /* The current best transformation */
425     Geom::Point best_transformation = transformation;
427     /* The current best metric for the best transformation; lower is better, NR_HUGE
428     ** means that we haven't snapped anything.
429     */
430     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
431     Inkscape::SnappedPoint best_snapped_point;
432     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
433     g_assert(best_snapped_point.getAtIntersection() == false);
435     std::vector<std::pair<Geom::Point, int> >::const_iterator j = transformed_points.begin();
437     // std::cout << std::endl;
438     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
440         /* Snap it */
441         Inkscape::SnappedPoint snapped_point;
442         Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
443         Geom::Point const b = ((*i).first - origin); // vector to original point
445         if (constrained) {
446             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
447                 // When uniformly scaling, each point will have its own unique constraint line,
448                 // running from the scaling origin to the original untransformed point. We will
449                 // calculate that line here
450                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, b);
451             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
452                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i).first, component_vectors[dim]);
453             } else if (transformation_type == TRANSLATION) {
454                 // When doing a constrained translation, all points will move in the same direction, i.e.
455                 // either horizontally or vertically. The lines along which they move are therefore all
456                 // parallel, but might not be colinear. Therefore we will have to set the point through
457                 // which the constraint-line runs here, for each point individually.
458                 dedicated_constraint.setPoint((*i).first);
459             } // else: leave the original constraint, e.g. for skewing
460             if (transformation_type == SCALE && !uniform) {
461                 g_warning("Non-uniform constrained scaling is not supported!");
462             }
463             snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, i == points.begin(), bbox);
464         } else {
465             bool const c1 = fabs(b[Geom::X]) < 1e-6;
466             bool const c2 = fabs(b[Geom::Y]) < 1e-6;
467             if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
468                 // When scaling, a point aligned either horizontally or vertically with the origin can only
469                 // move in that specific direction; therefore it should only snap in that direction, otherwise
470                 // we will get snapped points with an invalid transformation
471                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, component_vectors[c1]);
472                 snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, i == points.begin(), bbox);
473             } else {
474                 snapped_point = freeSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), i == points.begin(), bbox);
475             }
476         }
477         // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
478         snapped_point.setPointerDistance(Geom::L2(pointer - (*i).first));
480         Geom::Point result;
481         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
483         if (snapped_point.getSnapped()) {
484             /* We snapped.  Find the transformation that describes where the snapped point has
485             ** ended up, and also the metric for this transformation.
486             */
487             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
488             //Geom::Point const b = (*i - origin); // vector to original point
490             switch (transformation_type) {
491                 case TRANSLATION:
492                     result = snapped_point.getPoint() - (*i).first;
493                     /* Consider the case in which a box is almost aligned with a grid in both
494                      * horizontal and vertical directions. The distance to the intersection of
495                      * the grid lines will always be larger then the distance to a single grid
496                      * line. If we prefer snapping to an intersection instead of to a single
497                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
498                      * snapped distance will be used as a metric. Please note that the snapped
499                      * distance is defined as the distance to the nearest line of the intersection,
500                      * and not to the intersection itself!
501                      */
502                     // Only for translations, the relevant metric will be the real snapped distance,
503                     // so we don't have to do anything special here
504                     break;
505                 case SCALE:
506                 {
507                     result = Geom::Point(NR_HUGE, NR_HUGE);
508                     // If this point *i is horizontally or vertically aligned with
509                     // the origin of the scaling, then it will scale purely in X or Y
510                     // We can therefore only calculate the scaling in this direction
511                     // and the scaling factor for the other direction should remain
512                     // untouched (unless scaling is uniform ofcourse)
513                     for (int index = 0; index < 2; index++) {
514                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
515                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
516                                 result[index] = a[index] / b[index]; // then calculate it!
517                             }
518                             // we might leave result[1-index] = NR_HUGE
519                             // if scaling didn't occur in the other direction
520                         }
521                     }
522                     // Compare the resulting scaling with the desired scaling
523                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
524                     break;
525                 }
526                 case STRETCH:
527                     result = Geom::Point(NR_HUGE, NR_HUGE);
528                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
529                         result[dim] = a[dim] / b[dim];
530                         result[1-dim] = uniform ? result[dim] : 1;
531                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
532                         if (uniform && fabs(b[1-dim]) > 1e-6) {
533                            result[1-dim] = a[1-dim] / b[1-dim];
534                            result[dim] = result[1-dim];
535                         }
536                     }
537                     // Store the metric for this transformation as a virtual distance
538                     snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
539                     snapped_point.setSecondSnapDistance(NR_HUGE);
540                     break;
541                 case SKEW:
542                     result[0] = (snapped_point.getPoint()[dim] - ((*i).first)[dim]) / (((*i).first)[1 - dim] - origin[1 - dim]); // skew factor
543                     result[1] = transformation[1]; // scale factor
544                     // Store the metric for this transformation as a virtual distance
545                     snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
546                     snapped_point.setSecondSnapDistance(NR_HUGE);
547                     break;
548                 default:
549                     g_assert_not_reached();
550             }
552             // When scaling, we're considering the best transformation in each direction separately. We will have a metric in each
553             // direction, whereas for all other transformation we only a single one-dimensional metric. That's why we need to handle
554             // the scaling metric differently
555             if (transformation_type == SCALE) {
556                 for (int index = 0; index < 2; index++) {
557                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
558                         best_transformation[index] = result[index];
559                         best_scale_metric[index] = fabs(scale_metric[index]);
560                         // When scaling, we're considering the best transformation in each direction separately
561                         // Therefore two different snapped points might together make a single best transformation
562                         // We will however return only a single snapped point (e.g. to display the snapping indicator)
563                         best_snapped_point = snapped_point;
564                         // std::cout << "SEL ";
565                     } // else { std::cout << "    ";}
566                 }
567                 if (uniform) {
568                     if (best_scale_metric[0] < best_scale_metric[1]) {
569                         best_transformation[1] = best_transformation[0];
570                         best_scale_metric[1] = best_scale_metric[0];
571                     } else {
572                         best_transformation[0] = best_transformation[1];
573                         best_scale_metric[0] = best_scale_metric[1];
574                     }
575                 }
576             } else { // For all transformations other than scaling
577                 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
578                     best_transformation = result;
579                     best_snapped_point = snapped_point;
580                 }
581             }
582         }
584         j++;
585     }
587     Geom::Coord best_metric;
588     if (transformation_type == SCALE) {
589         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
590         for (int index = 0; index < 2; index++) {
591             if (best_transformation[index] == NR_HUGE) {
592                 if (uniform && best_transformation[1-index] < NR_HUGE) {
593                     best_transformation[index] = best_transformation[1-index];
594                 } else {
595                     best_transformation[index] = transformation[index];
596                 }
597             }
598         }
599         best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
600     } else { // For all transformations other than scaling
601         best_metric = best_snapped_point.getSnapDistance();
602     }
604     best_snapped_point.setTransformation(best_transformation);
605     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
606     // These rounding errors might be caused by NRRects, see bug #1584301
607     best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
608     return best_snapped_point;
612 /**
613  *  Try to snap a list of points to any interested snappers after they have undergone
614  *  a translation.
615  *
616  *  \param point_type Type of points.
617  *  \param p Points.
618  *  \param tr Proposed translation.
619  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
620  */
622 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
623                                                         std::vector<std::pair<Geom::Point, int> > const &p,
624                                                         Geom::Point const &pointer,
625                                                         Geom::Point const &tr) const
627     if (p.size() == 1) {
628         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
629     }
631     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
635 /**
636  *  Try to snap a list of points to any interested snappers after they have undergone a
637  *  translation.  A snap will only occur along a line described by a
638  *  Inkscape::Snapper::ConstraintLine.
639  *
640  *  \param point_type Type of points.
641  *  \param p Points.
642  *  \param constraint Constraint line.
643  *  \param tr Proposed translation.
644  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
645  */
647 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
648                                                                std::vector<std::pair<Geom::Point, int> > const &p,
649                                                                Geom::Point const &pointer,
650                                                                Inkscape::Snapper::ConstraintLine const &constraint,
651                                                                Geom::Point const &tr) const
653     if (p.size() == 1) {
654         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
655     }
657     return _snapTransformed(point_type, p, pointer, true, constraint, TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
661 /**
662  *  Try to snap a list of points to any interested snappers after they have undergone
663  *  a scale.
664  *
665  *  \param point_type Type of points.
666  *  \param p Points.
667  *  \param s Proposed scale.
668  *  \param o Origin of proposed scale.
669  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
670  */
672 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::SnapPreferences::PointType point_type,
673                                                   std::vector<std::pair<Geom::Point, int> > const &p,
674                                                   Geom::Point const &pointer,
675                                                   Geom::Scale const &s,
676                                                   Geom::Point const &o) const
678     if (p.size() == 1) {
679         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false), (p.at(0)).second));
680     }
682     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
686 /**
687  *  Try to snap a list of points to any interested snappers after they have undergone
688  *  a scale.  A snap will only occur along a line described by a
689  *  Inkscape::Snapper::ConstraintLine.
690  *
691  *  \param point_type Type of points.
692  *  \param p Points.
693  *  \param s Proposed scale.
694  *  \param o Origin of proposed scale.
695  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
696  */
698 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::SnapPreferences::PointType point_type,
699                                                          std::vector<std::pair<Geom::Point, int> > const &p,
700                                                          Geom::Point const &pointer,
701                                                          Geom::Scale const &s,
702                                                          Geom::Point const &o) const
704     // When constrained scaling, only uniform scaling is supported.
705     if (p.size() == 1) {
706         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true), (p.at(0)).second));
707     }
709     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
713 /**
714  *  Try to snap a list of points to any interested snappers after they have undergone
715  *  a stretch.
716  *
717  *  \param point_type Type of points.
718  *  \param p Points.
719  *  \param s Proposed stretch.
720  *  \param o Origin of proposed stretch.
721  *  \param d Dimension in which to apply proposed stretch.
722  *  \param u true if the stretch should be uniform (ie to be applied equally in both dimensions)
723  *  \return Snapped stretch, if a snap occurred, and a flag indicating whether a snap occurred.
724  */
726 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::SnapPreferences::PointType point_type,
727                                                             std::vector<std::pair<Geom::Point, int> > const &p,
728                                                             Geom::Point const &pointer,
729                                                             Geom::Coord const &s,
730                                                             Geom::Point const &o,
731                                                             Geom::Dim2 d,
732                                                             bool u) const
734     if (p.size() == 1) {
735         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u), (p.at(0)).second));
736     }
738     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
742 /**
743  *  Try to snap a list of points to any interested snappers after they have undergone
744  *  a skew.
745  *
746  *  \param point_type Type of points.
747  *  \param p Points.
748  *  \param s Proposed skew.
749  *  \param o Origin of proposed skew.
750  *  \param d Dimension in which to apply proposed skew.
751  *  \return Snapped skew, if a snap occurred, and a flag indicating whether a snap occurred.
752  */
754 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::SnapPreferences::PointType point_type,
755                                                  std::vector<std::pair<Geom::Point, int> > const &p,
756                                                  Geom::Point const &pointer,
757                                                  Inkscape::Snapper::ConstraintLine const &constraint,
758                                                  Geom::Point const &s,
759                                                  Geom::Point const &o,
760                                                  Geom::Dim2 d) const
762     // "s" contains skew factor in s[0], and scale factor in s[1]
764     // Snapping the nodes of the boundingbox of a selection that is being transformed, will only work if
765     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
766     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
767     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
768     // of bounding boxes is not allowed here.
769     g_assert(!(point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX));
771     if (p.size() == 1) {
772         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SKEW, s, o, d, false), (p.at(0)).second));
773     }
775     return _snapTransformed(point_type, p, pointer, true, constraint, SKEW, s, o, d, false);
778 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p, Inkscape::SnapSourceType const source_type, SnappedConstraints &sc, bool constrained) const
781     /*
782     std::cout << "Type and number of snapped constraints: " << std::endl;
783     std::cout << "  Points      : " << sc.points.size() << std::endl;
784     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
785     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
786     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
787     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
788     */
790     // Store all snappoints
791     std::list<Inkscape::SnappedPoint> sp_list;
793     // search for the closest snapped point
794     Inkscape::SnappedPoint closestPoint;
795     if (getClosestSP(sc.points, closestPoint)) {
796         sp_list.push_back(closestPoint);
797     }
799     // search for the closest snapped curve
800     Inkscape::SnappedCurve closestCurve;
801     if (getClosestCurve(sc.curves, closestCurve)) {
802         sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
803     }
805     if (snapprefs.getSnapIntersectionCS()) {
806         // search for the closest snapped intersection of curves
807         Inkscape::SnappedPoint closestCurvesIntersection;
808         if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection, _desktop->dt2doc())) {
809                 closestCurvesIntersection.setSource(source_type);
810                 sp_list.push_back(closestCurvesIntersection);
811         }
812     }
814     // search for the closest snapped grid line
815     Inkscape::SnappedLine closestGridLine;
816     if (getClosestSL(sc.grid_lines, closestGridLine)) {
817         closestGridLine.setTarget(Inkscape::SNAPTARGET_GRID);
818         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
819     }
821     // search for the closest snapped guide line
822     Inkscape::SnappedLine closestGuideLine;
823     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
824         closestGuideLine.setTarget(Inkscape::SNAPTARGET_GUIDE);
825         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
826     }
828     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
829     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
831     // When doing a constrained snap however, we're already at an intersection of the constrained line and
832     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
833     // no need to look for additional intersections
834     if (!constrained) {
835         // search for the closest snapped intersection of grid lines
836         Inkscape::SnappedPoint closestGridPoint;
837         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
838                 closestGridPoint.setSource(source_type);
839                 closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
840             sp_list.push_back(closestGridPoint);
841         }
843         // search for the closest snapped intersection of guide lines
844         Inkscape::SnappedPoint closestGuidePoint;
845         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
846                 closestGuidePoint.setSource(source_type);
847                 closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
848             sp_list.push_back(closestGuidePoint);
849         }
851         // search for the closest snapped intersection of grid with guide lines
852         if (snapprefs.getSnapIntersectionGG()) {
853             Inkscape::SnappedPoint closestGridGuidePoint;
854             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
855                 closestGridGuidePoint.setSource(source_type);
856                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
857                 sp_list.push_back(closestGridGuidePoint);
858             }
859         }
860     }
862     // now let's see which snapped point gets a thumbs up
863     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPSOURCE_UNDEFINED, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
864     // std::cout << "Finding the best snap..." << std::endl;
865     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
866         // first find out if this snapped point is within snapping range
867         // std::cout << "sp = " << from_2geom((*i).getPoint());
868         if ((*i).getSnapDistance() <= (*i).getTolerance()) {
869             // if it's the first point, or if it is closer than the best snapped point so far
870             if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
871                 // then prefer this point over the previous one
872                 bestSnappedPoint = *i;
873             }
874         }
875         // std::cout << std::endl;
876     }
878     // Update the snap indicator, if requested
879     if (_snapindicator) {
880         if (bestSnappedPoint.getSnapped()) {
881             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
882         } else {
883             _desktop->snapindicator->remove_snaptarget();
884         }
885     }
887     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
888     return bestSnappedPoint;
891 void SnapManager::setup(SPDesktop const *desktop,
892                 bool snapindicator,
893                 SPItem const *item_to_ignore,
894                 std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
895                 SPGuide *guide_to_ignore)
897     g_assert(desktop != NULL);
898     _item_to_ignore = item_to_ignore;
899     _items_to_ignore = NULL;
900     _desktop = desktop;
901     _snapindicator = snapindicator;
902     _unselected_nodes = unselected_nodes;
903     _guide_to_ignore = guide_to_ignore;
906 void SnapManager::setup(SPDesktop const *desktop,
907                 bool snapindicator,
908                 std::vector<SPItem const *> &items_to_ignore,
909                 std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
910                 SPGuide *guide_to_ignore)
912     g_assert(desktop != NULL);
913     _item_to_ignore = NULL;
914     _items_to_ignore = &items_to_ignore;
915     _desktop = desktop;
916     _snapindicator = snapindicator;
917     _unselected_nodes = unselected_nodes;
918     _guide_to_ignore = guide_to_ignore;
921 SPDocument *SnapManager::getDocument() const
923     return _named_view->document;
926 Geom::Point SnapManager::_transformPoint(std::pair<Geom::Point, int> const &p,
927                                         Transformation const transformation_type,
928                                         Geom::Point const &transformation,
929                                         Geom::Point const &origin,
930                                         Geom::Dim2 const dim,
931                                         bool const uniform) const
933     /* Work out the transformed version of this point */
934     Geom::Point transformed;
935     switch (transformation_type) {
936         case TRANSLATION:
937             transformed = p.first + transformation;
938             break;
939         case SCALE:
940             transformed = (p.first - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
941             break;
942         case STRETCH:
943         {
944             Geom::Scale s(1, 1);
945             if (uniform)
946                 s[Geom::X] = s[Geom::Y] = transformation[dim];
947             else {
948                 s[dim] = transformation[dim];
949                 s[1 - dim] = 1;
950             }
951             transformed = ((p.first - origin) * s) + origin;
952             break;
953         }
954         case SKEW:
955             // Apply the skew factor
956             transformed[dim] = (p.first)[dim] + transformation[0] * ((p.first)[1 - dim] - origin[1 - dim]);
957             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
958             // Apply that scale factor here
959             transformed[1-dim] = (p.first - origin)[1 - dim] * transformation[1] + origin[1 - dim];
960             break;
961         default:
962             g_assert_not_reached();
963     }
965     return transformed;
968 void SnapManager::_displaySnapsource(Inkscape::SnapPreferences::PointType point_type, std::pair<Geom::Point, int> const &p) const {
970     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
971     if (prefs->getBool("/options/snapclosestonly/value")) {
972         bool p_is_a_node = point_type & Inkscape::SnapPreferences::SNAPPOINT_NODE;
973         bool p_is_a_bbox = point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
974         if (snapprefs.getSnapEnabledGlobally() && ((p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
975             _desktop->snapindicator->set_new_snapsource(p);
976         } else {
977             _desktop->snapindicator->remove_snapsource();
978         }
979     }
982 /*
983   Local Variables:
984   mode:c++
985   c-file-style:"stroustrup"
986   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
987   indent-tabs-mode:nil
988   fill-column:99
989   End:
990 */
991 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :