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-2010 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 "selection.h"
34 #include "sp-guide.h"
35 #include "preferences.h"
36 #include "event-context.h"
37 using std::vector;
39 /**
40 * Construct a SnapManager for a SPNamedView.
41 *
42 * \param v `Owning' SPNamedView.
43 */
45 SnapManager::SnapManager(SPNamedView const *v) :
46 guide(this, 0),
47 object(this, 0),
48 snapprefs(),
49 _named_view(v)
50 {
51 }
53 /**
54 * \brief Return a list of snappers
55 *
56 * Inkscape snaps to objects, grids, and guides. For each of these snap targets a
57 * separate class is used, which has been derived from the base Snapper class. The
58 * getSnappers() method returns a list of pointers to instances of this class. This
59 * list contains exactly one instance of the guide snapper and of the object snapper
60 * class, but any number of grid snappers (because each grid has its own snapper
61 * instance)
62 *
63 * \return List of snappers that we use.
64 */
65 SnapManager::SnapperList
66 SnapManager::getSnappers() const
67 {
68 SnapManager::SnapperList s;
69 s.push_back(&guide);
70 s.push_back(&object);
72 SnapManager::SnapperList gs = getGridSnappers();
73 s.splice(s.begin(), gs);
75 return s;
76 }
78 /**
79 * \brief Return a list of gridsnappers
80 *
81 * Each grid has its own instance of the snapper class. This way snapping can
82 * be enabled per grid individually. A list will be returned containing the
83 * pointers to these instances, but only for grids that are being displayed
84 * and for which snapping is enabled.
85 *
86 * \return List of gridsnappers that we use.
87 */
88 SnapManager::SnapperList
89 SnapManager::getGridSnappers() const
90 {
91 SnapperList s;
93 if (_desktop && _desktop->gridsEnabled() && snapprefs.getSnapToGrids()) {
94 for ( GSList const *l = _named_view->grids; l != NULL; l = l->next) {
95 Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
96 s.push_back(grid->snapper);
97 }
98 }
100 return s;
101 }
103 /**
104 * \brief Return true if any snapping might occur, whether its to grids, guides or objects
105 *
106 * Each snapper instance handles its own snapping target, e.g. grids, guides or
107 * objects. This method iterates through all these snapper instances and returns
108 * true if any of the snappers might possible snap, considering only the relevant
109 * snapping preferences.
110 *
111 * \return true if one of the snappers will try to snap to something.
112 */
114 bool SnapManager::someSnapperMightSnap() const
115 {
116 if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
117 return false;
118 }
120 SnapperList const s = getSnappers();
121 SnapperList::const_iterator i = s.begin();
122 while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
123 i++;
124 }
126 return (i != s.end());
127 }
129 /**
130 * \return true if one of the grids might be snapped to.
131 */
133 bool SnapManager::gridSnapperMightSnap() const
134 {
135 if ( !snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally() ) {
136 return false;
137 }
139 SnapperList const s = getGridSnappers();
140 SnapperList::const_iterator i = s.begin();
141 while (i != s.end() && (*i)->ThisSnapperMightSnap() == false) {
142 i++;
143 }
145 return (i != s.end());
146 }
148 /**
149 * \brief Try to snap a point to grids, guides or objects.
150 *
151 * Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
152 * i.e. snap in any direction on the two dimensional canvas to the nearest
153 * snap target. freeSnapReturnByRef() is equal in snapping behavior to
154 * freeSnap(), but the former returns the snapped point trough the referenced
155 * parameter p. This parameter p initially contains the position of the snap
156 * source and will we overwritten by the target position if snapping has occurred.
157 * This makes snapping transparent to the calling code. If this is not desired
158 * because either the calling code must know whether snapping has occurred, or
159 * because the original position should not be touched, then freeSnap() should be
160 * called instead.
161 *
162 * PS:
163 * 1) SnapManager::setup() must have been called before calling this method,
164 * but only once for a set of points
165 * 2) Only to be used when a single source point is to be snapped; it assumes
166 * that source_num = 0, which is inefficient when snapping sets our source points
167 *
168 * \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
169 * \param source_type Detailed description of the source type, will be used by the snap indicator
170 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
171 */
173 void SnapManager::freeSnapReturnByRef(Geom::Point &p,
174 Inkscape::SnapSourceType const source_type,
175 Geom::OptRect const &bbox_to_snap) const
176 {
177 Inkscape::SnappedPoint const s = freeSnap(Inkscape::SnapCandidatePoint(p, source_type), bbox_to_snap);
178 s.getPoint(p);
179 }
182 /**
183 * \brief Try to snap a point to grids, guides or objects.
184 *
185 * Try to snap a point to grids, guides or objects, in two degrees-of-freedom,
186 * i.e. snap in any direction on the two dimensional canvas to the nearest
187 * snap target. freeSnap() is equal in snapping behavior to
188 * freeSnapReturnByRef(). Please read the comments of the latter for more details
189 *
190 * PS: SnapManager::setup() must have been called before calling this method,
191 * but only once for a set of points
192 *
193 * \param p Source point to be snapped
194 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
195 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
196 */
199 Inkscape::SnappedPoint SnapManager::freeSnap(Inkscape::SnapCandidatePoint const &p,
200 Geom::OptRect const &bbox_to_snap) const
201 {
202 if (!someSnapperMightSnap()) {
203 return Inkscape::SnappedPoint(p, Inkscape::SNAPTARGET_UNDEFINED, NR_HUGE, 0, false, false, false);
204 }
206 SnappedConstraints sc;
207 SnapperList const snappers = getSnappers();
209 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
210 (*i)->freeSnap(sc, p, bbox_to_snap, &_items_to_ignore, _unselected_nodes);
211 }
213 return findBestSnap(p, sc, false);
214 }
216 void SnapManager::preSnap(Inkscape::SnapCandidatePoint const &p)
217 {
218 // setup() must have been called before calling this method!
220 if (_snapindicator) {
221 _snapindicator = false; // prevent other methods from drawing a snap indicator; we want to control this here
222 Inkscape::SnappedPoint s = freeSnap(p);
223 if (s.getSnapped()) {
224 _desktop->snapindicator->set_new_snaptarget(s, true);
225 } else {
226 _desktop->snapindicator->remove_snaptarget(true);
227 }
228 _snapindicator = true; // restore the original value
229 }
230 }
232 /**
233 * \brief Snap to the closest multiple of a grid pitch
234 *
235 * When pasting, we would like to snap to the grid. Problem is that we don't know which
236 * nodes were aligned to the grid at the time of copying, so we don't know which nodes
237 * to snap. If we'd snap an unaligned node to the grid, previously aligned nodes would
238 * become unaligned. That's undesirable. Instead we will make sure that the offset
239 * between the source and its pasted copy is a multiple of the grid pitch. If the source
240 * was aligned, then the copy will therefore also be aligned.
241 *
242 * PS: Whether we really find a multiple also depends on the snapping range! Most users
243 * will have "always snap" enabled though, in which case a multiple will always be found.
244 * PS2: When multiple grids are present then the result will become ambiguous. There is no
245 * way to control to which grid this method will snap.
246 *
247 * \param t Vector that represents the offset of the pasted copy with respect to the original
248 * \return Offset vector after snapping to the closest multiple of a grid pitch
249 */
251 Geom::Point SnapManager::multipleOfGridPitch(Geom::Point const &t, Geom::Point const &origin)
252 {
253 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally())
254 return t;
256 if (_desktop && _desktop->gridsEnabled()) {
257 bool success = false;
258 Geom::Point nearest_multiple;
259 Geom::Coord nearest_distance = NR_HUGE;
260 Inkscape::SnappedPoint bestSnappedPoint(t);
262 // It will snap to the grid for which we find the closest snap. This might be a different
263 // grid than to which the objects were initially aligned. I don't see an easy way to fix
264 // this, so when using multiple grids one can get unexpected results
266 // Cannot use getGridSnappers() because we need both the grids AND their snappers
267 // Therefore we iterate through all grids manually
268 for (GSList const *l = _named_view->grids; l != NULL; l = l->next) {
269 Inkscape::CanvasGrid *grid = (Inkscape::CanvasGrid*) l->data;
270 const Inkscape::Snapper* snapper = grid->snapper;
271 if (snapper && snapper->ThisSnapperMightSnap()) {
272 // To find the nearest multiple of the grid pitch for a given translation t, we
273 // will use the grid snapper. Simply snapping the value t to the grid will do, but
274 // only if the origin of the grid is at (0,0). If it's not then compensate for this
275 // in the translation t
276 Geom::Point const t_offset = t + grid->origin;
277 SnappedConstraints sc;
278 // Only the first three parameters are being used for grid snappers
279 snapper->freeSnap(sc, Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH),Geom::OptRect(), NULL, NULL);
280 // Find the best snap for this grid, including intersections of the grid-lines
281 bool old_val = _snapindicator;
282 _snapindicator = false;
283 Inkscape::SnappedPoint s = findBestSnap(Inkscape::SnapCandidatePoint(t_offset, Inkscape::SNAPSOURCE_GRID_PITCH), sc, false, false, true);
284 _snapindicator = old_val;
285 if (s.getSnapped() && (s.getSnapDistance() < nearest_distance)) {
286 // use getSnapDistance() instead of getWeightedDistance() here because the pointer's position
287 // doesn't tell us anything about which node to snap
288 success = true;
289 nearest_multiple = s.getPoint() - to_2geom(grid->origin);
290 nearest_distance = s.getSnapDistance();
291 bestSnappedPoint = s;
292 }
293 }
294 }
296 if (success) {
297 bestSnappedPoint.setPoint(origin + nearest_multiple);
298 _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
299 return nearest_multiple;
300 }
301 }
303 return t;
304 }
306 /**
307 * \brief Try to snap a point along a constraint line to grids, guides or objects.
308 *
309 * Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
310 * i.e. snap in a specific direction on the two dimensional canvas to the nearest
311 * snap target.
312 *
313 * constrainedSnapReturnByRef() is equal in snapping behavior to
314 * constrainedSnap(), but the former returns the snapped point trough the referenced
315 * parameter p. This parameter p initially contains the position of the snap
316 * source and will we overwritten by the target position if snapping has occurred.
317 * This makes snapping transparent to the calling code. If this is not desired
318 * because either the calling code must know whether snapping has occurred, or
319 * because the original position should not be touched, then constrainedSnap() should
320 * be called instead.
321 *
322 * PS:
323 * 1) SnapManager::setup() must have been called before calling this method,
324 * but only once for a set of points
325 * 2) Only to be used when a single source point is to be snapped; it assumes
326 * that source_num = 0, which is inefficient when snapping sets our source points
328 *
329 * \param p Current position of the snap source; will be overwritten by the position of the snap target if snapping has occurred
330 * \param source_type Detailed description of the source type, will be used by the snap indicator
331 * \param constraint The direction or line along which snapping must occur
332 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
333 */
335 void SnapManager::constrainedSnapReturnByRef(Geom::Point &p,
336 Inkscape::SnapSourceType const source_type,
337 Inkscape::Snapper::SnapConstraint const &constraint,
338 Geom::OptRect const &bbox_to_snap) const
339 {
340 Inkscape::SnappedPoint const s = constrainedSnap(Inkscape::SnapCandidatePoint(p, source_type, 0), constraint, bbox_to_snap);
341 s.getPoint(p);
342 }
344 /**
345 * \brief Try to snap a point along a constraint line to grids, guides or objects.
346 *
347 * Try to snap a point to grids, guides or objects, in only one degree-of-freedom,
348 * i.e. snap in a specific direction on the two dimensional canvas to the nearest
349 * snap target. constrainedSnap is equal in snapping behavior to
350 * constrainedSnapReturnByRef(). Please read the comments of the latter for more details.
351 *
352 * PS: SnapManager::setup() must have been called before calling this method,
353 * but only once for a set of points
354 *
355 * \param p Source point to be snapped
356 * \param constraint The direction or line along which snapping must occur
357 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
358 */
360 Inkscape::SnappedPoint SnapManager::constrainedSnap(Inkscape::SnapCandidatePoint const &p,
361 Inkscape::Snapper::SnapConstraint const &constraint,
362 Geom::OptRect const &bbox_to_snap) const
363 {
364 // First project the mouse pointer onto the constraint
365 Geom::Point pp = constraint.projection(p.getPoint());
367 Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(pp, p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
369 if (!someSnapperMightSnap()) {
370 // Always return point on constraint
371 return no_snap;
372 }
374 SnappedConstraints sc;
375 SnapperList const snappers = getSnappers();
376 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
377 (*i)->constrainedSnap(sc, p, bbox_to_snap, constraint, &_items_to_ignore);
378 }
380 Inkscape::SnappedPoint result = findBestSnap(p, sc, true);
382 if (result.getSnapped()) {
383 // only change the snap indicator if we really snapped to something
384 if (_snapindicator) {
385 _desktop->snapindicator->set_new_snaptarget(result);
386 }
387 return result;
388 }
389 return no_snap;
390 }
392 /* See the documentation for constrainedSnap() directly above for more details.
393 * The difference is that multipleConstrainedSnaps() will take a list of constraints instead of a single one,
394 * and will try to snap the SnapCandidatePoint to all of the provided constraints and see which one fits best
395 * \param p Source point to be snapped
396 * \param constraints List of directions or lines along which snapping must occur
397 * \param bbox_to_snap Bounding box hulling the set of points, all from the same selection and having the same transformation
398 */
401 Inkscape::SnappedPoint SnapManager::multipleConstrainedSnaps(Inkscape::SnapCandidatePoint const &p,
402 std::vector<Inkscape::Snapper::SnapConstraint> const &constraints,
403 Geom::OptRect const &bbox_to_snap) const
404 {
406 Inkscape::SnappedPoint no_snap = Inkscape::SnappedPoint(p.getPoint(), p.getSourceType(), p.getSourceNum(), Inkscape::SNAPTARGET_CONSTRAINT, NR_HUGE, 0, false, true, false);
407 if (constraints.size() == 0) {
408 return no_snap;
409 }
411 SnappedConstraints sc;
412 SnapperList const snappers = getSnappers();
413 std::vector<Geom::Point> projections;
414 bool snapping_is_futile = !someSnapperMightSnap();
416 // Iterate over the constraints
417 for (std::vector<Inkscape::Snapper::SnapConstraint>::const_iterator c = constraints.begin(); c != constraints.end(); c++) {
418 // Project the mouse pointer onto the constraint; In case we don't snap then we will
419 // return the projection onto the constraint, such that the constraint is always enforced
420 Geom::Point pp = (*c).projection(p.getPoint());
421 projections.push_back(pp);
422 // Try to snap to the constraint
423 if (!snapping_is_futile) {
424 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
425 (*i)->constrainedSnap(sc, p, bbox_to_snap, *c, &_items_to_ignore);
426 }
427 }
428 }
430 Inkscape::SnappedPoint result = findBestSnap(p, sc, true);
432 if (result.getSnapped()) {
433 // only change the snap indicator if we really snapped to something
434 if (_snapindicator) {
435 _desktop->snapindicator->set_new_snaptarget(result);
436 }
437 return result;
438 }
440 // So we didn't snap, but we still need to return a point on one of the constraints
441 // Find out which of the constraints yielded the closest projection of point p
442 no_snap.setPoint(projections.front());
443 for (std::vector<Geom::Point>::iterator pp = projections.begin(); pp != projections.end(); pp++) {
444 if (pp != projections.begin()) {
445 if (Geom::L2(*pp - p.getPoint()) < Geom::L2(no_snap.getPoint() - p.getPoint())) {
446 no_snap.setPoint(*pp);
447 }
448 }
449 }
451 return no_snap;
452 }
454 /**
455 * \brief Try to snap a point of a guide to another guide or to a node
456 *
457 * Try to snap a point of a guide to another guide or to a node in two degrees-
458 * of-freedom, i.e. snap in any direction on the two dimensional canvas to the
459 * nearest snap target. This method is used when dragging or rotating a guide
460 *
461 * PS: SnapManager::setup() must have been called before calling this method,
462 *
463 * \param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred
464 * \param guide_normal Vector normal to the guide line
465 */
466 void SnapManager::guideFreeSnap(Geom::Point &p, Geom::Point const &guide_normal, SPGuideDragType drag_type) const
467 {
468 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
469 return;
470 }
472 if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
473 return;
474 }
476 Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN);
477 if (drag_type == SP_DRAG_ROTATE) {
478 candidate = Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_GUIDE);
479 }
481 // Snap to nodes
482 SnappedConstraints sc;
483 if (object.ThisSnapperMightSnap()) {
484 object.guideFreeSnap(sc, p, guide_normal);
485 }
487 // Snap to guides & grid lines
488 SnapperList snappers = getGridSnappers();
489 snappers.push_back(&guide);
490 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
491 (*i)->freeSnap(sc, candidate, Geom::OptRect(), NULL, NULL);
492 }
494 Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false, false);
496 s.getPoint(p);
497 }
499 /**
500 * \brief Try to snap a point on a guide to the intersection with another guide or a path
501 *
502 * Try to snap a point on a guide to the intersection of that guide with another
503 * guide or with a path. The snapped point will lie somewhere on the guide-line,
504 * making this is a constrained snap, i.e. in only one degree-of-freedom.
505 * This method is used when dragging the origin of the guide along the guide itself.
506 *
507 * PS: SnapManager::setup() must have been called before calling this method,
508 *
509 * \param p Current position of the point on the guide that is to be snapped; will be overwritten by the position of the snap target if snapping has occurred
510 * \param guide_normal Vector normal to the guide line
511 */
513 void SnapManager::guideConstrainedSnap(Geom::Point &p, SPGuide const &guideline) const
514 {
515 if (!snapprefs.getSnapEnabledGlobally() || snapprefs.getSnapPostponedGlobally()) {
516 return;
517 }
519 if (!(object.ThisSnapperMightSnap() || snapprefs.getSnapToGuides())) {
520 return;
521 }
523 Inkscape::SnapCandidatePoint candidate(p, Inkscape::SNAPSOURCE_GUIDE_ORIGIN, Inkscape::SNAPTARGET_UNDEFINED);
525 // Snap to nodes or paths
526 SnappedConstraints sc;
527 Inkscape::Snapper::SnapConstraint cl(guideline.point_on_line, Geom::rot90(guideline.normal_to_line));
528 if (object.ThisSnapperMightSnap()) {
529 object.constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL);
530 }
532 // Snap to guides & grid lines
533 SnapperList snappers = getGridSnappers();
534 snappers.push_back(&guide);
535 for (SnapperList::const_iterator i = snappers.begin(); i != snappers.end(); i++) {
536 (*i)->constrainedSnap(sc, candidate, Geom::OptRect(), cl, NULL);
537 }
539 Inkscape::SnappedPoint const s = findBestSnap(candidate, sc, false);
540 s.getPoint(p);
541 }
543 /**
544 * \brief Method for snapping sets of points while they are being transformed
545 *
546 * Method for snapping sets of points while they are being transformed, when using
547 * for example the selector tool. This method is for internal use only, and should
548 * not have to be called directly. Use freeSnapTransalation(), constrainedSnapScale(),
549 * etc. instead.
550 *
551 * This is what is being done in this method: transform each point, find out whether
552 * a free snap or constrained snap is more appropriate, do the snapping, calculate
553 * some metrics to quantify the snap "distance", and see if it's better than the
554 * previous snap. Finally, the best ("nearest") snap from all these points is returned.
555 *
556 * \param points Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
557 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
558 * \param constrained true if the snap is constrained, e.g. for stretching or for purely horizontal translation.
559 * \param constraint The direction or line along which snapping must occur, if 'constrained' is true; otherwise undefined.
560 * \param transformation_type Type of transformation to apply to points before trying to snap them.
561 * \param transformation Description of the transformation; details depend on the type.
562 * \param origin Origin of the transformation, if applicable.
563 * \param dim Dimension to which the transformation applies, if applicable.
564 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
565 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
566 */
568 Inkscape::SnappedPoint SnapManager::_snapTransformed(
569 std::vector<Inkscape::SnapCandidatePoint> const &points,
570 Geom::Point const &pointer,
571 bool constrained,
572 Inkscape::Snapper::SnapConstraint const &constraint,
573 Transformation transformation_type,
574 Geom::Point const &transformation,
575 Geom::Point const &origin,
576 Geom::Dim2 dim,
577 bool uniform) const
578 {
579 /* We have a list of points, which we are proposing to transform in some way. We need to see
580 ** if any of these points, when transformed, snap to anything. If they do, we return the
581 ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
582 */
584 /* Quick check to see if we have any snappers that are enabled
585 ** Also used to globally disable all snapping
586 */
587 if (someSnapperMightSnap() == false || points.size() == 0) {
588 return Inkscape::SnappedPoint(pointer);
589 }
591 std::vector<Inkscape::SnapCandidatePoint> transformed_points;
592 Geom::Rect bbox;
594 long source_num = 0;
595 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
597 /* Work out the transformed version of this point */
598 Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
600 // add the current transformed point to the box hulling all transformed points
601 if (i == points.begin()) {
602 bbox = Geom::Rect(transformed, transformed);
603 } else {
604 bbox.expandTo(transformed);
605 }
607 transformed_points.push_back(Inkscape::SnapCandidatePoint(transformed, (*i).getSourceType(), source_num));
608 source_num++;
609 }
611 /* The current best transformation */
612 Geom::Point best_transformation = transformation;
614 /* The current best metric for the best transformation; lower is better, NR_HUGE
615 ** means that we haven't snapped anything.
616 */
617 Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
618 Inkscape::SnappedPoint best_snapped_point;
619 g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
620 g_assert(best_snapped_point.getAtIntersection() == false);
622 // Warnings for the devs
623 if (constrained && transformation_type == SCALE && !uniform) {
624 g_warning("Non-uniform constrained scaling is not supported!");
625 }
627 if (!constrained && transformation_type == ROTATE) {
628 // We do not yet allow for simultaneous rotation and scaling
629 g_warning("Unconstrained rotation is not supported!");
630 }
632 std::vector<Inkscape::SnapCandidatePoint>::iterator j = transformed_points.begin();
634 // std::cout << std::endl;
635 bool first_free_snap = true;
636 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
638 /* Snap it */
639 Inkscape::SnappedPoint snapped_point;
640 Inkscape::Snapper::SnapConstraint dedicated_constraint = constraint;
641 Geom::Point const b = ((*i).getPoint() - origin); // vector to original point (not the transformed point! required for rotations!)
643 if (constrained) {
644 if (((transformation_type == SCALE || transformation_type == STRETCH) && uniform)) {
645 // When uniformly scaling, each point will have its own unique constraint line,
646 // running from the scaling origin to the original untransformed point. We will
647 // calculate that line here
648 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b);
649 } else if (transformation_type == ROTATE) {
650 Geom::Coord r = Geom::L2(b); // the radius of the circular constraint
651 if (r < 1e-9) { // points too close to the rotation center will not move. Don't try to snap these
652 // as they will always yield a perfect snap result if they're already snapped beforehand (e.g.
653 // when the transformation center has been snapped to a grid intersection in the selector tool)
654 continue; // skip this SnapCandidate and continue with the next one
655 // PS1: Apparently we don't have to do this for skewing, but why?
656 // PS2: We cannot easily filter these points upstream, e.g. in the grab() method (seltrans.cpp)
657 // because the rotation center will change when pressing shift, and grab() won't be recalled.
658 // Filtering could be done in handleRequest() (again in seltrans.cpp), by iterating through
659 // the snap candidates. But hey, we're iterating here anyway.
660 }
661 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b, r);
662 } else if (transformation_type == STRETCH) { // when non-uniform stretching {
663 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), component_vectors[dim]);
664 } else if (transformation_type == TRANSLATE) {
665 // When doing a constrained translation, all points will move in the same direction, i.e.
666 // either horizontally or vertically. The lines along which they move are therefore all
667 // parallel, but might not be colinear. Therefore we will have to specify the point through
668 // which the constraint-line runs here, for each point individually. (we could also have done this
669 // earlier on, e.g. in seltrans.cpp but we're being lazy there and don't want to add an iteration loop)
670 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), constraint.getDirection());
671 } // else: leave the original constraint, e.g. for skewing
672 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
673 } else {
674 bool const c1 = fabs(b[Geom::X]) < 1e-6;
675 bool const c2 = fabs(b[Geom::Y]) < 1e-6;
676 if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
677 // When scaling, a point aligned either horizontally or vertically with the origin can only
678 // move in that specific direction; therefore it should only snap in that direction, otherwise
679 // we will get snapped points with an invalid transformation
680 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, component_vectors[c1]);
681 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
682 } else {
683 // If we have a collection of SnapCandidatePoints, with mixed constrained snapping and free snapping
684 // requirements, then freeSnap might never see the SnapCandidatePoint with source_num == 0. The freeSnap()
685 // method in the object snapper depends on this, because only for source-num == 0 the target nodes will
686 // be collected. Therefore we enforce that the first SnapCandidatePoint that is to be freeSnapped always
687 // has source_num == 0;
688 // TODO: This is a bit ugly so fix this; do we need sourcenum for anything else? if we don't then get rid
689 // of it and explicitely communicate to the object snapper that this is a first point
690 if (first_free_snap) {
691 (*j).setSourceNum(0);
692 first_free_snap = false;
693 }
694 snapped_point = freeSnap(*j, bbox);
695 }
696 }
697 // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
698 snapped_point.setPointerDistance(Geom::L2(pointer - (*i).getPoint()));
700 Geom::Point result;
702 if (snapped_point.getSnapped()) {
703 /* We snapped. Find the transformation that describes where the snapped point has
704 ** ended up, and also the metric for this transformation.
705 */
706 Geom::Point const a = snapped_point.getPoint() - origin; // vector to snapped point
707 //Geom::Point const b = (*i - origin); // vector to original point
709 switch (transformation_type) {
710 case TRANSLATE:
711 result = snapped_point.getPoint() - (*i).getPoint();
712 /* Consider the case in which a box is almost aligned with a grid in both
713 * horizontal and vertical directions. The distance to the intersection of
714 * the grid lines will always be larger then the distance to a single grid
715 * line. If we prefer snapping to an intersection instead of to a single
716 * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
717 * snapped distance will be used as a metric. Please note that the snapped
718 * distance is defined as the distance to the nearest line of the intersection,
719 * and not to the intersection itself!
720 */
721 // Only for translations, the relevant metric will be the real snapped distance,
722 // so we don't have to do anything special here
723 break;
724 case SCALE:
725 {
726 result = Geom::Point(NR_HUGE, NR_HUGE);
727 // If this point *i is horizontally or vertically aligned with
728 // the origin of the scaling, then it will scale purely in X or Y
729 // We can therefore only calculate the scaling in this direction
730 // and the scaling factor for the other direction should remain
731 // untouched (unless scaling is uniform of course)
732 for (int index = 0; index < 2; index++) {
733 if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
734 if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
735 result[index] = a[index] / b[index]; // then calculate it!
736 }
737 // we might leave result[1-index] = NR_HUGE
738 // if scaling didn't occur in the other direction
739 }
740 }
741 if (uniform) {
742 if (fabs(result[0]) < fabs(result[1])) {
743 result[1] = result[0];
744 } else {
745 result[0] = result[1];
746 }
747 }
748 // Compare the resulting scaling with the desired scaling
749 Geom::Point scale_metric = Geom::abs(result - transformation); // One or both of its components might be NR_HUGE
750 snapped_point.setSnapDistance(std::min(scale_metric[0], scale_metric[1]));
751 snapped_point.setSecondSnapDistance(std::max(scale_metric[0], scale_metric[1]));
752 break;
753 }
754 case STRETCH:
755 result = Geom::Point(NR_HUGE, NR_HUGE);
756 if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
757 result[dim] = a[dim] / b[dim];
758 result[1-dim] = uniform ? result[dim] : 1;
759 } else { // STRETCHING might occur for this point, but only when the stretching is uniform
760 if (uniform && fabs(b[1-dim]) > 1e-6) {
761 result[1-dim] = a[1-dim] / b[1-dim];
762 result[dim] = result[1-dim];
763 }
764 }
765 // Store the metric for this transformation as a virtual distance
766 snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
767 snapped_point.setSecondSnapDistance(NR_HUGE);
768 break;
769 case SKEW:
770 result[0] = (snapped_point.getPoint()[dim] - ((*i).getPoint())[dim]) / b[1 - dim]; // skew factor
771 result[1] = transformation[1]; // scale factor
772 // Store the metric for this transformation as a virtual distance
773 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
774 snapped_point.setSecondSnapDistance(NR_HUGE);
775 break;
776 case ROTATE:
777 // a is vector to snapped point; b is vector to original point; now lets calculate angle between a and b
778 result[0] = atan2(Geom::dot(Geom::rot90(b), a), Geom::dot(b, a));
779 result[1] = result[1]; // how else should we store an angle in a point ;-)
780 // Store the metric for this transformation as a virtual distance (we're storing an angle)
781 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
782 snapped_point.setSecondSnapDistance(NR_HUGE);
783 break;
784 default:
785 g_assert_not_reached();
786 }
788 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
789 best_transformation = result;
790 best_snapped_point = snapped_point;
791 }
792 }
794 j++;
795 }
797 Geom::Coord best_metric;
798 if (transformation_type == SCALE) {
799 // When scaling, don't ever exit with one of scaling components set to NR_HUGE
800 for (int index = 0; index < 2; index++) {
801 if (best_transformation[index] == NR_HUGE) {
802 if (uniform && best_transformation[1-index] < NR_HUGE) {
803 best_transformation[index] = best_transformation[1-index];
804 } else {
805 best_transformation[index] = transformation[index];
806 }
807 }
808 }
809 }
811 best_metric = best_snapped_point.getSnapDistance();
812 best_snapped_point.setTransformation(best_transformation);
813 // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
814 // These rounding errors might be caused by NRRects, see bug #1584301
815 best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
816 return best_snapped_point;
817 }
820 /**
821 * \brief Apply a translation to a set of points and try to snap freely in 2 degrees-of-freedom
822 *
823 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
824 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
825 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred
826 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
827 */
829 Inkscape::SnappedPoint SnapManager::freeSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
830 Geom::Point const &pointer,
831 Geom::Point const &tr) const
832 {
833 if (p.size() == 1) {
834 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
835 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
836 }
840 return _snapTransformed(p, pointer, false, Geom::Point(0,0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
841 }
843 /**
844 * \brief Apply a translation to a set of points and try to snap along a constraint
845 *
846 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
847 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
848 * \param constraint The direction or line along which snapping must occur.
849 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred.
850 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
851 */
853 Inkscape::SnappedPoint SnapManager::constrainedSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
854 Geom::Point const &pointer,
855 Inkscape::Snapper::SnapConstraint const &constraint,
856 Geom::Point const &tr) const
857 {
858 if (p.size() == 1) {
859 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
860 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
861 }
863 return _snapTransformed(p, pointer, true, constraint, TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
864 }
867 /**
868 * \brief Apply a scaling to a set of points and try to snap freely in 2 degrees-of-freedom
869 *
870 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
871 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
872 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
873 * \param o Origin of the scaling
874 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
875 */
877 Inkscape::SnappedPoint SnapManager::freeSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
878 Geom::Point const &pointer,
879 Geom::Scale const &s,
880 Geom::Point const &o) const
881 {
882 if (p.size() == 1) {
883 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
884 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
885 }
887 return _snapTransformed(p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
888 }
891 /**
892 * \brief Apply a scaling to a set of points and snap such that the aspect ratio of the selection is preserved
893 *
894 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
895 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
896 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
897 * \param o Origin of the scaling
898 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
899 */
901 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
902 Geom::Point const &pointer,
903 Geom::Scale const &s,
904 Geom::Point const &o) const
905 {
906 // When constrained scaling, only uniform scaling is supported.
907 if (p.size() == 1) {
908 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
909 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
910 }
912 return _snapTransformed(p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
913 }
915 /**
916 * \brief Apply a stretch to a set of points and snap such that the direction of the stretch is preserved
917 *
918 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
919 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
920 * \param s Proposed stretch; the final stretch can only be calculated after snapping has occurred
921 * \param o Origin of the stretching
922 * \param d Dimension in which to apply proposed stretch.
923 * \param u true if the stretch should be uniform (i.e. to be applied equally in both dimensions)
924 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
925 */
927 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(std::vector<Inkscape::SnapCandidatePoint> const &p,
928 Geom::Point const &pointer,
929 Geom::Coord const &s,
930 Geom::Point const &o,
931 Geom::Dim2 d,
932 bool u) const
933 {
934 if (p.size() == 1) {
935 Geom::Point pt = _transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u);
936 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
937 }
939 return _snapTransformed(p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
940 }
942 /**
943 * \brief Apply a skew to a set of points and snap such that the direction of the skew is preserved
944 *
945 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
946 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
947 * \param constraint The direction or line along which snapping must occur.
948 * \param s Proposed skew; the final skew can only be calculated after snapping has occurred
949 * \param o Origin of the proposed skew
950 * \param d Dimension in which to apply proposed skew.
951 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
952 */
954 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(std::vector<Inkscape::SnapCandidatePoint> const &p,
955 Geom::Point const &pointer,
956 Inkscape::Snapper::SnapConstraint const &constraint,
957 Geom::Point const &s,
958 Geom::Point const &o,
959 Geom::Dim2 d) const
960 {
961 // "s" contains skew factor in s[0], and scale factor in s[1]
963 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
964 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
965 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
966 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
967 // of bounding boxes is not allowed here.
968 if (p.size() > 0) {
969 g_assert(!(p.at(0).getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY));
970 }
972 if (p.size() == 1) {
973 Geom::Point pt = _transformPoint(p.at(0), SKEW, s, o, d, false);
974 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
975 }
977 return _snapTransformed(p, pointer, true, constraint, SKEW, s, o, d, false);
978 }
980 /**
981 * \brief Apply a rotation to a set of points and snap, without scaling
982 *
983 * \param p Collection of points to snap (snap sources), at their untransformed position, all points undergoing the same transformation. Paired with an identifier of the type of the snap source.
984 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
985 * \param angle Proposed rotation (in radians); the final rotation can only be calculated after snapping has occurred
986 * \param o Origin of the rotation
987 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
988 */
990 Inkscape::SnappedPoint SnapManager::constrainedSnapRotate(std::vector<Inkscape::SnapCandidatePoint> const &p,
991 Geom::Point const &pointer,
992 Geom::Coord const &angle,
993 Geom::Point const &o) const
994 {
995 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
996 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
997 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
998 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
999 // of bounding boxes is not allowed here.
1001 if (p.size() == 1) {
1002 Geom::Point pt = _transformPoint(p.at(0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1003 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1004 }
1006 return _snapTransformed(p, pointer, true, Geom::Point(0,0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1008 }
1010 /**
1011 * \brief Given a set of possible snap targets, find the best target (which is not necessarily
1012 * also the nearest target), and show the snap indicator if requested
1013 *
1014 * \param p Source point to be snapped
1015 * \param sc A structure holding all snap targets that have been found so far
1016 * \param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation.
1017 * \param noCurves If true, then do consider snapping to intersections of curves, but not to the curves themselves
1018 * \param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example when pasting to the grid)
1019 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
1020 */
1022 Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p,
1023 SnappedConstraints const &sc,
1024 bool constrained,
1025 bool noCurves,
1026 bool allowOffScreen) const
1027 {
1030 /*
1031 std::cout << "Type and number of snapped constraints: " << std::endl;
1032 std::cout << " Points : " << sc.points.size() << std::endl;
1033 std::cout << " Lines : " << sc.lines.size() << std::endl;
1034 std::cout << " Grid lines : " << sc.grid_lines.size()<< std::endl;
1035 std::cout << " Guide lines : " << sc.guide_lines.size()<< std::endl;
1036 std::cout << " Curves : " << sc.curves.size()<< std::endl;
1037 */
1039 // Store all snappoints
1040 std::list<Inkscape::SnappedPoint> sp_list;
1042 // search for the closest snapped point
1043 Inkscape::SnappedPoint closestPoint;
1044 if (getClosestSP(sc.points, closestPoint)) {
1045 sp_list.push_back(closestPoint);
1046 }
1048 // search for the closest snapped curve
1049 if (!noCurves) {
1050 Inkscape::SnappedCurve closestCurve;
1051 if (getClosestCurve(sc.curves, closestCurve)) {
1052 sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
1053 }
1054 }
1056 if (snapprefs.getSnapIntersectionCS()) {
1057 // search for the closest snapped intersection of curves
1058 Inkscape::SnappedPoint closestCurvesIntersection;
1059 if (getClosestIntersectionCS(sc.curves, p.getPoint(), closestCurvesIntersection, _desktop->dt2doc())) {
1060 closestCurvesIntersection.setSource(p.getSourceType());
1061 sp_list.push_back(closestCurvesIntersection);
1062 }
1063 }
1065 // search for the closest snapped grid line
1066 Inkscape::SnappedLine closestGridLine;
1067 if (getClosestSL(sc.grid_lines, closestGridLine)) {
1068 sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
1069 }
1071 // search for the closest snapped guide line
1072 Inkscape::SnappedLine closestGuideLine;
1073 if (getClosestSL(sc.guide_lines, closestGuideLine)) {
1074 sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
1075 }
1077 // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
1078 // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
1080 // When doing a constrained snap however, we're already at an intersection of the constrained line and
1081 // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
1082 // no need to look for additional intersections
1083 if (!constrained) {
1084 // search for the closest snapped intersection of grid lines
1085 Inkscape::SnappedPoint closestGridPoint;
1086 if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
1087 closestGridPoint.setSource(p.getSourceType());
1088 closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
1089 sp_list.push_back(closestGridPoint);
1090 }
1092 // search for the closest snapped intersection of guide lines
1093 Inkscape::SnappedPoint closestGuidePoint;
1094 if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
1095 closestGuidePoint.setSource(p.getSourceType());
1096 closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
1097 sp_list.push_back(closestGuidePoint);
1098 }
1100 // search for the closest snapped intersection of grid with guide lines
1101 if (snapprefs.getSnapIntersectionGG()) {
1102 Inkscape::SnappedPoint closestGridGuidePoint;
1103 if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
1104 closestGridGuidePoint.setSource(p.getSourceType());
1105 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
1106 sp_list.push_back(closestGridGuidePoint);
1107 }
1108 }
1109 }
1111 // now let's see which snapped point gets a thumbs up
1112 Inkscape::SnappedPoint bestSnappedPoint(p.getPoint());
1113 // std::cout << "Finding the best snap..." << std::endl;
1114 for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
1115 // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << (*i).getTarget();
1116 bool onScreen = _desktop->get_display_area().contains((*i).getPoint());
1117 if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen
1118 if ((*i).getSnapDistance() <= (*i).getTolerance()) { // Only snap to points within snapping range
1119 // if it's the first point, or if it is closer than the best snapped point so far
1120 if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
1121 // then prefer this point over the previous one
1122 bestSnappedPoint = *i;
1123 }
1124 }
1125 }
1126 // std::cout << std::endl;
1127 }
1129 // Update the snap indicator, if requested
1130 if (_snapindicator) {
1131 if (bestSnappedPoint.getSnapped()) {
1132 _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
1133 } else {
1134 _desktop->snapindicator->remove_snaptarget();
1135 }
1136 }
1138 // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
1139 return bestSnappedPoint;
1140 }
1142 /// Convenience shortcut when there is only one item to ignore
1143 void SnapManager::setup(SPDesktop const *desktop,
1144 bool snapindicator,
1145 SPItem const *item_to_ignore,
1146 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1147 SPGuide *guide_to_ignore)
1148 {
1149 g_assert(desktop != NULL);
1150 _items_to_ignore.clear();
1151 _items_to_ignore.push_back(item_to_ignore);
1152 _desktop = desktop;
1153 _snapindicator = snapindicator;
1154 _unselected_nodes = unselected_nodes;
1155 _guide_to_ignore = guide_to_ignore;
1156 _rotation_center_source_item = NULL;
1157 }
1159 /**
1160 * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1161 * to ignore and toggling the snap indicator
1162 *
1163 * There are two overloaded setup() methods, of which the other one only allows for a single item to be ignored
1164 * whereas this one will take a list of items to ignore
1165 *
1166 * \param desktop Reference to the desktop to which this snap manager is attached
1167 * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1168 * \param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping"
1169 * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1170 * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1171 * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1172 * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1173 */
1175 void SnapManager::setup(SPDesktop const *desktop,
1176 bool snapindicator,
1177 std::vector<SPItem const *> &items_to_ignore,
1178 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1179 SPGuide *guide_to_ignore)
1180 {
1181 g_assert(desktop != NULL);
1182 _items_to_ignore = items_to_ignore;
1183 _desktop = desktop;
1184 _snapindicator = snapindicator;
1185 _unselected_nodes = unselected_nodes;
1186 _guide_to_ignore = guide_to_ignore;
1187 _rotation_center_source_item = NULL;
1188 }
1190 /// Setup, taking the list of items to ignore from the desktop's selection.
1191 void SnapManager::setupIgnoreSelection(SPDesktop const *desktop,
1192 bool snapindicator,
1193 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1194 SPGuide *guide_to_ignore)
1195 {
1196 _desktop = desktop;
1197 _snapindicator = snapindicator;
1198 _unselected_nodes = unselected_nodes;
1199 _guide_to_ignore = guide_to_ignore;
1200 _rotation_center_source_item = NULL;
1201 _items_to_ignore.clear();
1203 Inkscape::Selection *sel = _desktop->selection;
1204 GSList const *items = sel->itemList();
1205 for (GSList *i = const_cast<GSList*>(items); i; i = i->next) {
1206 _items_to_ignore.push_back(static_cast<SPItem const *>(i->data));
1207 }
1208 }
1210 SPDocument *SnapManager::getDocument() const
1211 {
1212 return _named_view->document;
1213 }
1215 /**
1216 * \brief Takes an untransformed point, applies the given transformation, and returns the transformed point. Eliminates lots of duplicated code
1217 *
1218 * \param p The untransformed position of the point, paired with an identifier of the type of the snap source.
1219 * \param transformation_type Type of transformation to apply.
1220 * \param transformation Mathematical description of the transformation; details depend on the type.
1221 * \param origin Origin of the transformation, if applicable.
1222 * \param dim Dimension to which the transformation applies, if applicable.
1223 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
1224 * \return The position of the point after transformation
1225 */
1227 Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p,
1228 Transformation const transformation_type,
1229 Geom::Point const &transformation,
1230 Geom::Point const &origin,
1231 Geom::Dim2 const dim,
1232 bool const uniform) const
1233 {
1234 /* Work out the transformed version of this point */
1235 Geom::Point transformed;
1236 switch (transformation_type) {
1237 case TRANSLATE:
1238 transformed = p.getPoint() + transformation;
1239 break;
1240 case SCALE:
1241 transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
1242 break;
1243 case STRETCH:
1244 {
1245 Geom::Scale s(1, 1);
1246 if (uniform)
1247 s[Geom::X] = s[Geom::Y] = transformation[dim];
1248 else {
1249 s[dim] = transformation[dim];
1250 s[1 - dim] = 1;
1251 }
1252 transformed = ((p.getPoint() - origin) * s) + origin;
1253 break;
1254 }
1255 case SKEW:
1256 // Apply the skew factor
1257 transformed[dim] = (p.getPoint())[dim] + transformation[0] * ((p.getPoint())[1 - dim] - origin[1 - dim]);
1258 // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
1259 // Apply that scale factor here
1260 transformed[1-dim] = (p.getPoint() - origin)[1 - dim] * transformation[1] + origin[1 - dim];
1261 break;
1262 case ROTATE:
1263 // for rotations: transformation[0] stores the angle in radians
1264 transformed = (p.getPoint() - origin) * Geom::Rotate(transformation[0]) + origin;
1265 break;
1266 default:
1267 g_assert_not_reached();
1268 }
1270 return transformed;
1271 }
1273 /**
1274 * \brief Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol
1275 *
1276 * \param point_type Category of points to which the source point belongs: node, guide or bounding box
1277 * \param p The transformed position of the source point, paired with an identifier of the type of the snap source.
1278 */
1280 void SnapManager::_displaySnapsource(Inkscape::SnapCandidatePoint const &p) const {
1282 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1283 if (prefs->getBool("/options/snapclosestonly/value")) {
1284 bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
1285 bool p_is_a_bbox = p.getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
1286 bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
1288 if (snapprefs.getSnapEnabledGlobally() && (p_is_other || (p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
1289 _desktop->snapindicator->set_new_snapsource(p);
1290 } else {
1291 _desktop->snapindicator->remove_snapsource();
1292 }
1293 }
1294 }
1296 /*
1297 Local Variables:
1298 mode:c++
1299 c-file-style:"stroustrup"
1300 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1301 indent-tabs-mode:nil
1302 fill-column:99
1303 End:
1304 */
1305 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :