Code

Remove some SP_ACTIVE_DESKTOP() calls
[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()) {
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                                              bool first_point,
142                                              Geom::OptRect const &bbox_to_snap) const
144     Inkscape::SnappedPoint const s = freeSnap(point_type, p, first_point, bbox_to_snap);
145     s.getPoint(p);
148 /**
149  *  Try to snap a point to any of the specified snappers.
150  *
151  *  \param point_type Type of point.
152  *  \param p Point.
153  *  \param first_point If true then this point is the first one from a whole bunch of points
154  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
155  *  \param snappers List of snappers to try to snap to
156  *  \return Snapped point.
157  */
159 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapPreferences::PointType point_type,
160                                              Geom::Point const &p,
161                                              bool first_point,
162                                              Geom::OptRect const &bbox_to_snap) const
164         if (_desktop->canvas->context_snap_delay_active == false) {
165                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
166                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
167         }
169         if (!someSnapperMightSnap()) {
170         return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
171     }
173     std::vector<SPItem const *> *items_to_ignore;
174     if (_item_to_ignore) { // If we have only a single item to ignore
175         // then build a list containing this single item;
176         // This single-item list will prevail over any other _items_to_ignore list, should that exist
177         items_to_ignore = new std::vector<SPItem const *>;
178         items_to_ignore->push_back(_item_to_ignore);
179     } else {
180         items_to_ignore = _items_to_ignore;
181     }
183     SnappedConstraints sc;
184     SnapperList const snappers = getSnappers();
186     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
187         (*i)->freeSnap(sc, point_type, p, first_point, bbox_to_snap, items_to_ignore, _unselected_nodes);
188     }
190     if (_item_to_ignore) {
191         delete items_to_ignore;
192     }
194     return findBestSnap(p, sc, false);
197 // When pasting, we would like to snap to the grid. Problem is that we don't know which nodes were
198 // aligned to the grid at the time of copying, so we don't know which nodes to snap. If we'd snap an
199 // unaligned node to the grid, previously aligned nodes would become unaligned. That's undesirable.
200 // Instead we will make sure that the offset between the source and the copy is a multiple of the grid
201 // pitch. If the source was aligned, then the copy will therefore also be aligned
202 // PS: Wether we really find a multiple also depends on the snapping range!
203 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
205     if (!snapprefs.getSnapEnabledGlobally()) // No need to check for snapprefs.getSnapPostponedGlobally() here
206         return t;
208     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
210     if (_desktop && _desktop->gridsEnabled()) {
211         bool success = false;
212         Geom::Point nearest_multiple;
213         Geom::Coord nearest_distance = NR_HUGE;
215         // It will snap to the grid for which we find the closest snap. This might be a different
216         // grid than to which the objects were initially aligned. I don't see an easy way to fix
217         // this, so when using multiple grids one can get unexpected results
219         // Cannot use getGridSnappers() because we need both the grids AND their snappers
220         // Therefore we iterate through all grids manually
221         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
222             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
223             const Inkscape::Snapper* snapper = grid->snapper;
224             if (snapper && snapper->ThisSnapperMightSnap()) {
225                 // To find the nearest multiple of the grid pitch for a given translation t, we
226                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
227                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
228                 // in the translation t
229                 Geom::Point const t_offset = t + grid->origin;
230                 SnappedConstraints sc;
231                 // Only the first three parameters are being used for grid snappers
232                 snapper->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_NODE, t_offset, TRUE, Geom::OptRect(), NULL, NULL);
233                 // Find the best snap for this grid, including intersections of the grid-lines
234                 Inkscape::SnappedPoint s = findBestSnap(t_offset, sc, false);
235                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
236                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
237                     // doesn't tell us anything about which node to snap
238                     success = true;
239                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
240                     nearest_distance = s.getSnapDistance();
241                 }
242             }
243         }
245         if (success)
246             return nearest_multiple;
247     }
249     return t;
252 /**
253  *  Try to snap a point to any interested snappers.  A snap will only occur along
254  *  a line described by a Inkscape::Snapper::ConstraintLine.
255  *
256  *  \param point_type Type of point.
257  *  \param p Point.
258  *  \param first_point If true then this point is the first one from a whole bunch of points
259  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
260  *  \param constraint Constraint line.
261  *  \return Snapped point.
262  */
264 void SnapManager::constrainedSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
265                                                     Geom::Point &p,
266                                                     Inkscape::Snapper::ConstraintLine const &constraint,
267                                                     bool first_point,
268                                                     Geom::OptRect const &bbox_to_snap) const
270     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, constraint, first_point, bbox_to_snap);
271     s.getPoint(p);
274 /**
275  *  Try to snap a point to any interested snappers.  A snap will only occur along
276  *  a line described by a Inkscape::Snapper::ConstraintLine.
277  *
278  *  \param point_type Type of point.
279  *  \param p Point.
280  *  \param first_point If true then this point is the first one from a whole bunch of points
281  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
282  *  \param constraint Constraint line.
283  *  \return Snapped point.
284  */
286 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapPreferences::PointType point_type,
287                                                     Geom::Point const &p,
288                                                     Inkscape::Snapper::ConstraintLine const &constraint,
289                                                     bool first_point,
290                                                     Geom::OptRect const &bbox_to_snap) const
292         if (_desktop->canvas->context_snap_delay_active == false) {
293                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
294                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
295         }
297         if (!someSnapperMightSnap()) {
298         return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
299     }
301     std::vector<SPItem const *> *items_to_ignore;
302     if (_item_to_ignore) { // If we have only a single item to ignore
303         // then build a list containing this single item;
304         // This single-item list will prevail over any other _items_to_ignore list, should that exist
305         items_to_ignore = new std::vector<SPItem const *>;
306         items_to_ignore->push_back(_item_to_ignore);
307     } else {
308         items_to_ignore = _items_to_ignore;
309     }
311     SnappedConstraints sc;
312     SnapperList const snappers = getSnappers();
313     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
314         (*i)->constrainedSnap(sc, point_type, p, first_point, bbox_to_snap, constraint, items_to_ignore);
315     }
317     if (_item_to_ignore) {
318         delete items_to_ignore;
319     }
321     return findBestSnap(p, sc, true);
324 void SnapManager::guideSnap(Geom::Point &p, Geom::Point const &guide_normal) const
326     // This method is used to snap a guide to nodes, while dragging the guide around
328         if (_desktop->canvas->context_snap_delay_active == false) {
329                 g_warning("context_snap_delay_active has not been set to true by the current context. Please report this!");
330                 // When the context goes into dragging-mode, then Inkscape should call this: sp_canvas_set_snap_delay_active(desktop->canvas, true);
331         }
333     if ( !(object.GuidesMightSnap() && snapprefs.getSnapEnabledGlobally()) || snapprefs.getSnapPostponedGlobally() ) {
334         return;
335     }
337     SnappedConstraints sc;
338     object.guideSnap(sc, p, guide_normal);
340     Inkscape::SnappedPoint const s = findBestSnap(p, sc, false);
341     s.getPoint(p);
345 /**
346  *  Main internal snapping method, which is called by the other, friendlier, public
347  *  methods.  It's a bit hairy as it has lots of parameters, but it saves on a lot
348  *  of duplicated code.
349  *
350  *  \param type Type of points being snapped.
351  *  \param points List of points to snap (i.e. untransformed).
352  *  \param pointer Location of the mouse pointer, at the time when dragging started (i.e. "untransformed")
353  *  \param constrained true if the snap is constrained.
354  *  \param constraint Constraint line to use, if `constrained' is true, otherwise undefined.
355  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
356  *  \param transformation Description of the transformation; details depend on the type.
357  *  \param origin Origin of the transformation, if applicable.
358  *  \param dim Dimension of the transformation, if applicable.
359  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
360  */
362 Inkscape::SnappedPoint SnapManager::_snapTransformed(
363     Inkscape::SnapPreferences::PointType type,
364     std::vector<Geom::Point> const &points,
365     Geom::Point const &pointer,
366     bool constrained,
367     Inkscape::Snapper::ConstraintLine const &constraint,
368     Transformation transformation_type,
369     Geom::Point const &transformation,
370     Geom::Point const &origin,
371     Geom::Dim2 dim,
372     bool uniform) const
374     /* We have a list of points, which we are proposing to transform in some way.  We need to see
375     ** if any of these points, when transformed, snap to anything.  If they do, we return the
376     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
377     */
379     /* Quick check to see if we have any snappers that are enabled
380     ** Also used to globally disable all snapping
381     */
382     if (someSnapperMightSnap() == false) {
383         return Inkscape::SnappedPoint();
384     }
386     std::vector<Geom::Point> transformed_points;
387     Geom::Rect bbox;
389     for (std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
391         /* Work out the transformed version of this point */
392         Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
394         // add the current transformed point to the box hulling all transformed points
395         if (i == points.begin()) {
396             bbox = Geom::Rect(transformed, transformed);
397         } else {
398             bbox.expandTo(transformed);
399         }
401         transformed_points.push_back(transformed);
402     }
404     /* The current best transformation */
405     Geom::Point best_transformation = transformation;
407     /* The current best metric for the best transformation; lower is better, NR_HUGE
408     ** means that we haven't snapped anything.
409     */
410     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
411     Inkscape::SnappedPoint best_snapped_point;
412     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
413     g_assert(best_snapped_point.getAtIntersection() == false);
415     std::vector<Geom::Point>::const_iterator j = transformed_points.begin();
417     // std::cout << std::endl;
418     for (std::vector<Geom::Point>::const_iterator i = points.begin(); i != points.end(); i++) {
420         /* Snap it */
421         Inkscape::SnappedPoint snapped_point;
422         Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
423         Geom::Point const b = (*i - origin); // vector to original point
425         if (constrained) {
426             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
427                 // When uniformly scaling, each point will have its own unique constraint line,
428                 // running from the scaling origin to the original untransformed point. We will
429                 // calculate that line here
430                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, b);
431             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
432                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i), component_vectors[dim]);
433             } else if (transformation_type == TRANSLATION) {
434                 // When doing a constrained translation, all points will move in the same direction, i.e.
435                 // either horizontally or vertically. The lines along which they move are therefore all
436                 // parallel, but might not be colinear. Therefore we will have to set the point through
437                 // which the constraint-line runs here, for each point individually.
438                 dedicated_constraint.setPoint(*i);
439             } // else: leave the original constraint, e.g. for skewing
440             if (transformation_type == SCALE && !uniform) {
441                 g_warning("Non-uniform constrained scaling is not supported!");
442             }
443             snapped_point = constrainedSnap(type, *j, dedicated_constraint, i == points.begin(), bbox);
444         } else {
445             bool const c1 = fabs(b[Geom::X]) < 1e-6;
446             bool const c2 = fabs(b[Geom::Y]) < 1e-6;
447             if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
448                 // When scaling, a point aligned either horizontally or vertically with the origin can only
449                 // move in that specific direction; therefore it should only snap in that direction, otherwise
450                 // we will get snapped points with an invalid transformation
451                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, component_vectors[c1]);
452                 snapped_point = constrainedSnap(type, *j, dedicated_constraint, i == points.begin(), bbox);
453             } else {
454                 snapped_point = freeSnap(type, *j, i == points.begin(), bbox);
455             }
456         }
457         // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
458         snapped_point.setPointerDistance(Geom::L2(pointer - *i));
460         Geom::Point result;
461         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
463         if (snapped_point.getSnapped()) {
464             /* We snapped.  Find the transformation that describes where the snapped point has
465             ** ended up, and also the metric for this transformation.
466             */
467             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
468             //Geom::Point const b = (*i - origin); // vector to original point
470             switch (transformation_type) {
471                 case TRANSLATION:
472                     result = snapped_point.getPoint() - *i;
473                     /* Consider the case in which a box is almost aligned with a grid in both
474                      * horizontal and vertical directions. The distance to the intersection of
475                      * the grid lines will always be larger then the distance to a single grid
476                      * line. If we prefer snapping to an intersection instead of to a single
477                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
478                      * snapped distance will be used as a metric. Please note that the snapped
479                      * distance is defined as the distance to the nearest line of the intersection,
480                      * and not to the intersection itself!
481                      */
482                     // Only for translations, the relevant metric will be the real snapped distance,
483                     // so we don't have to do anything special here
484                     break;
485                 case SCALE:
486                 {
487                     result = Geom::Point(NR_HUGE, NR_HUGE);
488                     // If this point *i is horizontally or vertically aligned with
489                     // the origin of the scaling, then it will scale purely in X or Y
490                     // We can therefore only calculate the scaling in this direction
491                     // and the scaling factor for the other direction should remain
492                     // untouched (unless scaling is uniform ofcourse)
493                     for (int index = 0; index < 2; index++) {
494                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
495                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
496                                 result[index] = a[index] / b[index]; // then calculate it!
497                             }
498                             // we might leave result[1-index] = NR_HUGE
499                             // if scaling didn't occur in the other direction
500                         }
501                     }
502                     // Compare the resulting scaling with the desired scaling
503                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
504                     break;
505                 }
506                 case STRETCH:
507                     result = Geom::Point(NR_HUGE, NR_HUGE);
508                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
509                         result[dim] = a[dim] / b[dim];
510                         result[1-dim] = uniform ? result[dim] : 1;
511                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
512                         if (uniform && fabs(b[1-dim]) > 1e-6) {
513                            result[1-dim] = a[1-dim] / b[1-dim];
514                            result[dim] = result[1-dim];
515                         }
516                     }
517                     // Store the metric for this transformation as a virtual distance
518                     snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
519                     snapped_point.setSecondSnapDistance(NR_HUGE);
520                     break;
521                 case SKEW:
522                     result[0] = (snapped_point.getPoint()[dim] - (*i)[dim]) / ((*i)[1 - dim] - origin[1 - dim]); // skew factor
523                     result[1] = transformation[1]; // scale factor
524                     // Store the metric for this transformation as a virtual distance
525                     snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
526                     snapped_point.setSecondSnapDistance(NR_HUGE);
527                     break;
528                 default:
529                     g_assert_not_reached();
530             }
532             // When scaling, we're considering the best transformation in each direction separately. We will have a metric in each
533             // direction, whereas for all other transformation we only a single one-dimensional metric. That's why we need to handle
534             // the scaling metric differently
535             if (transformation_type == SCALE) {
536                 for (int index = 0; index < 2; index++) {
537                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
538                         best_transformation[index] = result[index];
539                         best_scale_metric[index] = fabs(scale_metric[index]);
540                         // When scaling, we're considering the best transformation in each direction separately
541                         // Therefore two different snapped points might together make a single best transformation
542                         // We will however return only a single snapped point (e.g. to display the snapping indicator)
543                         best_snapped_point = snapped_point;
544                         // std::cout << "SEL ";
545                     } // else { std::cout << "    ";}
546                 }
547                 if (uniform) {
548                     if (best_scale_metric[0] < best_scale_metric[1]) {
549                         best_transformation[1] = best_transformation[0];
550                         best_scale_metric[1] = best_scale_metric[0];
551                     } else {
552                         best_transformation[0] = best_transformation[1];
553                         best_scale_metric[0] = best_scale_metric[1];
554                     }
555                 }
556             } else { // For all transformations other than scaling
557                 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
558                     best_transformation = result;
559                     best_snapped_point = snapped_point;
560                 }
561             }
562         }
564         j++;
565     }
567     Geom::Coord best_metric;
568     if (transformation_type == SCALE) {
569         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
570         for (int index = 0; index < 2; index++) {
571             if (best_transformation[index] == NR_HUGE) {
572                 if (uniform && best_transformation[1-index] < NR_HUGE) {
573                     best_transformation[index] = best_transformation[1-index];
574                 } else {
575                     best_transformation[index] = transformation[index];
576                 }
577             }
578         }
579         best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
580     } else { // For all transformations other than scaling
581         best_metric = best_snapped_point.getSnapDistance();
582     }
584     best_snapped_point.setTransformation(best_transformation);
585     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
586     // These rounding errors might be caused by NRRects, see bug #1584301
587     best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
588     return best_snapped_point;
592 /**
593  *  Try to snap a list of points to any interested snappers after they have undergone
594  *  a translation.
595  *
596  *  \param point_type Type of points.
597  *  \param p Points.
598  *  \param tr Proposed translation.
599  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
600  */
602 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
603                                                         std::vector<Geom::Point> const &p,
604                                                         Geom::Point const &pointer,
605                                                         Geom::Point const &tr) const
607     if (p.size() == 1) {
608         _displaySnapsource(point_type, _transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false));
609     }
611     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
615 /**
616  *  Try to snap a list of points to any interested snappers after they have undergone a
617  *  translation.  A snap will only occur along a line described by a
618  *  Inkscape::Snapper::ConstraintLine.
619  *
620  *  \param point_type Type of points.
621  *  \param p Points.
622  *  \param constraint Constraint line.
623  *  \param tr Proposed translation.
624  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
625  */
627 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
628                                                                std::vector<Geom::Point> const &p,
629                                                                Geom::Point const &pointer,
630                                                                Inkscape::Snapper::ConstraintLine const &constraint,
631                                                                Geom::Point const &tr) const
633     if (p.size() == 1) {
634         _displaySnapsource(point_type, _transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false));
635     }
637     return _snapTransformed(point_type, p, pointer, true, constraint, TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
641 /**
642  *  Try to snap a list of points to any interested snappers after they have undergone
643  *  a scale.
644  *
645  *  \param point_type Type of points.
646  *  \param p Points.
647  *  \param s Proposed scale.
648  *  \param o Origin of proposed scale.
649  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
650  */
652 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::SnapPreferences::PointType point_type,
653                                                   std::vector<Geom::Point> const &p,
654                                                   Geom::Point const &pointer,
655                                                   Geom::Scale const &s,
656                                                   Geom::Point const &o) const
658     if (p.size() == 1) {
659         _displaySnapsource(point_type, _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false));
660     }
662     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
666 /**
667  *  Try to snap a list of points to any interested snappers after they have undergone
668  *  a scale.  A snap will only occur along a line described by a
669  *  Inkscape::Snapper::ConstraintLine.
670  *
671  *  \param point_type Type of points.
672  *  \param p Points.
673  *  \param s Proposed scale.
674  *  \param o Origin of proposed scale.
675  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
676  */
678 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::SnapPreferences::PointType point_type,
679                                                          std::vector<Geom::Point> const &p,
680                                                          Geom::Point const &pointer,
681                                                          Geom::Scale const &s,
682                                                          Geom::Point const &o) const
684     // When constrained scaling, only uniform scaling is supported.
685     if (p.size() == 1) {
686         _displaySnapsource(point_type, _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true));
687     }
689     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
693 /**
694  *  Try to snap a list of points to any interested snappers after they have undergone
695  *  a stretch.
696  *
697  *  \param point_type Type of points.
698  *  \param p Points.
699  *  \param s Proposed stretch.
700  *  \param o Origin of proposed stretch.
701  *  \param d Dimension in which to apply proposed stretch.
702  *  \param u true if the stretch should be uniform (ie to be applied equally in both dimensions)
703  *  \return Snapped stretch, if a snap occurred, and a flag indicating whether a snap occurred.
704  */
706 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::SnapPreferences::PointType point_type,
707                                                             std::vector<Geom::Point> const &p,
708                                                             Geom::Point const &pointer,
709                                                             Geom::Coord const &s,
710                                                             Geom::Point const &o,
711                                                             Geom::Dim2 d,
712                                                             bool u) const
714     if (p.size() == 1) {
715         _displaySnapsource(point_type, _transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u));
716     }
718     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
722 /**
723  *  Try to snap a list of points to any interested snappers after they have undergone
724  *  a skew.
725  *
726  *  \param point_type Type of points.
727  *  \param p Points.
728  *  \param s Proposed skew.
729  *  \param o Origin of proposed skew.
730  *  \param d Dimension in which to apply proposed skew.
731  *  \return Snapped skew, if a snap occurred, and a flag indicating whether a snap occurred.
732  */
734 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::SnapPreferences::PointType point_type,
735                                                  std::vector<Geom::Point> const &p,
736                                                  Geom::Point const &pointer,
737                                                  Inkscape::Snapper::ConstraintLine const &constraint,
738                                                  Geom::Point const &s,
739                                                  Geom::Point const &o,
740                                                  Geom::Dim2 d) const
742     // "s" contains skew factor in s[0], and scale factor in s[1]
744     // Snapping the nodes of the boundingbox of a selection that is being transformed, will only work if
745     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
746     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
747     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
748     // of bounding boxes is not allowed here.
749     g_assert(!(point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX));
751     if (p.size() == 1) {
752         _displaySnapsource(point_type, _transformPoint(p.at(0), SKEW, s, o, d, false));
753     }
755     return _snapTransformed(point_type, p, pointer, true, constraint, SKEW, s, o, d, false);
758 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p, SnappedConstraints &sc, bool constrained) const
761     /*
762     std::cout << "Type and number of snapped constraints: " << std::endl;
763     std::cout << "  Points      : " << sc.points.size() << std::endl;
764     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
765     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
766     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
767     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
768     */
770     // Store all snappoints
771     std::list<Inkscape::SnappedPoint> sp_list;
773     // search for the closest snapped point
774     Inkscape::SnappedPoint closestPoint;
775     if (getClosestSP(sc.points, closestPoint)) {
776         sp_list.push_back(closestPoint);
777     }
779     // search for the closest snapped curve
780     Inkscape::SnappedCurve closestCurve;
781     if (getClosestCurve(sc.curves, closestCurve)) {
782         sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
783     }
785     if (snapprefs.getSnapIntersectionCS()) {
786         // search for the closest snapped intersection of curves
787         Inkscape::SnappedPoint closestCurvesIntersection;
788         if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection, _desktop->dt2doc())) {
789             sp_list.push_back(closestCurvesIntersection);
790         }
791     }
793     // search for the closest snapped grid line
794     Inkscape::SnappedLine closestGridLine;
795     if (getClosestSL(sc.grid_lines, closestGridLine)) {
796         closestGridLine.setTarget(Inkscape::SNAPTARGET_GRID);
797         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
798     }
800     // search for the closest snapped guide line
801     Inkscape::SnappedLine closestGuideLine;
802     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
803         closestGuideLine.setTarget(Inkscape::SNAPTARGET_GUIDE);
804         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
805     }
807     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
808     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
810     // When doing a constrained snap however, we're already at an intersection of the constrained line and
811     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
812     // no need to look for additional intersections
813     if (!constrained) {
814         // search for the closest snapped intersection of grid lines
815         Inkscape::SnappedPoint closestGridPoint;
816         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
817             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
818             sp_list.push_back(closestGridPoint);
819         }
821         // search for the closest snapped intersection of guide lines
822         Inkscape::SnappedPoint closestGuidePoint;
823         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
824             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
825             sp_list.push_back(closestGuidePoint);
826         }
828         // search for the closest snapped intersection of grid with guide lines
829         if (snapprefs.getSnapIntersectionGG()) {
830             Inkscape::SnappedPoint closestGridGuidePoint;
831             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
832                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
833                 sp_list.push_back(closestGridGuidePoint);
834             }
835         }
836     }
838     // now let's see which snapped point gets a thumbs up
839     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
840     // std::cout << "Finding the best snap..." << std::endl;
841     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
842         // first find out if this snapped point is within snapping range
843         // std::cout << "sp = " << from_2geom((*i).getPoint());
844         if ((*i).getSnapDistance() <= (*i).getTolerance()) {
845             // if it's the first point, or if it is closer than the best snapped point so far
846             if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
847                 // then prefer this point over the previous one
848                 bestSnappedPoint = *i;
849             }
850         }
851         // std::cout << std::endl;
852     }
854     // Update the snap indicator, if requested
855     if (_snapindicator) {
856         if (bestSnappedPoint.getSnapped()) {
857             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
858         } else {
859             _desktop->snapindicator->remove_snaptarget();
860         }
861     }
863     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
864     return bestSnappedPoint;
867 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, SPItem const *item_to_ignore, std::vector<Geom::Point> *unselected_nodes)
869     g_assert(desktop != NULL);
870     _item_to_ignore = item_to_ignore;
871     _items_to_ignore = NULL;
872     _desktop = desktop;
873     _snapindicator = snapindicator;
874     _unselected_nodes = unselected_nodes;
877 void SnapManager::setup(SPDesktop const *desktop, bool snapindicator, std::vector<SPItem const *> &items_to_ignore, std::vector<Geom::Point> *unselected_nodes)
879     g_assert(desktop != NULL);
880     _item_to_ignore = NULL;
881     _items_to_ignore = &items_to_ignore;
882     _desktop = desktop;
883     _snapindicator = snapindicator;
884     _unselected_nodes = unselected_nodes;
887 SPDocument *SnapManager::getDocument() const
889     return _named_view->document;
892 Geom::Point SnapManager::_transformPoint(Geom::Point const &p,
893                                         Transformation const transformation_type,
894                                         Geom::Point const &transformation,
895                                         Geom::Point const &origin,
896                                         Geom::Dim2 const dim,
897                                         bool const uniform) const
899     /* Work out the transformed version of this point */
900     Geom::Point transformed;
901     switch (transformation_type) {
902         case TRANSLATION:
903             transformed = p + transformation;
904             break;
905         case SCALE:
906             transformed = (p - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
907             break;
908         case STRETCH:
909         {
910             Geom::Scale s(1, 1);
911             if (uniform)
912                 s[Geom::X] = s[Geom::Y] = transformation[dim];
913             else {
914                 s[dim] = transformation[dim];
915                 s[1 - dim] = 1;
916             }
917             transformed = ((p - origin) * s) + origin;
918             break;
919         }
920         case SKEW:
921             // Apply the skew factor
922             transformed[dim] = p[dim] + transformation[0] * (p[1 - dim] - origin[1 - dim]);
923             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
924             // Apply that scale factor here
925             transformed[1-dim] = (p - origin)[1 - dim] * transformation[1] + origin[1 - dim];
926             break;
927         default:
928             g_assert_not_reached();
929     }
931     return transformed;
934 void SnapManager::_displaySnapsource(Inkscape::SnapPreferences::PointType point_type, Geom::Point const &p) const {
936     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
937     if (prefs->getBool("/options/snapclosestonly/value")) {
938         bool p_is_a_node = point_type & Inkscape::SnapPreferences::SNAPPOINT_NODE;
939         bool p_is_a_bbox = point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
940         if (snapprefs.getSnapEnabledGlobally() && ((p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
941             _desktop->snapindicator->set_new_snapsource(p);
942         } else {
943             _desktop->snapindicator->remove_snapsource();
944         }
945     }
948 /*
949   Local Variables:
950   mode:c++
951   c-file-style:"stroustrup"
952   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
953   indent-tabs-mode:nil
954   fill-column:99
955   End:
956 */
957 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :