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