Code

small cleanup in src/trace (warnings and trailing spaces)
[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 "document.h"
21 #include "sp-namedview.h"
22 #include "sp-image.h"
23 #include "sp-item-group.h"
24 #include "sp-item.h"
25 #include "sp-use.h"
26 #include "display/curve.h"
27 #include "inkscape.h"
28 #include "preferences.h"
29 #include "sp-text.h"
30 #include "sp-flowtext.h"
31 #include "text-editing.h"
32 #include "sp-clippath.h"
33 #include "sp-mask.h"
34 #include "helper/geom-curves.h"
35 #include "desktop.h"
37 Inkscape::SnapCandidate::SnapCandidate(SPItem* item, bool clip_or_mask, Geom::Matrix additional_affine)
38     : item(item), clip_or_mask(clip_or_mask), additional_affine(additional_affine)
39 {
40 }
42 Inkscape::SnapCandidate::~SnapCandidate()
43 {
44 }
46 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
47     : Snapper(sm, d)
48 {
49     _candidates = new std::vector<SnapCandidate>;
50     _points_to_snap_to = new std::vector<Geom::Point>;
51     _paths_to_snap_to = new std::vector<Geom::PathVector*>;
52 }
54 Inkscape::ObjectSnapper::~ObjectSnapper()
55 {
56     _candidates->clear();
57     delete _candidates;
59     _points_to_snap_to->clear();
60     delete _points_to_snap_to;
62     _clear_paths();
63     delete _paths_to_snap_to;
64 }
66 /**
67  *  Find all items within snapping range.
68  *  \param parent Pointer to the document's root, or to a clipped path or mask object
69  *  \param it List of items to ignore
70  *  \param first_point If true then this point is the first one from a whole bunch of points
71  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
72  *  \param DimensionToSnap Snap in X, Y, or both directions.
73  */
75 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
76                                               std::vector<SPItem const *> const *it,
77                                               bool const &first_point,
78                                               Geom::Rect const &bbox_to_snap,
79                                               DimensionToSnap const snap_dim,
80                                               bool const clip_or_mask,
81                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
82 {
83     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
84     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
86     if (!(c1 || c2)) {
87         return;
88     }
90     if (first_point) {
91         _candidates->clear();
92     }
94     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
95     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
97     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
98         g_assert(_snapmanager->getDesktop() != NULL);
99         if (SP_IS_ITEM(o) && !SP_ITEM(o)->isLocked() && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
100             // Don't snap to locked items, and
101             // don't snap to hidden objects, unless they're a clipped path or a mask
102             /* See if this item is on the ignore list */
103             std::vector<SPItem const *>::const_iterator i;
104             if (it != NULL) {
105                 i = it->begin();
106                 while (i != it->end() && *i != o) {
107                     i++;
108                 }
109             }
111             if (it == NULL || i == it->end()) {
112                 SPItem *item = SP_ITEM(o);
113                 if (item) {
114                     SPObject *obj = NULL;
115                     if (!clip_or_mask) { // cannot clip or mask more than once
116                         // The current item is not a clipping path or a mask, but might
117                         // still be the subject of clipping or masking itself ; if so, then
118                         // we should also consider that path or mask for snapping to
119                         obj = SP_OBJECT(item->clip_ref->getObject());
120                         if (obj) {
121                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
122                         }
123                         obj = SP_OBJECT(item->mask_ref->getObject());
124                         if (obj) {
125                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
126                         }
127                     }
128                 }
130                 if (SP_IS_GROUP(o)) {
131                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
132                 } else {
133                     Geom::OptRect bbox_of_item = Geom::Rect();
134                     if (clip_or_mask) {
135                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
136                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
137                         sp_item_invoke_bbox(item,
138                             bbox_of_item,
139                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
140                             true);
141                     } else {
142                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
143                     }
144                     if (bbox_of_item) {
145                         // See if the item is within range
146                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
147                             // This item is within snapping range, so record it as a candidate
148                             _candidates->push_back(SnapCandidate(item, clip_or_mask, additional_affine));
149                         }
150                     }
151                 }
152             }
153         }
154     }
158 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapPreferences::PointType const &t,
159                                          bool const &first_point) const
161     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
162     // e.g. when translating an item using the selector tool, then we will only do this for the
163     // first point and store the collection for later use. This significantly improves the performance
164     if (first_point) {
165         _points_to_snap_to->clear();
167          // Determine the type of bounding box we should snap to
168         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
170         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
171         bool p_is_a_bbox = t & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
172         bool p_is_a_guide = t & Inkscape::SnapPreferences::SNAPPOINT_GUIDE;
174         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
175         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)));
177         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
178             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
179             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
180             bbox_type = !prefs_bbox ?
181                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
182         }
184         // Consider the page border for snapping
185         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
186             _getBorderNodes(_points_to_snap_to);
187         }
189         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
190             //Geom::Matrix i2doc(Geom::identity());
191             SPItem *root_item = (*i).item;
192             if (SP_IS_USE((*i).item)) {
193                 root_item = sp_use_root(SP_USE((*i).item));
194             }
195             g_return_if_fail(root_item);
197             //Collect all nodes so we can snap to them
198                         if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_a_guide) {
199                                 // Note: there are two ways in which intersections are considered:
200                                 // Method 1: Intersections are calculated for each shape individually, for both the
201                                 //           snap source and snap target (see sp_shape_snappoints)
202                                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
203                                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
204                                 // Some differences:
205                                 // - Method 1 doesn't find intersections within a set of multiple objects
206                                 // - Method 2 only works for targets
207                                 // When considering intersections as snap targets:
208                                 // - Method 1 only works when snapping to nodes, whereas
209                                 // - Method 2 only works when snapping to paths
210                                 // - There will be performance differences too!
211                                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
213                                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
214                                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
215                                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
216                                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
217                                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
218                                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
219                                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
220                                         _snapmanager->snapprefs.setSnapIntersectionCS(false);
221                                 }
223                                 sp_item_snappoints(root_item, SnapPointsIter(*_points_to_snap_to), &_snapmanager->snapprefs);
225                                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
226                                         _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
227                                 }
228                         }
230             //Collect the bounding box's corners so we can snap to them
231                         if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_a_guide) {
232                                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
233                                 // of the item AND the bbox of the clipping path at the same time
234                                 if (!(*i).clip_or_mask) {
235                                         Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
236                                         getBBoxPoints(b, _points_to_snap_to, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
237                                 }
238                         }
239         }
240     }
243 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
244                                          Inkscape::SnapPreferences::PointType const &t,
245                                          Geom::Point const &p,
246                                          bool const &first_point,
247                                          std::vector<Geom::Point> *unselected_nodes) const
249     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
251     _collectNodes(t, first_point);
253     if (unselected_nodes != NULL) {
254         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
255     }
257     SnappedPoint s;
258     bool success = false;
260     for (std::vector<Geom::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
261         Geom::Coord dist = Geom::L2(*k - p);
262         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
263             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
264             success = true;
265         }
266     }
268     if (success) {
269         sc.points.push_back(s);
270     }
273 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
274                                          Inkscape::SnapPreferences::PointType const &t,
275                                          Geom::Point const &p,
276                                          Geom::Point const &guide_normal) const
278     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
279     _collectNodes(t, true);
281     SnappedPoint s;
282     bool success = false;
284     Geom::Coord tol = getSnapperTolerance();
286     for (std::vector<Geom::Point>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
287         // Project each node (*k) on the guide line (running through point p)
288         Geom::Point p_proj = project_on_linesegment(*k, p, p + Geom::rot90(guide_normal));
289         Geom::Coord dist = Geom::L2(*k - p_proj); // distance from node to the guide
290         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
291         if ((dist < tol && dist2 < tol) || (getSnapperAlwaysSnap() && dist < s.getSnapDistance())) {
292             s = SnappedPoint(*k, SNAPTARGET_NODE, dist, tol, getSnapperAlwaysSnap(), true);
293             success = true;
294         }
295     }
297     if (success) {
298         sc.points.push_back(s);
299     }
303 /**
304  * Returns index of first NR_END bpath in array.
305  */
307 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapPreferences::PointType const &t,
308                                          bool const &first_point) const
310     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
311     // e.g. when translating an item using the selector tool, then we will only do this for the
312     // first point and store the collection for later use. This significantly improves the performance
313     if (first_point) {
314         _clear_paths();
316         // Determine the type of bounding box we should snap to
317         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
319         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
321         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
322             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
323             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
324             bbox_type = !prefs_bbox ?
325                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
326         }
328         // Consider the page border for snapping
329         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
330             Geom::PathVector *border_path = _getBorderPathv();
331             if (border_path != NULL) {
332                 _paths_to_snap_to->push_back(border_path);
333             }
334         }
336         for (std::vector<SnapCandidate>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
338             /* Transform the requested snap point to this item's coordinates */
339             Geom::Matrix i2doc(Geom::identity());
340             SPItem *root_item = NULL;
341             /* We might have a clone at hand, so make sure we get the root item */
342             if (SP_IS_USE((*i).item)) {
343                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
344                 root_item = sp_use_root(SP_USE((*i).item));
345                 g_return_if_fail(root_item);
346             } else {
347                 i2doc = sp_item_i2doc_affine((*i).item);
348                 root_item = (*i).item;
349             }
351             //Build a list of all paths considered for snapping to
353             //Add the item's path to snap to
354             if (_snapmanager->snapprefs.getSnapToItemPath()) {
355                 if (!(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
356                     // Snapping to the path of characters is very cool, but for a large
357                     // chunk of text this will take ages! So limit snapping to text paths
358                     // containing max. 240 characters. Snapping the bbox will not be affected
359                     bool very_lenghty_prose = false;
360                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
361                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
362                     }
363                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
364                     // which corresponds to a lag of 500 msec. This is for snapping a rect
365                     // to a single line of text.
367                     // Snapping for example to a traced bitmap is also very stressing for
368                     // the CPU, so we'll only snap to paths having no more than 500 nodes
369                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
370                     bool very_complex_path = false;
371                     if (SP_IS_PATH(root_item)) {
372                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
373                     }
375                     if (!very_lenghty_prose && !very_complex_path) {
376                         SPCurve *curve = curve_for_item(root_item);
377                         if (curve) {
378                             // We will get our own copy of the path, which must be freed at some point
379                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
380                             _paths_to_snap_to->push_back(borderpathv); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
381                             curve->unref();
382                         }
383                     }
384                 }
385             }
387             //Add the item's bounding box to snap to
388             if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
389                 if (!(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
390                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
391                     // of the item AND the bbox of the clipping path at the same time
392                     if (!(*i).clip_or_mask) {
393                         Geom::OptRect rect;
394                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
395                         if (rect) {
396                             Geom::PathVector *path = _getPathvFromRect(*rect);
397                             _paths_to_snap_to->push_back(path);
398                         }
399                     }
400                 }
401             }
402         }
403     }
406 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
407                                      Inkscape::SnapPreferences::PointType const &t,
408                                      Geom::Point const &p,
409                                      bool const &first_point,
410                                      std::vector<Geom::Point> *unselected_nodes,
411                                      SPPath const *selected_path) const
413     _collectPaths(t, first_point);
414     // Now we can finally do the real snapping, using the paths collected above
416     g_assert(_snapmanager->getDesktop() != NULL);
417     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
419     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
421     if (first_point) {
422         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
423          * currently being edited, because that path requires special care: when snapping to nodes
424          * only the unselected nodes of that path should be considered, and these will be passed on separately.
425          * This path must not be ignored however when snapping to the paths, so we add it here
426          * manually when applicable.
427          *
428          * Note that this path must be the last in line!
429          * */
430         if (node_tool_active) {
431             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
432             if (curve) {
433                 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
434                 _paths_to_snap_to->push_back(pathv);
435                 curve->unref();
436             }
437         }
438     }
440     for (std::vector<Geom::PathVector*>::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
441         bool const being_edited = (node_tool_active && (*it_p) == _paths_to_snap_to->back());
442         //if true then this pathvector it_pv is currently being edited in the node tool
444         // char * svgd = sp_svg_write_path(**it_p);
445         // std::cout << "Dumping the pathvector: " << svgd << std::endl;
447         for(Geom::PathVector::iterator it_pv = (*it_p)->begin(); it_pv != (*it_p)->end(); ++it_pv) {
448             // Find a nearest point for each curve within this path
449             // n curves will return n time values with 0 <= t <= 1
450             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
452             std::vector<double>::const_iterator np = anp.begin();
453             unsigned int index = 0;
454             for (; np != anp.end(); np++, index++) {
455                 Geom::Curve const *curve = &((*it_pv).at_index(index));
456                 Geom::Point const sp_doc = curve->pointAt(*np);
458                 bool c1 = true;
459                 bool c2 = true;
460                 if (being_edited) {
461                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
462                      * and not to the pieces that are being dragged around. This way we avoid
463                      * self-snapping. For this we check whether the nodes at both ends of the current
464                      * piece are unselected; if they are then this piece must be stationary
465                      */
466                     g_assert(unselected_nodes != NULL);
467                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
468                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
469                     c1 = isUnselectedNode(start_pt, unselected_nodes);
470                     c2 = isUnselectedNode(end_pt, unselected_nodes);
471                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
472                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
473                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
474                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
475                      *   should be in the exact same order for both classes, so we can index them
476                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
477                      */
478                 }
480                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
481                 if (!being_edited || (c1 && c2)) {
482                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
483                     if (dist < getSnapperTolerance()) {
484                         sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve));
485                     }
486                 }
487             }
488         } // End of: for (Geom::PathVector::iterator ....)
489     }
492 /* Returns true if point is coincident with one of the unselected nodes */
493 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Geom::Point> const *unselected_nodes) const
495     if (unselected_nodes == NULL) {
496         return false;
497     }
499     if (unselected_nodes->size() == 0) {
500         return false;
501     }
503     for (std::vector<Geom::Point>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
504         if (Geom::L2(point - *i) < 1e-4) {
505             return true;
506         }
507     }
509     return false;
512 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
513                                      Inkscape::SnapPreferences::PointType const &t,
514                                      Geom::Point const &p,
515                                      bool const &first_point,
516                                      ConstraintLine const &c) const
519     _collectPaths(t, first_point);
521     // Now we can finally do the real snapping, using the paths collected above
523     g_assert(_snapmanager->getDesktop() != NULL);
524     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p);
526     Geom::Point direction_vector = c.getDirection();
527     if (!is_zero(direction_vector)) {
528         direction_vector = Geom::unit_vector(direction_vector);
529     }
531     Geom::Point const p1_on_cl = c.hasPoint() ? c.getPoint() : p;
532     Geom::Point const p2_on_cl = p1_on_cl + direction_vector;
534     // The intersection point of the constraint line with any path,
535     // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
536     // The distance between those points is twice the snapping tolerance
537     Geom::Point const p_proj_on_cl = project_on_linesegment(p, p1_on_cl, p2_on_cl);
538     Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);
539     Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
541     Geom::Path cl;
542     std::vector<Geom::Path> clv;
543     cl.start(p_min_on_cl);
544     cl.appendNew<Geom::LineSegment>(p_max_on_cl);
545     clv.push_back(cl);
547     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
548         if (*k) {
549             Geom::CrossingSet cs = Geom::crossings(clv, *(*k));
550             if (cs.size() > 0) {
551                 // We need only the first element of cs, because cl is only a single straight linesegment
552                 // This first element contains a vector filled with crossings of cl with *k
553                 for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {
554                     if ((*m).ta >= 0 && (*m).ta <= 1 ) {
555                         // Reconstruct the point of intersection
556                         Geom::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
557                         // When it's within snapping range, then return it
558                         // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)
559                         Geom::Coord dist = Geom::L2(_snapmanager->getDesktop()->dt2doc(p_proj_on_cl) - p_inters);
560                         SnappedPoint s(_snapmanager->getDesktop()->doc2dt(p_inters), SNAPTARGET_PATH, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true);
561                         sc.points.push_back(s);
562                     }
563                 }
564             }
565         }
566     }
570 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
571                                             Inkscape::SnapPreferences::PointType const &t,
572                                             Geom::Point const &p,
573                                             bool const &first_point,
574                                             Geom::OptRect const &bbox_to_snap,
575                                             std::vector<SPItem const *> const *it,
576                                             std::vector<Geom::Point> *unselected_nodes) const
578     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false ) {
579         return;
580     }
582     /* Get a list of all the SPItems that we will try to snap to */
583     if (first_point) {
584         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
585         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
586     }
588     if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
589         || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
590                 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
591                 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
592                 || _snapmanager->snapprefs.getIncludeItemCenter()) {
593         _snapNodes(sc, t, p, first_point, unselected_nodes);
594     }
596     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
597         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
598         if (n > 0) {
599             /* While editing a path in the node tool, findCandidates must ignore that path because
600              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
601              * That path must not be ignored however when snapping to the paths, so we add it here
602              * manually when applicable
603              */
604             SPPath *path = NULL;
605             if (it != NULL) {
606                 g_assert(SP_IS_PATH(*it->begin()));
607                 g_assert(it->size() == 1);
608                 path = SP_PATH(*it->begin());
609             }
610             _snapPaths(sc, t, p, first_point, unselected_nodes, path);
611         } else {
612             _snapPaths(sc, t, p, first_point, NULL, NULL);
613         }
614     }
617 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
618                                                   Inkscape::SnapPreferences::PointType const &t,
619                                                   Geom::Point const &p,
620                                                   bool const &first_point,
621                                                   Geom::OptRect const &bbox_to_snap,
622                                                   ConstraintLine const &c,
623                                                   std::vector<SPItem const *> const *it) const
625     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false) {
626         return;
627     }
629     /* Get a list of all the SPItems that we will try to snap to */
630     if (first_point) {
631         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p, p);
632         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, first_point, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
633     }
635     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
636     // This is usefull for example when scaling an object while maintaining a fixed aspect ratio. It's
637     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
639     // When snapping to objects, we either snap to their nodes or their paths. It is however very
640     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
641     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
642     // so we will more or less snap to them anyhow.
644     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
645         _snapPathsConstrained(sc, t, p, first_point, c);
646     }
650 // This method is used to snap a guide to nodes, while dragging the guide around
651 void Inkscape::ObjectSnapper::guideSnap(SnappedConstraints &sc,
652                                         Geom::Point const &p,
653                                         Geom::Point const &guide_normal) const
655     /* Get a list of all the SPItems that we will try to snap to */
656     std::vector<SPItem*> cand;
657     std::vector<SPItem const *> const it; //just an empty list
659     DimensionToSnap snap_dim;
660     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
661         snap_dim = GUIDE_TRANSL_SNAP_Y;
662     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
663         snap_dim = GUIDE_TRANSL_SNAP_X;
664     } else {
665         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
666     }
668     // We don't support ANGLED_GUIDE_ROT_SNAP yet.
670     // It would be cool to allow the user to rotate a guide by dragging it, instead of
671     // only translating it. (For example when CTRL is pressed). We will need an UI part
672     // for that first; and some important usability choices need to be made:
673     // E.g. which point should be used for pivoting? A previously snapped point,
674     // or a transformation center (which can be moved after clicking for the
675     // second time on an object; but should this point then be constrained to the
676     // line, or can it be located anywhere?)
678     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
679     _snapTranslatingGuideToNodes(sc, Inkscape::SnapPreferences::SNAPPOINT_GUIDE, p, guide_normal);
680     // _snapRotatingGuideToNodes has not been implemented yet.
683 /**
684  *  \return true if this Snapper will snap at least one kind of point.
685  */
686 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
688     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
689                                                 || _snapmanager->snapprefs.getSnapToItemNode()
690                                                 || _snapmanager->snapprefs.getSnapToBBoxPath()
691                                                 || _snapmanager->snapprefs.getSnapToBBoxNode()
692                                                 || _snapmanager->snapprefs.getSnapToPageBorder()
693                                                 || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
694                                                 || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
695                                                 || _snapmanager->snapprefs.getIncludeItemCenter();
697     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
700 bool Inkscape::ObjectSnapper::GuidesMightSnap() const
702     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapToBBoxNode();
703     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
706 void Inkscape::ObjectSnapper::_clear_paths() const
708     for (std::vector<Geom::PathVector*>::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
709         g_free(*k);
710     }
711     _paths_to_snap_to->clear();
714 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
716     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
717     return _getPathvFromRect(border_rect);
720 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
722     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
723     if (border_curve) {
724         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
725         return dummy;
726     } else {
727         return NULL;
728     }
731 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<Geom::Point> *points) const
733     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
734     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
735     points->push_back(Geom::Point(0,0));
736     points->push_back(Geom::Point(0,h));
737     points->push_back(Geom::Point(w,h));
738     points->push_back(Geom::Point(w,0));
741 void Inkscape::getBBoxPoints(Geom::OptRect const bbox, std::vector<Geom::Point> *points, bool const includeCorners, bool const includeLineMidpoints, bool const includeObjectMidpoints)
743         if (bbox) {
744                 // collect the corners of the bounding box
745                 for ( unsigned k = 0 ; k < 4 ; k++ ) {
746                         if (includeCorners) {
747                                 points->push_back(bbox->corner(k));
748                         }
749                         // optionally, collect the midpoints of the bounding box's edges too
750                         if (includeLineMidpoints) {
751                                 points->push_back((bbox->corner(k) + bbox->corner((k+1) % 4))/2);
752                         }
753                 }
754                 if (includeObjectMidpoints) {
755                         points->push_back(bbox->midpoint());
756                 }
757         }
760 /*
761   Local Variables:
762   mode:c++
763   c-file-style:"stroustrup"
764   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
765   indent-tabs-mode:nil
766   fill-column:99
767   End:
768 */
769 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :