Code

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