Code

Fix two "snap window not opened" warnings
[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 #include "event-context.h"
36 using std::vector;
38 /**
39  *  Construct a SnapManager for a SPNamedView.
40  *
41  *  \param v `Owning' SPNamedView.
42  */
44 SnapManager::SnapManager(SPNamedView const *v) :
45     guide(this, 0),
46     object(this, 0),
47     snapprefs(),
48     _named_view(v)
49 {
50 }
52 /**
53  *  \return List of snappers that we use.
54  */
55 SnapManager::SnapperList
56 SnapManager::getSnappers() const
57 {
58     SnapManager::SnapperList s;
59     s.push_back(&guide);
60     s.push_back(&object);
62     SnapManager::SnapperList gs = getGridSnappers();
63     s.splice(s.begin(), gs);
65     return s;
66 }
68 /**
69  *  \return List of gridsnappers that we use.
70  */
71 SnapManager::SnapperList
72 SnapManager::getGridSnappers() const
73 {
74     SnapperList s;
76     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
77     if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
78         for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
79             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
80             s.push_back(grid->snapper);
81         }
82     }
84     return s;
85 }
87 /**
88  * \return true if one of the snappers will try to snap something.
89  */
91 bool SnapManager::someSnapperMightSnap() const
92 {
93     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
94         return false;
95     }
97     SnapperList const s = getSnappers();
98     SnapperList::const_iterator i = s.begin();
99     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
100         i++;
101     }
103     return (i != s.end());
106 /**
107  * \return true if one of the snappers will try to snap something.
108  */
110 bool SnapManager::gridSnapperMightSnap() const
112     if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
113         return false;
114     }
116     SnapperList const s = getGridSnappers();
117     SnapperList::const_iterator i = s.begin();
118     while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
119         i++;
120     }
122     return (i != s.end());
125 /**
126  *  Try to snap a point to any of the specified snappers.
127  *
128  *  \param point_type Type of point.
129  *  \param p Point.
130  *  \param first_point If true then this point is the first one from a whole bunch of points
131  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
132  *  \param snappers List of snappers to try to snap to
133  *  \return Snapped point.
134  */
136 void SnapManager::freeSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
137                                       Geom::Point &p,
138                                       Inkscape::SnapSourceType const source_type,
139                                       bool first_point,
140                                       Geom::OptRect const &bbox_to_snap) const
142     Inkscape::SnappedPoint const s = freeSnap(point_type, p, source_type, first_point, bbox_to_snap);
143     s.getPoint(p);
147 /**
148  *  Try to snap a point to any of the specified snappers.
149  *
150  *  \param point_type Type of point.
151  *  \param p Point.
152  *  \param first_point If true then this point is the first one from a whole bunch of points
153  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
154  *  \param snappers List of snappers to try to snap to
155  *  \return Snapped point.
156  */
158 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapPreferences::PointType point_type,
159                                              Geom::Point const &p,
160                                              Inkscape::SnapSourceType const &source_type,
161                                              bool first_point,
162                                              Geom::OptRect const &bbox_to_snap) const
164         if (_desktop->event_context && _desktop->event_context->_snap_window_open == false) {
165                 g_warning("The current tool tries to snap, but it hasn't yet opened the snap window. Please report this!");
166                 // When the context goes into dragging-mode, then Inkscape should call this: sp_event_context_snap_window_open(event_context);
167         }
169         //std::cout << "SnapManager::freeSnap -> postponed: " << snapprefs.getSnapPostponedGlobally() << std::endl;
171         if (!someSnapperMightSnap()) {
172         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
173     }
175     std::vector<SPItem const *> *items_to_ignore;
176     if (_item_to_ignore) { // If we have only a single item to ignore
177         // then build a list containing this single item;
178         // This single-item list will prevail over any other _items_to_ignore list, should that exist
179         items_to_ignore = new std::vector<SPItem const *>;
180         items_to_ignore->push_back(_item_to_ignore);
181     } else {
182         items_to_ignore = _items_to_ignore;
183     }
185     SnappedConstraints sc;
186     SnapperList const snappers = getSnappers();
188     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
189         (*i)->freeSnap(sc, point_type, p, source_type, first_point, bbox_to_snap, items_to_ignore, _unselected_nodes);
190     }
192     if (_item_to_ignore) {
193         delete items_to_ignore;
194     }
196     return findBestSnap(p, source_type, sc, false);
199 // When pasting, we would like to snap to the grid. Problem is that we don't know which nodes were
200 // aligned to the grid at the time of copying, so we don't know which nodes to snap. If we'd snap an
201 // unaligned node to the grid, previously aligned nodes would become unaligned. That's undesirable.
202 // Instead we will make sure that the offset between the source and the copy is a multiple of the grid
203 // pitch. If the source was aligned, then the copy will therefore also be aligned
204 // PS: Whether we really find a multiple also depends on the snapping range!
205 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t) const
207     if (!snapprefs.getSnapEnabledGlobally()) // No need to check for snapprefs.getSnapPostponedGlobally() here
208         return t;
210     //FIXME: this code should actually do this: add new grid snappers that are active for this desktop. now it just adds all gridsnappers
212     if (_desktop && _desktop->gridsEnabled()) {
213         bool success = false;
214         Geom::Point nearest_multiple;
215         Geom::Coord nearest_distance = NR_HUGE;
217         // It will snap to the grid for which we find the closest snap. This might be a different
218         // grid than to which the objects were initially aligned. I don't see an easy way to fix
219         // this, so when using multiple grids one can get unexpected results
221         // Cannot use getGridSnappers() because we need both the grids AND their snappers
222         // Therefore we iterate through all grids manually
223         for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
224             Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
225             const Inkscape::Snapper* snapper = grid->snapper;
226             if (snapper && snapper->ThisSnapperMightSnap()) {
227                 // To find the nearest multiple of the grid pitch for a given translation t, we
228                 // will use the grid snapper. Simply snapping the value t to the grid will do, but
229                 // only if the origin of the grid is at (0,0). If it's not then compensate for this
230                 // in the translation t
231                 Geom::Point const t_offset = t + grid->origin;
232                 SnappedConstraints sc;
233                 // Only the first three parameters are being used for grid snappers
234                 snapper->freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_NODE, t_offset, Inkscape::SNAPSOURCE_UNDEFINED, TRUE, Geom::OptRect(), NULL, NULL);
235                 // Find the best snap for this grid, including intersections of the grid-lines
236                 Inkscape::SnappedPoint s = findBestSnap(t_offset, Inkscape::SNAPSOURCE_UNDEFINED, sc, false);
237                 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
238                     // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
239                     // doesn't tell us anything about which node to snap
240                     success = true;
241                     nearest_multiple = s.getPoint() - to_2geom(grid->origin);
242                     nearest_distance = s.getSnapDistance();
243                 }
244             }
245         }
247         if (success)
248             return nearest_multiple;
249     }
251     return t;
254 /**
255  *  Try to snap a point to any interested snappers.  A snap will only occur along
256  *  a line described by a Inkscape::Snapper::ConstraintLine.
257  *
258  *  \param point_type Type of point.
259  *  \param p Point.
260  *  \param first_point If true then this point is the first one from a whole bunch of points
261  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
262  *  \param constraint Constraint line.
263  *  \return Snapped point.
264  */
266 void SnapManager::constrainedSnapReturnByRef(Inkscape::SnapPreferences::PointType point_type,
267                                              Geom::Point &p,
268                                              Inkscape::SnapSourceType const source_type,
269                                              Inkscape::Snapper::ConstraintLine const &constraint,
270                                              bool const snap_projection,
271                                              bool first_point,
272                                              Geom::OptRect const &bbox_to_snap) const
274     Inkscape::SnappedPoint const s = constrainedSnap(point_type, p, source_type, constraint, snap_projection, first_point, bbox_to_snap);
275     s.getPoint(p);
279 /**
280  *  Try to snap a point to any interested snappers.  A snap will only occur along
281  *  a line described by a Inkscape::Snapper::ConstraintLine.
282  *
283  *  \param point_type Type of point.
284  *  \param p Point.
285  *  \param first_point If true then this point is the first one from a whole bunch of points
286  *  \param points_to_snap The whole bunch of points, all from the same selection and having the same transformation
287  *  \param constraint Constraint line.
288  *  \return Snapped point.
289  */
291 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapPreferences::PointType point_type,
292                                                     Geom::Point const &p,
293                                                     Inkscape::SnapSourceType const &source_type,
294                                                     Inkscape::Snapper::ConstraintLine const &constraint,
295                                                     bool /*snap_projection*/,
296                                                     bool first_point,
297                                                     Geom::OptRect const &bbox_to_snap) const
299         if (_desktop->event_context && _desktop->event_context->_snap_window_open == false) {
300                 g_warning("The current tool tries to snap, but it hasn't yet opened the snap window. Please report this!");
301                 // When the context goes into dragging-mode, then Inkscape should call this: sp_event_context_snap_window_open(event_context);
302         }
304         if (!someSnapperMightSnap()) {
305         return Inkscape::SnappedPoint(p, source_type, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
306     }
308     std::vector<SPItem const *> *items_to_ignore;
309     if (_item_to_ignore) { // If we have only a single item to ignore
310         // then build a list containing this single item;
311         // This single-item list will prevail over any other _items_to_ignore list, should that exist
312         items_to_ignore = new std::vector<SPItem const *>;
313         items_to_ignore->push_back(_item_to_ignore);
314     } else {
315         items_to_ignore = _items_to_ignore;
316     }
318     Geom::Point pp = constraint.projection(p);
320     SnappedConstraints sc;
321     SnapperList const snappers = getSnappers();
322     for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
323         (*i)->constrainedSnap(sc, point_type, pp, source_type, first_point, bbox_to_snap, constraint, items_to_ignore);
324     }
326     if (_item_to_ignore) {
327         delete items_to_ignore;
328     }
330     return findBestSnap(p, source_type, sc, true);
333 void SnapManager::guideSnap(Geom::Point &p, Geom::Point const &guide_normal) const
335     // This method is used to snap a guide to nodes or to other guides, while dragging the guide around. Will not snap to grids!
337         if (_desktop->event_context && _desktop->event_context->_snap_window_open == false) {
338                         g_warning("The current tool tries to snap, but it hasn't yet opened the snap window. Please report this!");
339                         // When the context goes into dragging-mode, then Inkscape should call this: sp_event_context_snap_window_open(event_context);
340         }
342     if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
343         return;
344     }
346     if (!(object.GuidesMightSnap() || snapprefs.getSnapToGuides())) {
347         return;
348     }
350     // Snap to nodes
351     SnappedConstraints sc;
352     if (object.GuidesMightSnap()) {
353         object.guideSnap(sc, p, guide_normal);
354     }
356     // Snap to guides
357     if (snapprefs.getSnapToGuides()) {
358         guide.freeSnap(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, Inkscape::SNAPSOURCE_GUIDE, true, Geom::OptRect(), NULL, NULL);
359     }
361     // We won't snap to grids, what's the use?
363     Inkscape::SnappedPoint const s = findBestSnap(p, Inkscape::SNAPSOURCE_GUIDE, sc, false);
364     s.getPoint(p);
368 /**
369  *  Main internal snapping method, which is called by the other, friendlier, public
370  *  methods.  It's a bit hairy as it has lots of parameters, but it saves on a lot
371  *  of duplicated code.
372  *
373  *  \param type Type of points being snapped.
374  *  \param points List of points to snap (i.e. untransformed).
375  *  \param pointer Location of the mouse pointer, at the time when dragging started (i.e. "untransformed")
376  *  \param constrained true if the snap is constrained.
377  *  \param constraint Constraint line to use, if `constrained' is true, otherwise undefined.
378  *  \param transformation_type Type of transformation to apply to points before trying to snap them.
379  *  \param transformation Description of the transformation; details depend on the type.
380  *  \param origin Origin of the transformation, if applicable.
381  *  \param dim Dimension of the transformation, if applicable.
382  *  \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
383  */
385 Inkscape::SnappedPoint SnapManager::_snapTransformed(
386     Inkscape::SnapPreferences::PointType type,
387     std::vector<std::pair<Geom::Point, int> > const &points,
388     Geom::Point const &pointer,
389     bool constrained,
390     Inkscape::Snapper::ConstraintLine const &constraint,
391     Transformation transformation_type,
392     Geom::Point const &transformation,
393     Geom::Point const &origin,
394     Geom::Dim2 dim,
395     bool uniform) const
397     /* We have a list of points, which we are proposing to transform in some way.  We need to see
398     ** if any of these points, when transformed, snap to anything.  If they do, we return the
399     ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
400     */
402     /* Quick check to see if we have any snappers that are enabled
403     ** Also used to globally disable all snapping
404     */
405     if (someSnapperMightSnap() == false) {
406         return Inkscape::SnappedPoint();
407     }
409     std::vector<std::pair<Geom::Point, int> > transformed_points;
410     Geom::Rect bbox;
412     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
414         /* Work out the transformed version of this point */
415         Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
417         // add the current transformed point to the box hulling all transformed points
418         if (i == points.begin()) {
419             bbox = Geom::Rect(transformed, transformed);
420         } else {
421             bbox.expandTo(transformed);
422         }
424         transformed_points.push_back(std::make_pair(transformed, (*i).second));
425     }
427     /* The current best transformation */
428     Geom::Point best_transformation = transformation;
430     /* The current best metric for the best transformation; lower is better, NR_HUGE
431     ** means that we haven't snapped anything.
432     */
433     Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
434     Inkscape::SnappedPoint best_snapped_point;
435     g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
436     g_assert(best_snapped_point.getAtIntersection() == false);
438     std::vector<std::pair<Geom::Point, int> >::const_iterator j = transformed_points.begin();
440     // std::cout << std::endl;
441     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
443         /* Snap it */
444         Inkscape::SnappedPoint snapped_point;
445         Inkscape::Snapper::ConstraintLine dedicated_constraint = constraint;
446         Geom::Point const b = ((*i).first - origin); // vector to original point
448         if (constrained) {
449             if ((transformation_type == SCALE || transformation_type == STRETCH) && uniform) {
450                 // When uniformly scaling, each point will have its own unique constraint line,
451                 // running from the scaling origin to the original untransformed point. We will
452                 // calculate that line here
453                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, b);
454             } else if (transformation_type == STRETCH) { // when non-uniform stretching {
455                 dedicated_constraint = Inkscape::Snapper::ConstraintLine((*i).first, component_vectors[dim]);
456             } else if (transformation_type == TRANSLATION) {
457                 // When doing a constrained translation, all points will move in the same direction, i.e.
458                 // either horizontally or vertically. The lines along which they move are therefore all
459                 // parallel, but might not be colinear. Therefore we will have to set the point through
460                 // which the constraint-line runs here, for each point individually.
461                 dedicated_constraint.setPoint((*i).first);
462             } // else: leave the original constraint, e.g. for skewing
463             if (transformation_type == SCALE && !uniform) {
464                 g_warning("Non-uniform constrained scaling is not supported!");
465             }
466             snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, false, i == points.begin(), bbox);
467         } else {
468             bool const c1 = fabs(b[Geom::X]) < 1e-6;
469             bool const c2 = fabs(b[Geom::Y]) < 1e-6;
470             if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
471                 // When scaling, a point aligned either horizontally or vertically with the origin can only
472                 // move in that specific direction; therefore it should only snap in that direction, otherwise
473                 // we will get snapped points with an invalid transformation
474                 dedicated_constraint = Inkscape::Snapper::ConstraintLine(origin, component_vectors[c1]);
475                 snapped_point = constrainedSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), dedicated_constraint, false, i == points.begin(), bbox);
476             } else {
477                 snapped_point = freeSnap(type, (*j).first, static_cast<Inkscape::SnapSourceType>((*j).second), i == points.begin(), bbox);
478             }
479         }
480         // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
481         snapped_point.setPointerDistance(Geom::L2(pointer - (*i).first));
483         Geom::Point result;
484         Geom::Point scale_metric(NR_HUGE, NR_HUGE);
486         if (snapped_point.getSnapped()) {
487             /* We snapped.  Find the transformation that describes where the snapped point has
488             ** ended up, and also the metric for this transformation.
489             */
490             Geom::Point const a = (snapped_point.getPoint() - origin); // vector to snapped point
491             //Geom::Point const b = (*i - origin); // vector to original point
493             switch (transformation_type) {
494                 case TRANSLATION:
495                     result = snapped_point.getPoint() - (*i).first;
496                     /* Consider the case in which a box is almost aligned with a grid in both
497                      * horizontal and vertical directions. The distance to the intersection of
498                      * the grid lines will always be larger then the distance to a single grid
499                      * line. If we prefer snapping to an intersection instead of to a single
500                      * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
501                      * snapped distance will be used as a metric. Please note that the snapped
502                      * distance is defined as the distance to the nearest line of the intersection,
503                      * and not to the intersection itself!
504                      */
505                     // Only for translations, the relevant metric will be the real snapped distance,
506                     // so we don't have to do anything special here
507                     break;
508                 case SCALE:
509                 {
510                     result = Geom::Point(NR_HUGE, NR_HUGE);
511                     // If this point *i is horizontally or vertically aligned with
512                     // the origin of the scaling, then it will scale purely in X or Y
513                     // We can therefore only calculate the scaling in this direction
514                     // and the scaling factor for the other direction should remain
515                     // untouched (unless scaling is uniform ofcourse)
516                     for (int index = 0; index < 2; index++) {
517                         if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
518                             if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
519                                 result[index] = a[index] / b[index]; // then calculate it!
520                             }
521                             // we might leave result[1-index] = NR_HUGE
522                             // if scaling didn't occur in the other direction
523                         }
524                     }
525                     // Compare the resulting scaling with the desired scaling
526                     scale_metric = result - transformation; // One or both of its components might be NR_HUGE
527                     break;
528                 }
529                 case STRETCH:
530                     result = Geom::Point(NR_HUGE, NR_HUGE);
531                     if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
532                         result[dim] = a[dim] / b[dim];
533                         result[1-dim] = uniform ? result[dim] : 1;
534                     } else { // STRETCHING might occur for this point, but only when the stretching is uniform
535                         if (uniform && fabs(b[1-dim]) > 1e-6) {
536                            result[1-dim] = a[1-dim] / b[1-dim];
537                            result[dim] = result[1-dim];
538                         }
539                     }
540                     // Store the metric for this transformation as a virtual distance
541                     snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
542                     snapped_point.setSecondSnapDistance(NR_HUGE);
543                     break;
544                 case SKEW:
545                     result[0] = (snapped_point.getPoint()[dim] - ((*i).first)[dim]) / (((*i).first)[1 - dim] - origin[1 - dim]); // skew factor
546                     result[1] = transformation[1]; // scale factor
547                     // Store the metric for this transformation as a virtual distance
548                     snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
549                     snapped_point.setSecondSnapDistance(NR_HUGE);
550                     break;
551                 default:
552                     g_assert_not_reached();
553             }
555             // When scaling, we're considering the best transformation in each direction separately. We will have a metric in each
556             // direction, whereas for all other transformation we only a single one-dimensional metric. That's why we need to handle
557             // the scaling metric differently
558             if (transformation_type == SCALE) {
559                 for (int index = 0; index < 2; index++) {
560                     if (fabs(scale_metric[index]) < fabs(best_scale_metric[index])) {
561                         best_transformation[index] = result[index];
562                         best_scale_metric[index] = fabs(scale_metric[index]);
563                         // When scaling, we're considering the best transformation in each direction separately
564                         // Therefore two different snapped points might together make a single best transformation
565                         // We will however return only a single snapped point (e.g. to display the snapping indicator)
566                         best_snapped_point = snapped_point;
567                         // std::cout << "SEL ";
568                     } // else { std::cout << "    ";}
569                 }
570                 if (uniform) {
571                     if (best_scale_metric[0] < best_scale_metric[1]) {
572                         best_transformation[1] = best_transformation[0];
573                         best_scale_metric[1] = best_scale_metric[0];
574                     } else {
575                         best_transformation[0] = best_transformation[1];
576                         best_scale_metric[0] = best_scale_metric[1];
577                     }
578                 }
579             } else { // For all transformations other than scaling
580                 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
581                     best_transformation = result;
582                     best_snapped_point = snapped_point;
583                 }
584             }
585         }
587         j++;
588     }
590     Geom::Coord best_metric;
591     if (transformation_type == SCALE) {
592         // When scaling, don't ever exit with one of scaling components set to NR_HUGE
593         for (int index = 0; index < 2; index++) {
594             if (best_transformation[index] == NR_HUGE) {
595                 if (uniform && best_transformation[1-index] < NR_HUGE) {
596                     best_transformation[index] = best_transformation[1-index];
597                 } else {
598                     best_transformation[index] = transformation[index];
599                 }
600             }
601         }
602         best_metric = std::min(best_scale_metric[0], best_scale_metric[1]);
603     } else { // For all transformations other than scaling
604         best_metric = best_snapped_point.getSnapDistance();
605     }
607     best_snapped_point.setTransformation(best_transformation);
608     // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
609     // These rounding errors might be caused by NRRects, see bug #1584301
610     best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
611     return best_snapped_point;
615 /**
616  *  Try to snap a list of points to any interested snappers after they have undergone
617  *  a translation.
618  *
619  *  \param point_type Type of points.
620  *  \param p Points.
621  *  \param tr Proposed translation.
622  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
623  */
625 Inkscape::SnappedPoint SnapManager::freeSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
626                                                         std::vector<std::pair<Geom::Point, int> > const &p,
627                                                         Geom::Point const &pointer,
628                                                         Geom::Point const &tr) const
630     if (p.size() == 1) {
631         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
632     }
634     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
638 /**
639  *  Try to snap a list of points to any interested snappers after they have undergone a
640  *  translation.  A snap will only occur along a line described by a
641  *  Inkscape::Snapper::ConstraintLine.
642  *
643  *  \param point_type Type of points.
644  *  \param p Points.
645  *  \param constraint Constraint line.
646  *  \param tr Proposed translation.
647  *  \return Snapped translation, if a snap occurred, and a flag indicating whether a snap occurred.
648  */
650 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslation(Inkscape::SnapPreferences::PointType point_type,
651                                                                std::vector<std::pair<Geom::Point, int> > const &p,
652                                                                Geom::Point const &pointer,
653                                                                Inkscape::Snapper::ConstraintLine const &constraint,
654                                                                Geom::Point const &tr) const
656     if (p.size() == 1) {
657         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), TRANSLATION, tr, Geom::Point(0,0), Geom::X, false), (p.at(0)).second));
658     }
660     return _snapTransformed(point_type, p, pointer, true, constraint, TRANSLATION, tr, Geom::Point(0,0), Geom::X, false);
664 /**
665  *  Try to snap a list of points to any interested snappers after they have undergone
666  *  a scale.
667  *
668  *  \param point_type Type of points.
669  *  \param p Points.
670  *  \param s Proposed scale.
671  *  \param o Origin of proposed scale.
672  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
673  */
675 Inkscape::SnappedPoint SnapManager::freeSnapScale(Inkscape::SnapPreferences::PointType point_type,
676                                                   std::vector<std::pair<Geom::Point, int> > const &p,
677                                                   Geom::Point const &pointer,
678                                                   Geom::Scale const &s,
679                                                   Geom::Point const &o) const
681     if (p.size() == 1) {
682         _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));
683     }
685     return _snapTransformed(point_type, p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
689 /**
690  *  Try to snap a list of points to any interested snappers after they have undergone
691  *  a scale.  A snap will only occur along a line described by a
692  *  Inkscape::Snapper::ConstraintLine.
693  *
694  *  \param point_type Type of points.
695  *  \param p Points.
696  *  \param s Proposed scale.
697  *  \param o Origin of proposed scale.
698  *  \return Snapped scale, if a snap occurred, and a flag indicating whether a snap occurred.
699  */
701 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(Inkscape::SnapPreferences::PointType point_type,
702                                                          std::vector<std::pair<Geom::Point, int> > const &p,
703                                                          Geom::Point const &pointer,
704                                                          Geom::Scale const &s,
705                                                          Geom::Point const &o) const
707     // When constrained scaling, only uniform scaling is supported.
708     if (p.size() == 1) {
709         _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));
710     }
712     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
716 /**
717  *  Try to snap a list of points to any interested snappers after they have undergone
718  *  a stretch.
719  *
720  *  \param point_type Type of points.
721  *  \param p Points.
722  *  \param s Proposed stretch.
723  *  \param o Origin of proposed stretch.
724  *  \param d Dimension in which to apply proposed stretch.
725  *  \param u true if the stretch should be uniform (ie to be applied equally in both dimensions)
726  *  \return Snapped stretch, if a snap occurred, and a flag indicating whether a snap occurred.
727  */
729 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(Inkscape::SnapPreferences::PointType point_type,
730                                                             std::vector<std::pair<Geom::Point, int> > const &p,
731                                                             Geom::Point const &pointer,
732                                                             Geom::Coord const &s,
733                                                             Geom::Point const &o,
734                                                             Geom::Dim2 d,
735                                                             bool u) const
737     if (p.size() == 1) {
738         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u), (p.at(0)).second));
739     }
741     return _snapTransformed(point_type, p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
745 /**
746  *  Try to snap a list of points to any interested snappers after they have undergone
747  *  a skew.
748  *
749  *  \param point_type Type of points.
750  *  \param p Points.
751  *  \param s Proposed skew.
752  *  \param o Origin of proposed skew.
753  *  \param d Dimension in which to apply proposed skew.
754  *  \return Snapped skew, if a snap occurred, and a flag indicating whether a snap occurred.
755  */
757 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(Inkscape::SnapPreferences::PointType point_type,
758                                                  std::vector<std::pair<Geom::Point, int> > const &p,
759                                                  Geom::Point const &pointer,
760                                                  Inkscape::Snapper::ConstraintLine const &constraint,
761                                                  Geom::Point const &s,
762                                                  Geom::Point const &o,
763                                                  Geom::Dim2 d) const
765     // "s" contains skew factor in s[0], and scale factor in s[1]
767     // Snapping the nodes of the boundingbox of a selection that is being transformed, will only work if
768     // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
769     // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
770     // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
771     // of bounding boxes is not allowed here.
772     g_assert(!(point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX));
774     if (p.size() == 1) {
775         _displaySnapsource(point_type, std::make_pair(_transformPoint(p.at(0), SKEW, s, o, d, false), (p.at(0)).second));
776     }
778     return _snapTransformed(point_type, p, pointer, true, constraint, SKEW, s, o, d, false);
781 Inkscape::SnappedPoint SnapManager::findBestSnap(Geom::Point const &p, Inkscape::SnapSourceType const source_type, SnappedConstraints &sc, bool constrained) const
784     /*
785     std::cout << "Type and number of snapped constraints: " << std::endl;
786     std::cout << "  Points      : " << sc.points.size() << std::endl;
787     std::cout << "  Lines       : " << sc.lines.size() << std::endl;
788     std::cout << "  Grid lines  : " << sc.grid_lines.size()<< std::endl;
789     std::cout << "  Guide lines : " << sc.guide_lines.size()<< std::endl;
790     std::cout << "  Curves      : " << sc.curves.size()<< std::endl;
791     */
793     // Store all snappoints
794     std::list<Inkscape::SnappedPoint> sp_list;
796     // search for the closest snapped point
797     Inkscape::SnappedPoint closestPoint;
798     if (getClosestSP(sc.points, closestPoint)) {
799         sp_list.push_back(closestPoint);
800     }
802     // search for the closest snapped curve
803     Inkscape::SnappedCurve closestCurve;
804     if (getClosestCurve(sc.curves, closestCurve)) {
805         sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
806     }
808     if (snapprefs.getSnapIntersectionCS()) {
809         // search for the closest snapped intersection of curves
810         Inkscape::SnappedPoint closestCurvesIntersection;
811         if (getClosestIntersectionCS(sc.curves, p, closestCurvesIntersection, _desktop->dt2doc())) {
812             closestCurvesIntersection.setSource(source_type);
813             sp_list.push_back(closestCurvesIntersection);
814         }
815     }
817     // search for the closest snapped grid line
818     Inkscape::SnappedLine closestGridLine;
819     if (getClosestSL(sc.grid_lines, closestGridLine)) {
820         sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
821     }
823     // search for the closest snapped guide line
824     Inkscape::SnappedLine closestGuideLine;
825     if (getClosestSL(sc.guide_lines, closestGuideLine)) {
826         sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
827     }
829     // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
830     // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
832     // When doing a constrained snap however, we're already at an intersection of the constrained line and
833     // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
834     // no need to look for additional intersections
835     if (!constrained) {
836         // search for the closest snapped intersection of grid lines
837         Inkscape::SnappedPoint closestGridPoint;
838         if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
839             closestGridPoint.setSource(source_type);
840             closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
841             sp_list.push_back(closestGridPoint);
842         }
844         // search for the closest snapped intersection of guide lines
845         Inkscape::SnappedPoint closestGuidePoint;
846         if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
847             closestGuidePoint.setSource(source_type);
848             closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
849             sp_list.push_back(closestGuidePoint);
850         }
852         // search for the closest snapped intersection of grid with guide lines
853         if (snapprefs.getSnapIntersectionGG()) {
854             Inkscape::SnappedPoint closestGridGuidePoint;
855             if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
856                 closestGridGuidePoint.setSource(source_type);
857                 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
858                 sp_list.push_back(closestGridGuidePoint);
859             }
860         }
861     }
863     // now let's see which snapped point gets a thumbs up
864     Inkscape::SnappedPoint bestSnappedPoint = Inkscape::SnappedPoint(p, Inkscape::SNAPSOURCE_UNDEFINED, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false);
865     // std::cout << "Finding the best snap..." << std::endl;
866     for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
867         // first find out if this snapped point is within snapping range
868         // std::cout << "sp = " << from_2geom((*i).getPoint());
869         if ((*i).getSnapDistance() <= (*i).getTolerance()) {
870             // if it's the first point, or if it is closer than the best snapped point so far
871             if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
872                 // then prefer this point over the previous one
873                 bestSnappedPoint = *i;
874             }
875         }
876         // std::cout << std::endl;
877     }
879     // Update the snap indicator, if requested
880     if (_snapindicator) {
881         if (bestSnappedPoint.getSnapped()) {
882             _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
883         } else {
884             _desktop->snapindicator->remove_snaptarget();
885         }
886     }
888     // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
889     return bestSnappedPoint;
892 void SnapManager::setup(SPDesktop const *desktop,
893                         bool snapindicator,
894                         SPItem const *item_to_ignore,
895                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
896                         SPGuide *guide_to_ignore)
898     g_assert(desktop != NULL);
899     _item_to_ignore = item_to_ignore;
900     _items_to_ignore = NULL;
901     _desktop = desktop;
902     _snapindicator = snapindicator;
903     _unselected_nodes = unselected_nodes;
904     _guide_to_ignore = guide_to_ignore;
907 void SnapManager::setup(SPDesktop const *desktop,
908                         bool snapindicator,
909                         std::vector<SPItem const *> &items_to_ignore,
910                         std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
911                         SPGuide *guide_to_ignore)
913     g_assert(desktop != NULL);
914     _item_to_ignore = NULL;
915     _items_to_ignore = &items_to_ignore;
916     _desktop = desktop;
917     _snapindicator = snapindicator;
918     _unselected_nodes = unselected_nodes;
919     _guide_to_ignore = guide_to_ignore;
922 SPDocument *SnapManager::getDocument() const
924     return _named_view->document;
927 Geom::Point SnapManager::_transformPoint(std::pair<Geom::Point, int> const &p,
928                                         Transformation const transformation_type,
929                                         Geom::Point const &transformation,
930                                         Geom::Point const &origin,
931                                         Geom::Dim2 const dim,
932                                         bool const uniform) const
934     /* Work out the transformed version of this point */
935     Geom::Point transformed;
936     switch (transformation_type) {
937         case TRANSLATION:
938             transformed = p.first + transformation;
939             break;
940         case SCALE:
941             transformed = (p.first - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
942             break;
943         case STRETCH:
944         {
945             Geom::Scale s(1, 1);
946             if (uniform)
947                 s[Geom::X] = s[Geom::Y] = transformation[dim];
948             else {
949                 s[dim] = transformation[dim];
950                 s[1 - dim] = 1;
951             }
952             transformed = ((p.first - origin) * s) + origin;
953             break;
954         }
955         case SKEW:
956             // Apply the skew factor
957             transformed[dim] = (p.first)[dim] + transformation[0] * ((p.first)[1 - dim] - origin[1 - dim]);
958             // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
959             // Apply that scale factor here
960             transformed[1-dim] = (p.first - origin)[1 - dim] * transformation[1] + origin[1 - dim];
961             break;
962         default:
963             g_assert_not_reached();
964     }
966     return transformed;
969 void SnapManager::_displaySnapsource(Inkscape::SnapPreferences::PointType point_type, std::pair<Geom::Point, int> const &p) const {
971     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
972     if (prefs->getBool("/options/snapclosestonly/value")) {
973         bool p_is_a_node = point_type & Inkscape::SnapPreferences::SNAPPOINT_NODE;
974         bool p_is_a_bbox = point_type & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
975         if (snapprefs.getSnapEnabledGlobally() && ((p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
976             _desktop->snapindicator->set_new_snapsource(p);
977         } else {
978             _desktop->snapindicator->remove_snapsource();
979         }
980     }
983 /*
984   Local Variables:
985   mode:c++
986   c-file-style:"stroustrup"
987   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
988   indent-tabs-mode:nil
989   fill-column:99
990   End:
991 */
992 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :