Code

2Geom migration: use 2geom::projection instead of libnr's project_on_linesegment
[inkscape.git] / src / object-snapper.cpp
1 /**
2  *  \file object-snapper.cpp
3  *  \brief Snapping things to objects.
4  *
5  * Authors:
6  *   Carl Hetherington <inkscape@carlh.net>
7  *   Diederik van Lierop <mail@diedenrezi.nl>
8  *
9  * Copyright (C) 2005 - 2008 Authors
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include "svg/svg.h"
15 #include "libnr/nr-rect-ops.h"
16 #include "libnr/nr-point-fns.h"
17 #include <2geom/path-intersection.h>
18 #include <2geom/point.h>
19 #include <2geom/rect.h>
20 #include <2geom/line.h>
21 #include "document.h"
22 #include "sp-namedview.h"
23 #include "sp-image.h"
24 #include "sp-item-group.h"
25 #include "sp-item.h"
26 #include "sp-use.h"
27 #include "display/curve.h"
28 #include "inkscape.h"
29 #include "preferences.h"
30 #include "sp-text.h"
31 #include "sp-flowtext.h"
32 #include "text-editing.h"
33 #include "sp-clippath.h"
34 #include "sp-mask.h"
35 #include "helper/geom-curves.h"
36 #include "desktop.h"
38 Inkscape::SnapCandidate::SnapCandidate(SPItem* item, bool clip_or_mask, Geom::Matrix additional_affine)
39     : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine)
40 {
41 }
43 Inkscape::SnapCandidate::~SnapCandidate()
44 {
45 }
47 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
48     : Snapper(sm, d)
49 {
50     _candidates = new std::vector<SnapCandidate>;
51     _points_to_snap_to = new std::vector<std::pair<Geom::Point, int> >;
52     _paths_to_snap_to = new std::vector<std::pair<Geom::PathVector*, SnapTargetType> >;
53 }
55 Inkscape::ObjectSnapper::~ObjectSnapper()
56 {
57     _candidates->clear();
58     delete _candidates;
60     _points_to_snap_to->clear();
61     delete _points_to_snap_to;
63     _clear_paths();
64     delete _paths_to_snap_to;
65 }
67 /**
68  *  \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
69  */
70 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
71 {
72         SPDesktop const *dt = _snapmanager->getDesktop();
73         double const zoom =  dt ? dt->current_zoom() : 1;
74         return _snapmanager->snapprefs.getObjectTolerance() / zoom;
75 }
77 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
78 {
79     return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
80 }
82 /**
83  *  Find all items within snapping range.
84  *  \param parent Pointer to the document's root, or to a clipped path or mask object
85  *  \param it List of items to ignore
86  *  \param first_point If true then this point is the first one from a whole bunch of points
87  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
88  *  \param DimensionToSnap Snap in X, Y, or both directions.
89  */
91 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
92                                               std::vector<SPItem const *> const *it,
93                                               bool const &first_point,
94                                               Geom::Rect const &bbox_to_snap,
95                                               DimensionToSnap const snap_dim,
96                                               bool const clip_or_mask,
97                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
98 {
99     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
100     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
102     if (!(c1 || c2)) {
103         return;
104     }
106     if (first_point) {
107         _candidates->clear();
108     }
110     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
111     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
113     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
114         g_assert(_snapmanager->getDesktop() != NULL);
115         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
116             // Snapping to items in a locked layer is allowed
117             // Don't snap to hidden objects, unless they're a clipped path or a mask
118             /* See if this item is on the ignore list */
119             std::vector<SPItem const *>::const_iterator i;
120             if (it != NULL) {
121                 i = it->begin();
122                 while (i != it->end() && *i != o) {
123                     i++;
124                 }
125             }
127             if (it == NULL || i == it->end()) {
128                 SPItem *item = SP_ITEM(o);
129                 if (item) {
130                     SPObject *obj = NULL;
131                     if (!clip_or_mask) { // cannot clip or mask more than once
132                         // The current item is not a clipping path or a mask, but might
133                         // still be the subject of clipping or masking itself ; if so, then
134                         // we should also consider that path or mask for snapping to
135                         obj = SP_OBJECT(item->clip_ref->getObject());
136                         if (obj) {
137                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
138                         }
139                         obj = SP_OBJECT(item->mask_ref->getObject());
140                         if (obj) {
141                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
142                         }
143                     }
144                 }
146                 if (SP_IS_GROUP(o)) {
147                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
148                 } else {
149                     Geom::OptRect bbox_of_item = Geom::Rect();
150                     if (clip_or_mask) {
151                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
152                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
153                         sp_item_invoke_bbox(item,
154                             bbox_of_item,
155                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
156                             true);
157                     } else {
158                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
159                     }
160                     if (bbox_of_item) {
161                         // See if the item is within range
162                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
163                             // This item is within snapping range, so record it as a candidate
164                             _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
165                             // For debugging: print the id of the candidate to the console
166                             // SPObject *obj = (SPObject*)item;
167                             // std::cout << "Snap candidate added: " << obj->id << std::endl;
168                         }
169                     }
170                 }
171             }
172         }
173     }
177 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapPreferences::PointType const &t,
178                                          bool const &first_point) const
180     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
181     // e.g. when translating an item using the selector tool, then we will only do this for the
182     // first point and store the collection for later use. This significantly improves the performance
183     if (first_point) {
184         _points_to_snap_to->clear();
186          // Determine the type of bounding box we should snap to
187         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
189         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
190         bool p_is_a_bbox = t & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
191         bool p_is_a_guide = t & Inkscape::SnapPreferences::SNAPPOINT_GUIDE;
193         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
194         g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_a_guide) || (p_is_a_node && p_is_a_guide)));
196         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
197             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
198             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
199             bbox_type = !prefs_bbox ?
200                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
201         }
203         // Consider the page border for snapping to
204         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
205             _getBorderNodes(_points_to_snap_to);
206         }
208         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
209             //Geom::Matrix i2doc(Geom::identity());
210             SPItem *root_item = (*i).item;
211             if (SP_IS_USE((*i).item)) {
212                 root_item = sp_use_root(SP_USE((*i).item));
213             }
214             g_return_if_fail(root_item);
216             //Collect all nodes so we can snap to them
217                         if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_a_guide) {
218                                 // Note: there are two ways in which intersections are considered:
219                                 // Method 1: Intersections are calculated for each shape individually, for both the
220                                 //           snap source and snap target (see sp_shape_snappoints)
221                                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
222                                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
223                                 // Some differences:
224                                 // - Method 1 doesn't find intersections within a set of multiple objects
225                                 // - Method 2 only works for targets
226                                 // When considering intersections as snap targets:
227                                 // - Method 1 only works when snapping to nodes, whereas
228                                 // - Method 2 only works when snapping to paths
229                                 // - There will be performance differences too!
230                                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
232                                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
233                                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
234                                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
235                                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
236                                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
237                                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
238                                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
239                                         _snapmanager->snapprefs.setSnapIntersectionCS(false);
240                                 }
242                                 sp_item_snappoints(root_item, true, *_points_to_snap_to, &_snapmanager->snapprefs);
244                                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
245                                         _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
246                                 }
247                         }
249             //Collect the bounding box's corners so we can snap to them
250                         if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_a_guide) {
251                                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
252                                 // of the item AND the bbox of the clipping path at the same time
253                                 if (!(*i).clip_or_mask) {
254                                         Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
255                                         getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
256                                 }
257                         }
258         }
259     }
262 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
263                                          Inkscape::SnapPreferences::PointType const &t,
264                                          Geom::Point const &p,
265                                          SnapSourceType const &source_type,
266                                          bool const &first_point,
267                                          std::vector<std::pair<Geom::Point, int> > *unselected_nodes) const
269     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
271     _collectNodes(t, first_point);
273     if (unselected_nodes != NULL) {
274         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
275     }
277     SnappedPoint s;
278     bool success = false;
280     for (std::vector<std::pair<Geom::Point, int> >::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
281         Geom::Coord dist = Geom::L2((*k).first - p);
282         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
283             s = SnappedPoint((*k).first, source_type, static_cast<Inkscape::SnapTargetType>((*k).second), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
284             success = true;
285         }
286     }
288     if (success) {
289         sc.points.push_back(s);
290     }
293 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
294                                          Inkscape::SnapPreferences::PointType const &t,
295                                          Geom::Point const &p,
296                                          Geom::Point const &guide_normal) const
298     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
299     _collectNodes(t, true);
301     SnappedPoint s;
302     bool success = false;
304     Geom::Coord tol = getSnapperTolerance();
306     for (std::vector<std::pair<Geom::Point, int> >::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
307         // Project each node (*k) on the guide line (running through point p)
308         Geom::Point p_proj = Geom::projection((*k).first, Geom::Line(p, p + Geom::rot90(guide_normal)));
309         Geom::Coord dist = Geom::L2((*k).first - p_proj); // distance from node to the guide
310         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
311         if ((dist < tol && dist2 < tol) || (getSnapperAlwaysSnap() && dist < s.getSnapDistance())) {
312             s = SnappedPoint((*k).first, SNAPSOURCE_GUIDE, static_cast<Inkscape::SnapTargetType>((*k).second), dist, tol, getSnapperAlwaysSnap(), true);
313             success = true;
314         }
315     }
317     if (success) {
318         sc.points.push_back(s);
319     }
323 /**
324  * Returns index of first NR_END bpath in array.
325  */
327 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapPreferences::PointType const &t,
328                                          bool const &first_point) const
330     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
331     // e.g. when translating an item using the selector tool, then we will only do this for the
332     // first point and store the collection for later use. This significantly improves the performance
333     if (first_point) {
334         _clear_paths();
336         // Determine the type of bounding box we should snap to
337         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
339         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
341         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
342             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
343             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
344             bbox_type = !prefs_bbox ?
345                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
346         }
348         // Consider the page border for snapping
349         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
350             Geom::PathVector *border_path = _getBorderPathv();
351             if (border_path != NULL) {
352                 _paths_to_snap_to->push_back(std::make_pair(border_path, SNAPTARGET_PAGE_BORDER));
353             }
354         }
356         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
358             /* Transform the requested snap point to this item's coordinates */
359             Geom::Matrix i2doc(Geom::identity());
360             SPItem *root_item = NULL;
361             /* We might have a clone at hand, so make sure we get the root item */
362             if (SP_IS_USE((*i).item)) {
363                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
364                 root_item = sp_use_root(SP_USE((*i).item));
365                 g_return_if_fail(root_item);
366             } else {
367                 i2doc = sp_item_i2doc_affine((*i).item);
368                 root_item = (*i).item;
369             }
371             //Build a list of all paths considered for snapping to
373             //Add the item's path to snap to
374             if (_snapmanager->snapprefs.getSnapToItemPath()) {
375                 if (!(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
376                     // Snapping to the path of characters is very cool, but for a large
377                     // chunk of text this will take ages! So limit snapping to text paths
378                     // containing max. 240 characters. Snapping the bbox will not be affected
379                     bool very_lenghty_prose = false;
380                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
381                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
382                     }
383                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
384                     // which corresponds to a lag of 500 msec. This is for snapping a rect
385                     // to a single line of text.
387                     // Snapping for example to a traced bitmap is also very stressing for
388                     // the CPU, so we'll only snap to paths having no more than 500 nodes
389                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
390                     bool very_complex_path = false;
391                     if (SP_IS_PATH(root_item)) {
392                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
393                     }
395                     if (!very_lenghty_prose && !very_complex_path) {
396                         SPCurve *curve = curve_for_item(root_item);
397                         if (curve) {
398                             // We will get our own copy of the path, which must be freed at some point
399                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
400                             _paths_to_snap_to->push_back(std::make_pair(borderpathv, SNAPTARGET_PATH)); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
401                             curve->unref();
402                         }
403                     }
404                 }
405             }
407             //Add the item's bounding box to snap to
408             if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
409                 if (!(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
410                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
411                     // of the item AND the bbox of the clipping path at the same time
412                     if (!(*i).clip_or_mask) {
413                         Geom::OptRect rect;
414                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
415                         if (rect) {
416                             Geom::PathVector *path = _getPathvFromRect(*rect);
417                             _paths_to_snap_to->push_back(std::make_pair(path, SNAPTARGET_BBOX_EDGE));
418                         }
419                     }
420                 }
421             }
422         }
423     }
426 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
427                                      Inkscape::SnapPreferences::PointType const &t,
428                                      Geom::Point const &p,
429                                      SnapSourceType const &source_type,
430                                      bool const &first_point,
431                                      std::vector<std::pair<Geom::Point, int> > *unselected_nodes,
432                                      SPPath const *selected_path) const
434     _collectPaths(t, first_point);
435     // Now we can finally do the real snapping, using the paths collected above
437     g_assert(_snapmanager->getDesktop() != NULL);
438     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
440     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
442     if (first_point) {
443         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
444          * currently being edited, because that path requires special care: when snapping to nodes
445          * only the unselected nodes of that path should be considered, and these will be passed on separately.
446          * This path must not be ignored however when snapping to the paths, so we add it here
447          * manually when applicable.
448          *
449          * Note that this path must be the last in line!
450          * */
451         if (node_tool_active) {
452             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
453             if (curve) {
454                 Geom::PathVector *pathv = pathvector_for_curve(SP_ITEM(selected_path), curve, true, true, Geom::identity(), Geom::identity()); // We will get our own copy of the path, which must be freed at some point
455                 _paths_to_snap_to->push_back(std::make_pair(pathv, SNAPTARGET_PATH));
456                 curve->unref();
457             }
458         }
459     }
461     for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
462         bool const being_edited = (node_tool_active && (*it_p) == _paths_to_snap_to->back());
463         //if true then this pathvector it_pv is currently being edited in the node tool
465         // char * svgd = sp_svg_write_path(**it_p->first);
466         // std::cout << "Dumping the pathvector: " << svgd << std::endl;
468         for(Geom::PathVector::iterator it_pv = (it_p->first)->begin(); it_pv != (it_p->first)->end(); ++it_pv) {
469             // Find a nearest point for each curve within this path
470             // n curves will return n time values with 0 <= t <= 1
471             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
473             std::vector<double>::const_iterator np = anp.begin();
474             unsigned int index = 0;
475             for (; np != anp.end(); np++, index++) {
476                 Geom::Curve const *curve = &((*it_pv).at_index(index));
477                 Geom::Point const sp_doc = curve->pointAt(*np);
479                 bool c1 = true;
480                 bool c2 = true;
481                 if (being_edited) {
482                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
483                      * and not to the pieces that are being dragged around. This way we avoid
484                      * self-snapping. For this we check whether the nodes at both ends of the current
485                      * piece are unselected; if they are then this piece must be stationary
486                      */
487                     g_assert(unselected_nodes != NULL);
488                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
489                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
490                     c1 = isUnselectedNode(start_pt, unselected_nodes);
491                     c2 = isUnselectedNode(end_pt, unselected_nodes);
492                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
493                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
494                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
495                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
496                      *   should be in the exact same order for both classes, so we can index them
497                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
498                      */
499                 }
501                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
502                 if (!being_edited || (c1 && c2)) {
503                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
504                     if (dist < getSnapperTolerance()) {
505                         sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, source_type, it_p->second));
506                     }
507                 }
508             }
509         } // End of: for (Geom::PathVector::iterator ....)
510     }
513 /* Returns true if point is coincident with one of the unselected nodes */
514 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<std::pair<Geom::Point, int> > const *unselected_nodes) const
516     if (unselected_nodes == NULL) {
517         return false;
518     }
520     if (unselected_nodes->size() == 0) {
521         return false;
522     }
524     for (std::vector<std::pair<Geom::Point, int> >::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
525         if (Geom::L2(point - (*i).first) < 1e-4) {
526             return true;
527         }
528     }
530     return false;
533 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
534                                      Inkscape::SnapPreferences::PointType const &t,
535                                      Geom::Point const &p,
536                                      SnapSourceType const source_type,
537                                      bool const &first_point,
538                                      ConstraintLine const &c) const
541     _collectPaths(t, first_point);
543     // Now we can finally do the real snapping, using the paths collected above
545     g_assert(_snapmanager->getDesktop() != NULL);
546     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
548     Geom::Point direction_vector = c.getDirection();
549     if (!is_zero(direction_vector)) {
550         direction_vector = Geom::unit_vector(direction_vector);
551     }
553     Geom::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
554     Geom::Point const p2_on_cl = p1_on_cl + direction_vector;
556     // The intersection point of the constraint line with any path,
557     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
558     // The distance between those points is twice the snapping tolerance
559     Geom::Point const p_proj_on_cl = Geom::projection(p, Geom::Line(p1_on_cl, p2_on_cl));
560     Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);
561     Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
563     Geom::Path cl;
564     std::vector<Geom::Path> clv;
565     cl.start(p_min_on_cl);
566     cl.appendNew<Geom::LineSegment>(p_max_on_cl);
567     clv.push_back(cl);
569     for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
570         if (k->first) {
571             Geom::CrossingSet cs = Geom::crossings(clv, *(k->first));
572             if (cs.size() > 0) {
573                 // We need only the first element of cs, because cl is only a single straight linesegment
574                 // This first element contains a vector filled with crossings of cl with k->first
575                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {
576                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
577                         // Reconstruct the point of intersection
578                         Geom::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
579                         // When it's within snapping range, then return it
580                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)
581                         Geom::Coord dist = Geom::L2(_snapmanager->getDesktop()->dt2doc(p_proj_on_cl) - p_inters);
582                         SnappedPoint s(_snapmanager->getDesktop()->doc2dt(p_inters), source_type, k->second, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
583                         sc.points.push_back(s);
584                     }
585                 }
586             }
587         }
588     }
592 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
593                                             Inkscape::SnapPreferences::PointType const &t,
594                                             Geom::Point const &p,
595                                             SnapSourceType const &source_type,
596                                             bool const &first_point,
597                                             Geom::OptRect const &bbox_to_snap,
598                                             std::vector<SPItem const *> const *it,
599                                             std::vector<std::pair<Geom::Point, int> > *unselected_nodes) const
601     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false ) {
602         return;
603     }
605     /* Get a list of all the SPItems that we will try to snap to */
606     if (first_point) {
607         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
608         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
609     }
611     if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
612         || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
613                 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
614                 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
615                 || _snapmanager->snapprefs.getIncludeItemCenter()) {
616         _snapNodes(sc, t, p, source_type, first_point, unselected_nodes);
617     }
619     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
620         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
621         if (n > 0) {
622             /* While editing a path in the node tool, findCandidates must ignore that path because
623              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
624              * That path must not be ignored however when snapping to the paths, so we add it here
625              * manually when applicable
626              */
627             SPPath *path = NULL;
628             if (it != NULL) {
629                 g_assert(SP_IS_PATH(*it->begin()));
630                 g_assert(it->size() == 1);
631                 path = SP_PATH(*it->begin());
632             }
633             _snapPaths(sc, t, p, source_type, first_point, unselected_nodes, path);
634         } else {
635             _snapPaths(sc, t, p, source_type, first_point, NULL, NULL);
636         }
637     }
640 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
641                                                   Inkscape::SnapPreferences::PointType const &t,
642                                                   Geom::Point const &p,
643                                                   SnapSourceType const &source_type,
644                                                   bool const &first_point,
645                                                   Geom::OptRect const &bbox_to_snap,
646                                                   ConstraintLine const &c,
647                                                   std::vector<SPItem const *> const *it) const
649     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false) {
650         return;
651     }
653     /* Get a list of all the SPItems that we will try to snap to */
654     if (first_point) {
655         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
656         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
657     }
659     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
660     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
661     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
663     // When snapping to objects, we either snap to their nodes or their paths. It is however very
664     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
665     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
666     // so we will more or less snap to them anyhow.
668     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
669         _snapPathsConstrained(sc, t, p, source_type, first_point, c);
670     }
674 // This method is used to snap a guide to nodes, while dragging the guide around
675 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
676                                         Geom::Point const &p,
677                                         Geom::Point const &guide_normal) const
679     /* Get a list of all the SPItems that we will try to snap to */
680     std::vector<SPItem*> cand;
681     std::vector<SPItem const *> const it; //just an empty list
683     DimensionToSnap snap_dim;
684     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
685         snap_dim = GUIDE_TRANSL_SNAP_Y;
686     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
687         snap_dim = GUIDE_TRANSL_SNAP_X;
688     } else {
689         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
690     }
692     // We don't support ANGLED_GUIDE_ROT_SNAP yet.
694     // It would be cool to allow the user to rotate a guide by dragging it, instead of
695     // only translating it. (For example when CTRL is pressed). We will need an UI part
696     // for that first; and some important usability choices need to be made:
697     // E.g. which point should be used for pivoting? A previously snapped point,
698     // or a transformation center (which can be moved after clicking for the
699     // second time on an object; but should this point then be constrained to the
700     // line, or can it be located anywhere?)
702     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
703     _snapTranslatingGuideToNodes(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, guide_normal);
704     // _snapRotatingGuideToNodes has not been implemented yet.
707 /**
708  *  \return true if this Snapper will snap at least one kind of point.
709  */
710 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
712     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
713                                                 || _snapmanager->snapprefs.getSnapToItemNode()
714                                                 || _snapmanager->snapprefs.getSnapToBBoxPath()
715                                                 || _snapmanager->snapprefs.getSnapToBBoxNode()
716                                                 || _snapmanager->snapprefs.getSnapToPageBorder()
717                                                 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
718                                                 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
719                                                 || _snapmanager->snapprefs.getIncludeItemCenter();
721     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
724 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
726     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapToBBoxNode();
727     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
730 void Inkscape::ObjectSnapper::_clear_paths() const
732     for (std::vector<std::pair<Geom::PathVector*, SnapTargetType> >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
733         g_free(k->first);
734     }
735     _paths_to_snap_to->clear();
738 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
740     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
741     return _getPathvFromRect(border_rect);
744 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
746     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
747     if (border_curve) {
748         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
749         return dummy;
750     } else {
751         return NULL;
752     }
755 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<std::pair<Geom::Point, int> > *points) const
757     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
758     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
759     points->push_back(std::make_pair(Geom::Point(0,0), SNAPTARGET_PAGE_CORNER));
760     points->push_back(std::make_pair(Geom::Point(0,h), SNAPTARGET_PAGE_CORNER));
761     points->push_back(std::make_pair(Geom::Point(w,h), SNAPTARGET_PAGE_CORNER));
762     points->push_back(std::make_pair(Geom::Point(w,0), SNAPTARGET_PAGE_CORNER));
765 void Inkscape::getBBoxPoints(Geom::OptRect const bbox, std::vector<std::pair<Geom::Point, int> > *points, bool const isTarget, bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints)
767         if (bbox) {
768                 // collect the corners of the bounding box
769                 for ( unsigned k = 0 ; k < 4 ; k++ ) {
770                         if (includeCorners) {
771                                 points->push_back(std::make_pair((bbox->corner(k)), isTarget ? int(Inkscape::SNAPTARGET_BBOX_CORNER) : int(Inkscape::SNAPSOURCE_BBOX_CORNER)));
772                         }
773                         // optionally, collect the midpoints of the bounding box's edges too
774                         if (includeLineMidpoints) {
775                                 points->push_back(std::make_pair((bbox->corner(k) + bbox->corner((k+1) % 4))/2, isTarget ? int(Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT) : int(Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT)));
776                         }
777                 }
778                 if (includeObjectMidpoints) {
779                         points->push_back(std::make_pair(bbox->midpoint(), isTarget ? int(Inkscape::SNAPTARGET_BBOX_MIDPOINT) : int(Inkscape::SNAPSOURCE_BBOX_MIDPOINT)));
780                 }
781         }
784 /*
785   Local Variables:
786   mode:c++
787   c-file-style:"stroustrup"
788   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
789   indent-tabs-mode:nil
790   fill-column:99
791   End:
792 */
793 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :