Code

537e0cd5248ce21872c061fde01d5990691e0c59
[inkscape.git] / src / snap.cpp
1 #define __SP_DESKTOP_SNAP_C__
3 /**
4  * \file snap.cpp
5  * \brief SnapManager class.
6  *
7  * Authors:
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   Frank Felfe <innerspace@iname.com>
10  *   Nathan Hurst <njh@njhurst.com>
11  *   Carl Hetherington <inkscape@carlh.net>
12  *   Diederik van Lierop <mail@diedenrezi.nl>
13  *
14  * Copyright (C) 2006-2007 Johan Engelen <johan@shouraizou.nl>
15  * Copyrigth (C) 2004      Nathan Hurst
16  * Copyright (C) 1999-2009 Authors
17  *
18  * Released under GNU GPL, read the file 'COPYING' for more information
19  */
21 #include <utility>
23 #include "sp-namedview.h"
24 #include "snap.h"
25 #include "snapped-line.h"
26 #include "snapped-curve.h"
28 #include "display/canvas-grid.h"
29 #include "display/snap-indicator.h"
31 #include "inkscape.h"
32 #include "desktop.h"
33 #include "sp-guide.h"
34 #include "preferences.h"
35 using std::vector;
37 /**
38  *  Construct a SnapManager for a SPNamedView.
39  *
40  *  \param v `Owning' SPNamedView.
41  */
43 SnapManager::SnapManager(SPNamedView const *v) :
44     guide(this, 0),
45     object(this, 0),
46     snapprefs(),
47     _named_view(v)
48 {
49 }
51 /**
52  *  \return List of snappers that we use.
53  */
54 SnapManager::SnapperList
55 SnapManager::getSnappers() const
56 {
57     SnapManager::SnapperList s;
58     s.push_back(&guide);
59     s.push_back(&object);
61     SnapManager::SnapperList gs = getGridSnappers();
62     s.splice(s.begin(), gs);
64     return s;
65 }
67 /**
68  *  \return List of gridsnappers that we use.
69  */
70 SnapManager::SnapperList
71 SnapManager::getGridSnappers() const
72 {
73     SnapperList s;
75     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
76     if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
77         for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
78             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
79             s.push_back(grid->snapper);
80         }
81     }
83     return s;
84 }
86 /**
87  * \return true if one of the snappers will try to snap something.
88  */
90 bool SnapManager::someSnapperMightSnap() const
91 {
92     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
93         return false;
94     }
96     SnapperList const s = getSnappers();
97     SnapperList::const_iterator i = s.begin();
98     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
99         i++;
100     }
102     return (i != s.end());
105 /**
106  * \return true if one of the snappers will try to snap something.
107  */
109 bool SnapManager::gridSnapperMightSnap() const
111     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
112         return false;
113     }
115     SnapperList const s = getGridSnappers();
116     SnapperList::const_iterator i = s.begin();
117     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
118         i++;
119     }
121     return (i != s.end());
124 /**
125  *  Try to snap a point to any of the specified snappers.
126  *
127  *  \param point_type Type of point.
128  *  \param p Point.
129  *  \param first_point If true then this point is the first one from a whole bunch of points
130  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
131  *  \param snappers List of snappers to try to snap to
132  *  \return Snapped point.
133  */
135 void SnapManager::freeSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
136                                       Geom::Point &p,
137                                       Inkscape::SnapSourceType const source_type,
138                                       bool first_point,
139                                       Geom::OptRect const &bbox_to_snap) const
141     Inkscape::SnappedPoint const s = freeSnap(point_type, p, source_type, first_point, bbox_to_snap);
142     s.getPoint(p);
146 /**
147  *  Try to snap a point to any of the specified snappers.
148  *
149  *  \param point_type Type of point.
150  *  \param p Point.
151  *  \param first_point If true then this point is the first one from a whole bunch of points
152  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
153  *  \param snappers List of snappers to try to snap to
154  *  \return Snapped point.
155  */
157 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapPreferences::PointType point_type,
158                                              Geom::Point const &p,
159                                              Inkscape::SnapSourceType const &source_type,
160                                              bool first_point,
161                                              Geom::OptRect const &bbox_to_snap) const
163     if (_desktop->canvas->context_snap_delay_active == false) {
164         g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
165         // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
166     }
168     if (!someSnapperMightSnap()) {
169         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
170     }
172     std::vector<SPItem const *> *items_to_ignore;
173     if (_item_to_ignore) { // If we have only a single item to ignore
174         // then build a list containing this single item;
175         // This single-item list will prevail over any other _items_to_ignore list, should that exist
176         items_to_ignore = new std::vector<SPItem const *>;
177         items_to_ignore->push_back(_item_to_ignore);
178     } else {
179         items_to_ignore = _items_to_ignore;
180     }
182     SnappedConstraints sc;
183     SnapperList const snappers = getSnappers();
185     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
186         (*i)->freeSnap(sc, point_type, p, source_type, first_point, bbox_to_snap, items_to_ignore, _unselected_nodes);
187     }
189     if (_item_to_ignore) {
190         delete items_to_ignore;
191     }
193     return findBestSnap(p, source_type, sc, false);
196 // When pasting, we would like to snap to the grid. Problem is that we don't know which nodes were
197 // aligned to the grid at the time of copying, so we don't know which nodes to snap. If we'd snap an
198 // unaligned node to the grid, previously aligned nodes would become unaligned. That's undesirable.
199 // Instead we will make sure that the offset between the source and the copy is a multiple of the grid
200 // pitch. If the source was aligned, then the copy will therefore also be aligned
201 // PS: Whether we really find a multiple also depends on the snapping range!
202 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
204     if (!snapprefs.getSnapEnabledGlobally()) // No need to check for snapprefs.getSnapPostponedGlobally() here
205         return t;
207     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
209     if (_desktop && _desktop->gridsEnabled()) {
210         bool success = false;
211         Geom::Point nearest_multiple;
212         Geom::Coord nearest_distance = NR_HUGE;
214         // It will snap to the grid for which we find the closest snap. This might be a different
215         // grid than to which the objects were initially aligned. I don't see an easy way to fix
216         // this, so when using multiple grids one can get unexpected results
218         // Cannot use getGridSnappers() because we need both the grids AND their snappers
219         // Therefore we iterate through all grids manually
220         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
221             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
222             const Inkscape::Snapper* snapper = grid->snapper;
223             if (snapper && snapper->ThisSnapperMightSnap()) {
224                 // To find the nearest multiple of the grid pitch for a given translation t, we
225                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
226                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
227                 // in the translation t
228                 Geom::Point const t_offset = t + grid->origin;
229                 SnappedConstraints sc;
230                 // Only the first three parameters are being used for grid snappers
231                 snapper->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_NODE, t_offset, Inkscape::SNAPSOURCE_UNDEFINED, TRUE, Geom::OptRect(), NULL, NULL);
232                 // Find the best snap for this grid, including intersections of the grid-lines
233                 Inkscape::SnappedPoint s = findBestSnap(t_offset, Inkscape::SNAPSOURCE_UNDEFINED, sc, false);
234                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
235                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
236                     // doesn't tell us anything about which node to snap
237                     success = true;
238                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
239                     nearest_distance = s.getSnapDistance();
240                 }
241             }
242         }
244         if (success)
245             return nearest_multiple;
246     }
248     return t;
251 /**
252  *  Try to snap a point to any interested snappers.  A snap will only occur along
253  *  a line described by a Inkscape::Snapper::ConstraintLine.
254  *
255  *  \param point_type Type of point.
256  *  \param p Point.
257  *  \param first_point If true then this point is the first one from a whole bunch of points
258  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
259  *  \param constraint Constraint line.
260  *  \return Snapped point.
261  */
263 void SnapManager::constrainedSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
264                                              Geom::Point &p,
265                                              Inkscape::SnapSourceType const source_type,
266                                              Inkscape::Snapper::ConstraintLine const &constraint,
267                                              bool const snap_projection,
268                                              bool first_point,
269                                              Geom::OptRect const &bbox_to_snap) const
271     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, source_type, constraint, snap_projection, first_point, bbox_to_snap);
272     s.getPoint(p);
276 /**
277  *  Try to snap a point to any interested snappers.  A snap will only occur along
278  *  a line described by a Inkscape::Snapper::ConstraintLine.
279  *
280  *  \param point_type Type of point.
281  *  \param p Point.
282  *  \param first_point If true then this point is the first one from a whole bunch of points
283  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
284  *  \param constraint Constraint line.
285  *  \return Snapped point.
286  */
288 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapPreferences::PointType point_type,
289                                                     Geom::Point const &p,
290                                                     Inkscape::SnapSourceType const &source_type,
291                                                     Inkscape::Snapper::ConstraintLine const &constraint,
292                                                     bool snap_projection,
293                                                     bool first_point,
294                                                     Geom::OptRect const &bbox_to_snap) const
296     if (_desktop->canvas->context_snap_delay_active == false) {
297         g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
298         // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
299     }
301     if (!someSnapperMightSnap()) {
302         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
303     }
305     std::vector<SPItem const *> *items_to_ignore;
306     if (_item_to_ignore) { // If we have only a single item to ignore
307         // then build a list containing this single item;
308         // This single-item list will prevail over any other _items_to_ignore list, should that exist
309         items_to_ignore = new std::vector<SPItem const *>;
310         items_to_ignore->push_back(_item_to_ignore);
311     } else {
312         items_to_ignore = _items_to_ignore;
313     }
315     Geom::Point pp = constraint.projection(p);
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, pp, 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, false, 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, false, 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         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
818     }
820     // search for the closest snapped guide line
821     Inkscape::SnappedLine closestGuideLine;
822     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
823         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
824     }
826     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
827     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
829     // When doing a constrained snap however, we're already at an intersection of the constrained line and
830     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
831     // no need to look for additional intersections
832     if (!constrained) {
833         // search for the closest snapped intersection of grid lines
834         Inkscape::SnappedPoint closestGridPoint;
835         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
836             closestGridPoint.setSource(source_type);
837             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
838             sp_list.push_back(closestGridPoint);
839         }
841         // search for the closest snapped intersection of guide lines
842         Inkscape::SnappedPoint closestGuidePoint;
843         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
844             closestGuidePoint.setSource(source_type);
845             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
846             sp_list.push_back(closestGuidePoint);
847         }
849         // search for the closest snapped intersection of grid with guide lines
850         if (snapprefs.getSnapIntersectionGG()) {
851             Inkscape::SnappedPoint closestGridGuidePoint;
852             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
853                 closestGridGuidePoint.setSource(source_type);
854                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
855                 sp_list.push_back(closestGridGuidePoint);
856             }
857         }
858     }
860     // now let's see which snapped point gets a thumbs up
861     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPSOURCE_UNDEFINED, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
862     // std::cout << "Finding the best snap..." << std::endl;
863     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
864         // first find out if this snapped point is within snapping range
865         // std::cout << "sp = " << from_2geom((*i).getPoint());
866         if ((*i).getSnapDistance() <= (*i).getTolerance()) {
867             // if it's the first point, or if it is closer than the best snapped point so far
868             if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
869                 // then prefer this point over the previous one
870                 bestSnappedPoint = *i;
871             }
872         }
873         // std::cout << std::endl;
874     }
876     // Update the snap indicator, if requested
877     if (_snapindicator) {
878         if (bestSnappedPoint.getSnapped()) {
879             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
880         } else {
881             _desktop->snapindicator->remove_snaptarget();
882         }
883     }
885     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
886     return bestSnappedPoint;
889 void SnapManager::setup(SPDesktop const *desktop,
890                         bool snapindicator,
891                         SPItem const *item_to_ignore,
892                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
893                         SPGuide *guide_to_ignore)
895     g_assert(desktop != NULL);
896     _item_to_ignore = item_to_ignore;
897     _items_to_ignore = NULL;
898     _desktop = desktop;
899     _snapindicator = snapindicator;
900     _unselected_nodes = unselected_nodes;
901     _guide_to_ignore = guide_to_ignore;
904 void SnapManager::setup(SPDesktop const *desktop,
905                         bool snapindicator,
906                         std::vector<SPItem const *> &items_to_ignore,
907                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
908                         SPGuide *guide_to_ignore)
910     g_assert(desktop != NULL);
911     _item_to_ignore = NULL;
912     _items_to_ignore = &items_to_ignore;
913     _desktop = desktop;
914     _snapindicator = snapindicator;
915     _unselected_nodes = unselected_nodes;
916     _guide_to_ignore = guide_to_ignore;
919 SPDocument *SnapManager::getDocument() const
921     return _named_view->document;
924 Geom::Point SnapManager::_transformPoint(std::pair<Geom::Point, int> const &p,
925                                         Transformation const transformation_type,
926                                         Geom::Point const &transformation,
927                                         Geom::Point const &origin,
928                                         Geom::Dim2 const dim,
929                                         bool const uniform) const
931     /* Work out the transformed version of this point */
932     Geom::Point transformed;
933     switch (transformation_type) {
934         case TRANSLATION:
935             transformed = p.first + transformation;
936             break;
937         case SCALE:
938             transformed = (p.first - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
939             break;
940         case STRETCH:
941         {
942             Geom::Scale s(1, 1);
943             if (uniform)
944                 s[Geom::X] = s[Geom::Y] = transformation[dim];
945             else {
946                 s[dim] = transformation[dim];
947                 s[1 - dim] = 1;
948             }
949             transformed = ((p.first - origin) * s) + origin;
950             break;
951         }
952         case SKEW:
953             // Apply the skew factor
954             transformed[dim] = (p.first)[dim] + transformation[0] * ((p.first)[1 - dim] - origin[1 - dim]);
955             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
956             // Apply that scale factor here
957             transformed[1-dim] = (p.first - origin)[1 - dim] * transformation[1] + origin[1 - dim];
958             break;
959         default:
960             g_assert_not_reached();
961     }
963     return transformed;
966 void SnapManager::_displaySnapsource(Inkscape::SnapPreferences::PointType point_type, std::pair<Geom::Point, int> const &p) const {
968     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
969     if (prefs->getBool("/options/snapclosestonly/value")) {
970         bool p_is_a_node = point_type & Inkscape::SnapPreferences::SNAPPOINT_NODE;
971         bool p_is_a_bbox = point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
972         if (snapprefs.getSnapEnabledGlobally() && ((p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
973             _desktop->snapindicator->set_new_snapsource(p);
974         } else {
975             _desktop->snapindicator->remove_snapsource();
976         }
977     }
980 /*
981   Local Variables:
982   mode:c++
983   c-file-style:"stroustrup"
984   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
985   indent-tabs-mode:nil
986   fill-column:99
987   End:
988 */
989 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :