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 *
657 * \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.
658 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
659 * \param constrained true if the snap is constrained, e.g. for stretching or for purely horizontal translation.
660 * \param constraint The direction or line along which snapping must occur, if 'constrained' is true; otherwise undefined.
661 * \param transformation_type Type of transformation to apply to points before trying to snap them.
662 * \param transformation Description of the transformation; details depend on the type.
663 * \param origin Origin of the transformation, if applicable.
664 * \param dim Dimension to which the transformation applies, if applicable.
665 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
666 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
667 */
669 Inkscape::SnappedPoint SnapManager::_snapTransformed(
670 std::vector<Inkscape::SnapCandidatePoint> const &points,
671 Geom::Point const &pointer,
672 bool constrained,
673 Inkscape::Snapper::SnapConstraint const &constraint,
674 Transformation transformation_type,
675 Geom::Point const &transformation,
676 Geom::Point const &origin,
677 Geom::Dim2 dim,
678 bool uniform) const
679 {
680 /* We have a list of points, which we are proposing to transform in some way. We need to see
681 ** if any of these points, when transformed, snap to anything. If they do, we return the
682 ** appropriate transformation with `true'; otherwise we return the original scale with `false'.
683 */
685 /* Quick check to see if we have any snappers that are enabled
686 ** Also used to globally disable all snapping
687 */
688 if (someSnapperMightSnap() == false || points.size() == 0) {
689 return Inkscape::SnappedPoint(pointer);
690 }
692 std::vector<Inkscape::SnapCandidatePoint> transformed_points;
693 Geom::Rect bbox;
695 long source_num = 0;
696 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
698 /* Work out the transformed version of this point */
699 Geom::Point transformed = _transformPoint(*i, transformation_type, transformation, origin, dim, uniform);
701 // add the current transformed point to the box hulling all transformed points
702 if (i == points.begin()) {
703 bbox = Geom::Rect(transformed, transformed);
704 } else {
705 bbox.expandTo(transformed);
706 }
708 transformed_points.push_back(Inkscape::SnapCandidatePoint(transformed, (*i).getSourceType(), source_num, Inkscape::SNAPTARGET_UNDEFINED, Geom::OptRect()));
709 source_num++;
710 }
712 /* The current best transformation */
713 Geom::Point best_transformation = transformation;
715 /* The current best metric for the best transformation; lower is better, NR_HUGE
716 ** means that we haven't snapped anything.
717 */
718 Geom::Point best_scale_metric(NR_HUGE, NR_HUGE);
719 Inkscape::SnappedPoint best_snapped_point;
720 g_assert(best_snapped_point.getAlwaysSnap() == false); // Check initialization of snapped point
721 g_assert(best_snapped_point.getAtIntersection() == false);
723 // Warnings for the devs
724 if (constrained && transformation_type == SCALE && !uniform) {
725 g_warning("Non-uniform constrained scaling is not supported!");
726 }
728 if (!constrained && transformation_type == ROTATE) {
729 // We do not yet allow for simultaneous rotation and scaling
730 g_warning("Unconstrained rotation is not supported!");
731 }
733 std::vector<Inkscape::SnapCandidatePoint>::iterator j = transformed_points.begin();
735 // std::cout << std::endl;
736 bool first_free_snap = true;
737 for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = points.begin(); i != points.end(); i++) {
739 /* Snap it */
740 Inkscape::SnappedPoint snapped_point;
741 Inkscape::Snapper::SnapConstraint dedicated_constraint = constraint;
742 Geom::Point const b = ((*i).getPoint() - origin); // vector to original point (not the transformed point! required for rotations!)
744 if (constrained) {
745 if (((transformation_type == SCALE || transformation_type == STRETCH) && uniform)) {
746 // When uniformly scaling, each point will have its own unique constraint line,
747 // running from the scaling origin to the original untransformed point. We will
748 // calculate that line here
749 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b);
750 } else if (transformation_type == ROTATE) {
751 Geom::Coord r = Geom::L2(b); // the radius of the circular constraint
752 if (r < 1e-9) { // points too close to the rotation center will not move. Don't try to snap these
753 // as they will always yield a perfect snap result if they're already snapped beforehand (e.g.
754 // when the transformation center has been snapped to a grid intersection in the selector tool)
755 continue; // skip this SnapCandidate and continue with the next one
756 // PS1: Apparently we don't have to do this for skewing, but why?
757 // PS2: We cannot easily filter these points upstream, e.g. in the grab() method (seltrans.cpp)
758 // because the rotation center will change when pressing shift, and grab() won't be recalled.
759 // Filtering could be done in handleRequest() (again in seltrans.cpp), by iterating through
760 // the snap candidates. But hey, we're iterating here anyway.
761 }
762 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, b, r);
763 } else if (transformation_type == STRETCH) { // when non-uniform stretching {
764 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), component_vectors[dim]);
765 } else if (transformation_type == TRANSLATE) {
766 // When doing a constrained translation, all points will move in the same direction, i.e.
767 // either horizontally or vertically. The lines along which they move are therefore all
768 // parallel, but might not be colinear. Therefore we will have to specify the point through
769 // which the constraint-line runs here, for each point individually. (we could also have done this
770 // earlier on, e.g. in seltrans.cpp but we're being lazy there and don't want to add an iteration loop)
771 dedicated_constraint = Inkscape::Snapper::SnapConstraint((*i).getPoint(), constraint.getDirection());
772 } // else: leave the original constraint, e.g. for skewing
773 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
774 } else {
775 bool const c1 = fabs(b[Geom::X]) < 1e-6;
776 bool const c2 = fabs(b[Geom::Y]) < 1e-6;
777 if (transformation_type == SCALE && (c1 || c2) && !(c1 && c2)) {
778 // When scaling, a point aligned either horizontally or vertically with the origin can only
779 // move in that specific direction; therefore it should only snap in that direction, otherwise
780 // we will get snapped points with an invalid transformation
781 dedicated_constraint = Inkscape::Snapper::SnapConstraint(origin, component_vectors[c1]);
782 snapped_point = constrainedSnap(*j, dedicated_constraint, bbox);
783 } else {
784 // If we have a collection of SnapCandidatePoints, with mixed constrained snapping and free snapping
785 // requirements, then freeSnap might never see the SnapCandidatePoint with source_num == 0. The freeSnap()
786 // method in the object snapper depends on this, because only for source-num == 0 the target nodes will
787 // be collected. Therefore we enforce that the first SnapCandidatePoint that is to be freeSnapped always
788 // has source_num == 0;
789 // TODO: This is a bit ugly so fix this; do we need sourcenum for anything else? if we don't then get rid
790 // of it and explicitely communicate to the object snapper that this is a first point
791 if (first_free_snap) {
792 (*j).setSourceNum(0);
793 first_free_snap = false;
794 }
795 snapped_point = freeSnap(*j, bbox);
796 }
797 }
798 // std::cout << "dist = " << snapped_point.getSnapDistance() << std::endl;
799 snapped_point.setPointerDistance(Geom::L2(pointer - (*i).getPoint()));
801 Geom::Point result;
803 if (snapped_point.getSnapped()) {
804 /* We snapped. Find the transformation that describes where the snapped point has
805 ** ended up, and also the metric for this transformation.
806 */
807 Geom::Point const a = snapped_point.getPoint() - origin; // vector to snapped point
808 //Geom::Point const b = (*i - origin); // vector to original point
810 switch (transformation_type) {
811 case TRANSLATE:
812 result = snapped_point.getPoint() - (*i).getPoint();
813 /* Consider the case in which a box is almost aligned with a grid in both
814 * horizontal and vertical directions. The distance to the intersection of
815 * the grid lines will always be larger then the distance to a single grid
816 * line. If we prefer snapping to an intersection instead of to a single
817 * grid line, then we cannot use "metric = Geom::L2(result)". Therefore the
818 * snapped distance will be used as a metric. Please note that the snapped
819 * distance is defined as the distance to the nearest line of the intersection,
820 * and not to the intersection itself!
821 */
822 // Only for translations, the relevant metric will be the real snapped distance,
823 // so we don't have to do anything special here
824 break;
825 case SCALE:
826 {
827 result = Geom::Point(NR_HUGE, NR_HUGE);
828 // If this point *i is horizontally or vertically aligned with
829 // the origin of the scaling, then it will scale purely in X or Y
830 // We can therefore only calculate the scaling in this direction
831 // and the scaling factor for the other direction should remain
832 // untouched (unless scaling is uniform of course)
833 for (int index = 0; index < 2; index++) {
834 if (fabs(b[index]) > 1e-6) { // if SCALING CAN occur in this direction
835 if (fabs(fabs(a[index]/b[index]) - fabs(transformation[index])) > 1e-12) { // if SNAPPING DID occur in this direction
836 result[index] = a[index] / b[index]; // then calculate it!
837 }
838 // we might leave result[1-index] = NR_HUGE
839 // if scaling didn't occur in the other direction
840 }
841 }
842 if (uniform) {
843 if (fabs(result[0]) < fabs(result[1])) {
844 result[1] = result[0];
845 } else {
846 result[0] = result[1];
847 }
848 }
849 // Compare the resulting scaling with the desired scaling
850 Geom::Point scale_metric = Geom::abs(result - transformation); // One or both of its components might be NR_HUGE
851 snapped_point.setSnapDistance(std::min(scale_metric[0], scale_metric[1]));
852 snapped_point.setSecondSnapDistance(std::max(scale_metric[0], scale_metric[1]));
853 break;
854 }
855 case STRETCH:
856 result = Geom::Point(NR_HUGE, NR_HUGE);
857 if (fabs(b[dim]) > 1e-6) { // if STRETCHING will occur for this point
858 result[dim] = a[dim] / b[dim];
859 result[1-dim] = uniform ? result[dim] : 1;
860 } else { // STRETCHING might occur for this point, but only when the stretching is uniform
861 if (uniform && fabs(b[1-dim]) > 1e-6) {
862 result[1-dim] = a[1-dim] / b[1-dim];
863 result[dim] = result[1-dim];
864 }
865 }
866 // Store the metric for this transformation as a virtual distance
867 snapped_point.setSnapDistance(std::abs(result[dim] - transformation[dim]));
868 snapped_point.setSecondSnapDistance(NR_HUGE);
869 break;
870 case SKEW:
871 result[0] = (snapped_point.getPoint()[dim] - ((*i).getPoint())[dim]) / b[1 - dim]; // skew factor
872 result[1] = transformation[1]; // scale factor
873 // Store the metric for this transformation as a virtual distance
874 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
875 snapped_point.setSecondSnapDistance(NR_HUGE);
876 break;
877 case ROTATE:
878 // a is vector to snapped point; b is vector to original point; now lets calculate angle between a and b
879 result[0] = atan2(Geom::dot(Geom::rot90(b), a), Geom::dot(b, a));
880 result[1] = result[1]; // how else should we store an angle in a point ;-)
881 // Store the metric for this transformation as a virtual distance (we're storing an angle)
882 snapped_point.setSnapDistance(std::abs(result[0] - transformation[0]));
883 snapped_point.setSecondSnapDistance(NR_HUGE);
884 break;
885 default:
886 g_assert_not_reached();
887 }
889 if (best_snapped_point.isOtherSnapBetter(snapped_point, true)) {
890 best_transformation = result;
891 best_snapped_point = snapped_point;
892 }
893 }
895 j++;
896 }
898 Geom::Coord best_metric;
899 if (transformation_type == SCALE) {
900 // When scaling, don't ever exit with one of scaling components set to NR_HUGE
901 for (int index = 0; index < 2; index++) {
902 if (best_transformation[index] == NR_HUGE) {
903 if (uniform && best_transformation[1-index] < NR_HUGE) {
904 best_transformation[index] = best_transformation[1-index];
905 } else {
906 best_transformation[index] = transformation[index];
907 }
908 }
909 }
910 }
912 best_metric = best_snapped_point.getSnapDistance();
913 best_snapped_point.setTransformation(best_transformation);
914 // Using " < 1e6" instead of " < NR_HUGE" for catching some rounding errors
915 // These rounding errors might be caused by NRRects, see bug #1584301
916 best_snapped_point.setSnapDistance(best_metric < 1e6 ? best_metric : NR_HUGE);
917 return best_snapped_point;
918 }
921 /**
922 * \brief Apply a translation to a set of points and try to snap freely in 2 degrees-of-freedom
923 *
924 * \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.
925 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
926 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred
927 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
928 */
930 Inkscape::SnappedPoint SnapManager::freeSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
931 Geom::Point const &pointer,
932 Geom::Point const &tr) const
933 {
934 if (p.size() == 1) {
935 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
936 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
937 }
941 return _snapTransformed(p, pointer, false, Geom::Point(0,0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
942 }
944 /**
945 * \brief Apply a translation to a set of points and try to snap along a constraint
946 *
947 * \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.
948 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
949 * \param constraint The direction or line along which snapping must occur.
950 * \param tr Proposed translation; the final translation can only be calculated after snapping has occurred.
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::constrainedSnapTranslate(std::vector<Inkscape::SnapCandidatePoint> const &p,
955 Geom::Point const &pointer,
956 Inkscape::Snapper::SnapConstraint const &constraint,
957 Geom::Point const &tr) const
958 {
959 if (p.size() == 1) {
960 Geom::Point pt = _transformPoint(p.at(0), TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
961 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
962 }
964 return _snapTransformed(p, pointer, true, constraint, TRANSLATE, tr, Geom::Point(0,0), Geom::X, false);
965 }
968 /**
969 * \brief Apply a scaling to a set of points and try to snap freely in 2 degrees-of-freedom
970 *
971 * \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.
972 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
973 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
974 * \param o Origin of the scaling
975 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
976 */
978 Inkscape::SnappedPoint SnapManager::freeSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
979 Geom::Point const &pointer,
980 Geom::Scale const &s,
981 Geom::Point const &o) const
982 {
983 if (p.size() == 1) {
984 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
985 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
986 }
988 return _snapTransformed(p, pointer, false, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, false);
989 }
992 /**
993 * \brief Apply a scaling to a set of points and snap such that the aspect ratio of the selection is preserved
994 *
995 * \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.
996 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
997 * \param s Proposed scaling; the final scaling can only be calculated after snapping has occurred
998 * \param o Origin of the scaling
999 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1000 */
1002 Inkscape::SnappedPoint SnapManager::constrainedSnapScale(std::vector<Inkscape::SnapCandidatePoint> const &p,
1003 Geom::Point const &pointer,
1004 Geom::Scale const &s,
1005 Geom::Point const &o) const
1006 {
1007 // When constrained scaling, only uniform scaling is supported.
1008 if (p.size() == 1) {
1009 Geom::Point pt = _transformPoint(p.at(0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
1010 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1011 }
1013 return _snapTransformed(p, pointer, true, Geom::Point(0,0), SCALE, Geom::Point(s[Geom::X], s[Geom::Y]), o, Geom::X, true);
1014 }
1016 /**
1017 * \brief Apply a stretch to a set of points and snap such that the direction of the stretch is preserved
1018 *
1019 * \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.
1020 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1021 * \param s Proposed stretch; the final stretch can only be calculated after snapping has occurred
1022 * \param o Origin of the stretching
1023 * \param d Dimension in which to apply proposed stretch.
1024 * \param u true if the stretch should be uniform (i.e. to be applied equally in both dimensions)
1025 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1026 */
1028 Inkscape::SnappedPoint SnapManager::constrainedSnapStretch(std::vector<Inkscape::SnapCandidatePoint> const &p,
1029 Geom::Point const &pointer,
1030 Geom::Coord const &s,
1031 Geom::Point const &o,
1032 Geom::Dim2 d,
1033 bool u) const
1034 {
1035 if (p.size() == 1) {
1036 Geom::Point pt = _transformPoint(p.at(0), STRETCH, Geom::Point(s, s), o, d, u);
1037 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1038 }
1040 return _snapTransformed(p, pointer, true, Geom::Point(0,0), STRETCH, Geom::Point(s, s), o, d, u);
1041 }
1043 /**
1044 * \brief Apply a skew to a set of points and snap such that the direction of the skew is preserved
1045 *
1046 * \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.
1047 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1048 * \param constraint The direction or line along which snapping must occur.
1049 * \param s Proposed skew; the final skew can only be calculated after snapping has occurred
1050 * \param o Origin of the proposed skew
1051 * \param d Dimension in which to apply proposed skew.
1052 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1053 */
1055 Inkscape::SnappedPoint SnapManager::constrainedSnapSkew(std::vector<Inkscape::SnapCandidatePoint> const &p,
1056 Geom::Point const &pointer,
1057 Inkscape::Snapper::SnapConstraint const &constraint,
1058 Geom::Point const &s,
1059 Geom::Point const &o,
1060 Geom::Dim2 d) const
1061 {
1062 // "s" contains skew factor in s[0], and scale factor in s[1]
1064 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
1065 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
1066 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
1067 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
1068 // of bounding boxes is not allowed here.
1069 if (p.size() > 0) {
1070 g_assert(!(p.at(0).getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY));
1071 }
1073 if (p.size() == 1) {
1074 Geom::Point pt = _transformPoint(p.at(0), SKEW, s, o, d, false);
1075 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1076 }
1078 return _snapTransformed(p, pointer, true, constraint, SKEW, s, o, d, false);
1079 }
1081 /**
1082 * \brief Apply a rotation to a set of points and snap, without scaling
1083 *
1084 * \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.
1085 * \param pointer Location of the mouse pointer at the time dragging started (i.e. when the selection was still untransformed).
1086 * \param angle Proposed rotation (in radians); the final rotation can only be calculated after snapping has occurred
1087 * \param o Origin of the rotation
1088 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics.
1089 */
1091 Inkscape::SnappedPoint SnapManager::constrainedSnapRotate(std::vector<Inkscape::SnapCandidatePoint> const &p,
1092 Geom::Point const &pointer,
1093 Geom::Coord const &angle,
1094 Geom::Point const &o) const
1095 {
1096 // Snapping the nodes of the bounding box of a selection that is being transformed, will only work if
1097 // the transformation of the bounding box is equal to the transformation of the individual nodes. This is
1098 // NOT the case for example when rotating or skewing. The bounding box itself cannot possibly rotate or skew,
1099 // so it's corners have a different transformation. The snappers cannot handle this, therefore snapping
1100 // of bounding boxes is not allowed here.
1102 if (p.size() == 1) {
1103 Geom::Point pt = _transformPoint(p.at(0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1104 _displaySnapsource(Inkscape::SnapCandidatePoint(pt, p.at(0).getSourceType()));
1105 }
1107 return _snapTransformed(p, pointer, true, Geom::Point(0,0), ROTATE, Geom::Point(angle, angle), o, Geom::X, false);
1109 }
1111 /**
1112 * \brief Given a set of possible snap targets, find the best target (which is not necessarily
1113 * also the nearest target), and show the snap indicator if requested
1114 *
1115 * \param p Source point to be snapped
1116 * \param sc A structure holding all snap targets that have been found so far
1117 * \param constrained True if the snap is constrained, e.g. for stretching or for purely horizontal translation.
1118 * \param noCurves If true, then do consider snapping to intersections of curves, but not to the curves themselves
1119 * \param allowOffScreen If true, then snapping to points which are off the screen is allowed (needed for example when pasting to the grid)
1120 * \return An instance of the SnappedPoint class, which holds data on the snap source, snap target, and various metrics
1121 */
1123 Inkscape::SnappedPoint SnapManager::findBestSnap(Inkscape::SnapCandidatePoint const &p,
1124 SnappedConstraints const &sc,
1125 bool constrained,
1126 bool noCurves,
1127 bool allowOffScreen) const
1128 {
1129 g_assert(_desktop != NULL);
1131 /*
1132 std::cout << "Type and number of snapped constraints: " << std::endl;
1133 std::cout << " Points : " << sc.points.size() << std::endl;
1134 std::cout << " Lines : " << sc.lines.size() << std::endl;
1135 std::cout << " Grid lines : " << sc.grid_lines.size()<< std::endl;
1136 std::cout << " Guide lines : " << sc.guide_lines.size()<< std::endl;
1137 std::cout << " Curves : " << sc.curves.size()<< std::endl;
1138 */
1140 // Store all snappoints
1141 std::list<Inkscape::SnappedPoint> sp_list;
1143 // search for the closest snapped point
1144 Inkscape::SnappedPoint closestPoint;
1145 if (getClosestSP(sc.points, closestPoint)) {
1146 sp_list.push_back(closestPoint);
1147 }
1149 // search for the closest snapped curve
1150 if (!noCurves) {
1151 Inkscape::SnappedCurve closestCurve;
1152 if (getClosestCurve(sc.curves, closestCurve)) {
1153 sp_list.push_back(Inkscape::SnappedPoint(closestCurve));
1154 }
1155 }
1157 if (snapprefs.getSnapIntersectionCS()) {
1158 // search for the closest snapped intersection of curves
1159 Inkscape::SnappedPoint closestCurvesIntersection;
1160 if (getClosestIntersectionCS(sc.curves, p.getPoint(), closestCurvesIntersection, _desktop->dt2doc())) {
1161 closestCurvesIntersection.setSource(p.getSourceType());
1162 sp_list.push_back(closestCurvesIntersection);
1163 }
1164 }
1166 // search for the closest snapped grid line
1167 Inkscape::SnappedLine closestGridLine;
1168 if (getClosestSL(sc.grid_lines, closestGridLine)) {
1169 sp_list.push_back(Inkscape::SnappedPoint(closestGridLine));
1170 }
1172 // search for the closest snapped guide line
1173 Inkscape::SnappedLine closestGuideLine;
1174 if (getClosestSL(sc.guide_lines, closestGuideLine)) {
1175 sp_list.push_back(Inkscape::SnappedPoint(closestGuideLine));
1176 }
1178 // When freely snapping to a grid/guide/path, only one degree of freedom is eliminated
1179 // Therefore we will try get fully constrained by finding an intersection with another grid/guide/path
1181 // When doing a constrained snap however, we're already at an intersection of the constrained line and
1182 // the grid/guide/path we're snapping to. This snappoint is therefore fully constrained, so there's
1183 // no need to look for additional intersections
1184 if (!constrained) {
1185 // search for the closest snapped intersection of grid lines
1186 Inkscape::SnappedPoint closestGridPoint;
1187 if (getClosestIntersectionSL(sc.grid_lines, closestGridPoint)) {
1188 closestGridPoint.setSource(p.getSourceType());
1189 closestGridPoint.setTarget(Inkscape::SNAPTARGET_GRID_INTERSECTION);
1190 sp_list.push_back(closestGridPoint);
1191 }
1193 // search for the closest snapped intersection of guide lines
1194 Inkscape::SnappedPoint closestGuidePoint;
1195 if (getClosestIntersectionSL(sc.guide_lines, closestGuidePoint)) {
1196 closestGuidePoint.setSource(p.getSourceType());
1197 closestGuidePoint.setTarget(Inkscape::SNAPTARGET_GUIDE_INTERSECTION);
1198 sp_list.push_back(closestGuidePoint);
1199 }
1201 // search for the closest snapped intersection of grid with guide lines
1202 if (snapprefs.getSnapIntersectionGG()) {
1203 Inkscape::SnappedPoint closestGridGuidePoint;
1204 if (getClosestIntersectionSL(sc.grid_lines, sc.guide_lines, closestGridGuidePoint)) {
1205 closestGridGuidePoint.setSource(p.getSourceType());
1206 closestGridGuidePoint.setTarget(Inkscape::SNAPTARGET_GRID_GUIDE_INTERSECTION);
1207 sp_list.push_back(closestGridGuidePoint);
1208 }
1209 }
1210 }
1212 // now let's see which snapped point gets a thumbs up
1213 Inkscape::SnappedPoint bestSnappedPoint(p.getPoint());
1214 // std::cout << "Finding the best snap..." << std::endl;
1215 for (std::list<Inkscape::SnappedPoint>::const_iterator i = sp_list.begin(); i != sp_list.end(); i++) {
1216 // std::cout << "sp = " << (*i).getPoint() << " | source = " << (*i).getSource() << " | target = " << (*i).getTarget();
1217 bool onScreen = _desktop->get_display_area().contains((*i).getPoint());
1218 if (onScreen || allowOffScreen) { // Only snap to points which are not off the screen
1219 if ((*i).getSnapDistance() <= (*i).getTolerance()) { // Only snap to points within snapping range
1220 // if it's the first point, or if it is closer than the best snapped point so far
1221 if (i == sp_list.begin() || bestSnappedPoint.isOtherSnapBetter(*i, false)) {
1222 // then prefer this point over the previous one
1223 bestSnappedPoint = *i;
1224 }
1225 }
1226 }
1227 // std::cout << std::endl;
1228 }
1230 // Update the snap indicator, if requested
1231 if (_snapindicator) {
1232 if (bestSnappedPoint.getSnapped()) {
1233 _desktop->snapindicator->set_new_snaptarget(bestSnappedPoint);
1234 } else {
1235 _desktop->snapindicator->remove_snaptarget();
1236 }
1237 }
1239 // std::cout << "findBestSnap = " << bestSnappedPoint.getPoint() << " | dist = " << bestSnappedPoint.getSnapDistance() << std::endl;
1240 return bestSnappedPoint;
1241 }
1243 /// Convenience shortcut when there is only one item to ignore
1244 void SnapManager::setup(SPDesktop const *desktop,
1245 bool snapindicator,
1246 SPItem const *item_to_ignore,
1247 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1248 SPGuide *guide_to_ignore)
1249 {
1250 g_assert(desktop != NULL);
1251 if (_desktop != NULL) {
1252 g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1253 }
1254 _items_to_ignore.clear();
1255 _items_to_ignore.push_back(item_to_ignore);
1256 _desktop = desktop;
1257 _snapindicator = snapindicator;
1258 _unselected_nodes = unselected_nodes;
1259 _guide_to_ignore = guide_to_ignore;
1260 _rotation_center_source_items = NULL;
1261 }
1263 /**
1264 * \brief Prepare the snap manager for the actual snapping, which includes building a list of snap targets
1265 * to ignore and toggling the snap indicator
1266 *
1267 * There are two overloaded setup() methods, of which the other one only allows for a single item to be ignored
1268 * whereas this one will take a list of items to ignore
1269 *
1270 * \param desktop Reference to the desktop to which this snap manager is attached
1271 * \param snapindicator If true then a snap indicator will be displayed automatically (when enabled in the preferences)
1272 * \param items_to_ignore These items will not be snapped to, e.g. the items that are currently being dragged. This avoids "self-snapping"
1273 * \param unselected_nodes Stationary nodes of the path that is currently being edited in the node tool and
1274 * that can be snapped too. Nodes not in this list will not be snapped to, to avoid "self-snapping". Of each
1275 * unselected node both the position (Geom::Point) and the type (Inkscape::SnapTargetType) will be stored
1276 * \param guide_to_ignore Guide that is currently being dragged and should not be snapped to
1277 */
1279 void SnapManager::setup(SPDesktop const *desktop,
1280 bool snapindicator,
1281 std::vector<SPItem const *> &items_to_ignore,
1282 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1283 SPGuide *guide_to_ignore)
1284 {
1285 g_assert(desktop != NULL);
1286 if (_desktop != NULL) {
1287 g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1288 }
1289 _items_to_ignore = items_to_ignore;
1290 _desktop = desktop;
1291 _snapindicator = snapindicator;
1292 _unselected_nodes = unselected_nodes;
1293 _guide_to_ignore = guide_to_ignore;
1294 _rotation_center_source_items = NULL;
1295 }
1297 /// Setup, taking the list of items to ignore from the desktop's selection.
1298 void SnapManager::setupIgnoreSelection(SPDesktop const *desktop,
1299 bool snapindicator,
1300 std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
1301 SPGuide *guide_to_ignore)
1302 {
1303 g_assert(desktop != NULL);
1304 if (_desktop != NULL) {
1305 // Someone has been naughty here! This is dangerous
1306 g_warning("The snapmanager has been set up before, but unSetup() hasn't been called afterwards. It possibly held invalid pointers");
1307 }
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 _items_to_ignore.clear();
1315 Inkscape::Selection *sel = _desktop->selection;
1316 GSList const *items = sel->itemList();
1317 for (GSList *i = const_cast<GSList*>(items); i; i = i->next) {
1318 _items_to_ignore.push_back(static_cast<SPItem const *>(i->data));
1319 }
1320 }
1322 SPDocument *SnapManager::getDocument() const
1323 {
1324 return _named_view->document;
1325 }
1327 /**
1328 * \brief Takes an untransformed point, applies the given transformation, and returns the transformed point. Eliminates lots of duplicated code
1329 *
1330 * \param p The untransformed position of the point, paired with an identifier of the type of the snap source.
1331 * \param transformation_type Type of transformation to apply.
1332 * \param transformation Mathematical description of the transformation; details depend on the type.
1333 * \param origin Origin of the transformation, if applicable.
1334 * \param dim Dimension to which the transformation applies, if applicable.
1335 * \param uniform true if the transformation should be uniform; only applicable for stretching and scaling.
1336 * \return The position of the point after transformation
1337 */
1339 Geom::Point SnapManager::_transformPoint(Inkscape::SnapCandidatePoint const &p,
1340 Transformation const transformation_type,
1341 Geom::Point const &transformation,
1342 Geom::Point const &origin,
1343 Geom::Dim2 const dim,
1344 bool const uniform) const
1345 {
1346 /* Work out the transformed version of this point */
1347 Geom::Point transformed;
1348 switch (transformation_type) {
1349 case TRANSLATE:
1350 transformed = p.getPoint() + transformation;
1351 break;
1352 case SCALE:
1353 transformed = (p.getPoint() - origin) * Geom::Scale(transformation[Geom::X], transformation[Geom::Y]) + origin;
1354 break;
1355 case STRETCH:
1356 {
1357 Geom::Scale s(1, 1);
1358 if (uniform)
1359 s[Geom::X] = s[Geom::Y] = transformation[dim];
1360 else {
1361 s[dim] = transformation[dim];
1362 s[1 - dim] = 1;
1363 }
1364 transformed = ((p.getPoint() - origin) * s) + origin;
1365 break;
1366 }
1367 case SKEW:
1368 // Apply the skew factor
1369 transformed[dim] = (p.getPoint())[dim] + transformation[0] * ((p.getPoint())[1 - dim] - origin[1 - dim]);
1370 // While skewing, mirroring and scaling (by integer multiples) in the opposite direction is also allowed.
1371 // Apply that scale factor here
1372 transformed[1-dim] = (p.getPoint() - origin)[1 - dim] * transformation[1] + origin[1 - dim];
1373 break;
1374 case ROTATE:
1375 // for rotations: transformation[0] stores the angle in radians
1376 transformed = (p.getPoint() - origin) * Geom::Rotate(transformation[0]) + origin;
1377 break;
1378 default:
1379 g_assert_not_reached();
1380 }
1382 return transformed;
1383 }
1385 /**
1386 * \brief Mark the location of the snap source (not the snap target!) on the canvas by drawing a symbol
1387 *
1388 * \param point_type Category of points to which the source point belongs: node, guide or bounding box
1389 * \param p The transformed position of the source point, paired with an identifier of the type of the snap source.
1390 */
1392 void SnapManager::_displaySnapsource(Inkscape::SnapCandidatePoint const &p) const {
1394 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1395 if (prefs->getBool("/options/snapclosestonly/value")) {
1396 bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
1397 bool p_is_a_bbox = p.getSourceType() & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
1398 bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
1400 g_assert(_desktop != NULL);
1401 if (snapprefs.getSnapEnabledGlobally() && (p_is_other || (p_is_a_node && snapprefs.getSnapModeNode()) || (p_is_a_bbox && snapprefs.getSnapModeBBox()))) {
1402 _desktop->snapindicator->set_new_snapsource(p);
1403 } else {
1404 _desktop->snapindicator->remove_snapsource();
1405 }
1406 }
1407 }
1409 /*
1410 Local Variables:
1411 mode:c++
1412 c-file-style:"stroustrup"
1413 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1414 indent-tabs-mode:nil
1415 fill-column:99
1416 End:
1417 */
1418 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :