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