Code

When snapping to a bounding box, flash that bounding box together with the snap indicator
[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 <2geom/path-intersection.h>
16 #include <2geom/point.h>
17 #include <2geom/rect.h>
18 #include <2geom/line.h>
19 #include "document.h"
20 #include "sp-namedview.h"
21 #include "sp-image.h"
22 #include "sp-item-group.h"
23 #include "sp-item.h"
24 #include "sp-use.h"
25 #include "display/curve.h"
26 #include "inkscape.h"
27 #include "preferences.h"
28 #include "sp-text.h"
29 #include "sp-flowtext.h"
30 #include "text-editing.h"
31 #include "sp-clippath.h"
32 #include "sp-mask.h"
33 #include "helper/geom-curves.h"
34 #include "desktop.h"
36 Inkscape::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
37     : Snapper(sm, d)
38 {
39     _candidates = new std::vector<SnapCandidateItem>;
40     _points_to_snap_to = new std::vector<Inkscape::SnapCandidatePoint>;
41     _paths_to_snap_to = new std::vector<Inkscape::SnapCandidatePath >;
42 }
44 Inkscape::ObjectSnapper::~ObjectSnapper()
45 {
46     _candidates->clear();
47     delete _candidates;
49     _points_to_snap_to->clear();
50     delete _points_to_snap_to;
52     _clear_paths();
53     delete _paths_to_snap_to;
54 }
56 /**
57  *  \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
58  */
59 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
60 {
61     SPDesktop const *dt = _snapmanager->getDesktop();
62     double const zoom =  dt ? dt->current_zoom() : 1;
63     return _snapmanager->snapprefs.getObjectTolerance() / zoom;
64 }
66 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
67 {
68     return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
69 }
71 /**
72  *  Find all items within snapping range.
73  *  \param parent Pointer to the document's root, or to a clipped path or mask object
74  *  \param it List of items to ignore
75  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
76  *  \param DimensionToSnap Snap in X, Y, or both directions.
77  */
79 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
80                                               std::vector<SPItem const *> const *it,
81                                               bool const &first_point,
82                                               Geom::Rect const &bbox_to_snap,
83                                               DimensionToSnap const snap_dim,
84                                               bool const clip_or_mask,
85                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
86 {
87     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
88     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
90     if (!(c1 || c2)) {
91         return;
92     }
94     if (first_point) {
95         _candidates->clear();
96     }
98     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
99     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
101     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
102         g_assert(_snapmanager->getDesktop() != NULL);
103         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
104             // Snapping to items in a locked layer is allowed
105             // Don't snap to hidden objects, unless they're a clipped path or a mask
106             /* See if this item is on the ignore list */
107             std::vector<SPItem const *>::const_iterator i;
108             if (it != NULL) {
109                 i = it->begin();
110                 while (i != it->end() && *i != o) {
111                     i++;
112                 }
113             }
115             if (it == NULL || i == it->end()) {
116                 SPItem *item = SP_ITEM(o);
117                 if (item) {
118                     SPObject *obj = NULL;
119                     if (!clip_or_mask) { // cannot clip or mask more than once
120                         // The current item is not a clipping path or a mask, but might
121                         // still be the subject of clipping or masking itself ; if so, then
122                         // we should also consider that path or mask for snapping to
123                         obj = SP_OBJECT(item->clip_ref->getObject());
124                         if (obj) {
125                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
126                         }
127                         obj = SP_OBJECT(item->mask_ref->getObject());
128                         if (obj) {
129                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
130                         }
131                     }
132                 }
134                 if (SP_IS_GROUP(o)) {
135                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
136                 } else {
137                     Geom::OptRect bbox_of_item = Geom::Rect();
138                     if (clip_or_mask) {
139                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
140                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
141                         sp_item_invoke_bbox(item,
142                             bbox_of_item,
143                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
144                             true);
145                     } else {
146                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
147                     }
148                     if (bbox_of_item) {
149                         // See if the item is within range
150                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
151                             // This item is within snapping range, so record it as a candidate
152                             _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
153                             // For debugging: print the id of the candidate to the console
154                             //SPObject *obj = (SPObject*)item;
155                             //std::cout << "Snap candidate added: " << obj->id << std::endl;
156                         }
157                     }
158                 }
159             }
160         }
161     }
165 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapPreferences::PointType const &t,
166                                             bool const &first_point) const
168     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
169     // e.g. when translating an item using the selector tool, then we will only do this for the
170     // first point and store the collection for later use. This significantly improves the performance
171     if (first_point) {
172         _points_to_snap_to->clear();
174          // Determine the type of bounding box we should snap to
175         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
177         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
178         bool p_is_a_bbox = t & Inkscape::SnapPreferences::SNAPPOINT_BBOX;
179         bool p_is_other = t & Inkscape::SnapPreferences::SNAPPOINT_OTHER;
181         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
182         g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
184         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
185             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
186             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
187             bbox_type = !prefs_bbox ?
188                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
189         }
191         // Consider the page border for snapping to
192         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
193             _getBorderNodes(_points_to_snap_to);
194         }
196         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
197             //Geom::Matrix i2doc(Geom::identity());
198             SPItem *root_item = (*i).item;
199             if (SP_IS_USE((*i).item)) {
200                 root_item = sp_use_root(SP_USE((*i).item));
201             }
202             g_return_if_fail(root_item);
204             //Collect all nodes so we can snap to them
205             if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
206                 // Note: there are two ways in which intersections are considered:
207                 // Method 1: Intersections are calculated for each shape individually, for both the
208                 //           snap source and snap target (see sp_shape_snappoints)
209                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
210                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
211                 // Some differences:
212                 // - Method 1 doesn't find intersections within a set of multiple objects
213                 // - Method 2 only works for targets
214                 // When considering intersections as snap targets:
215                 // - Method 1 only works when snapping to nodes, whereas
216                 // - Method 2 only works when snapping to paths
217                 // - There will be performance differences too!
218                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
220                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
221                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
222                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
223                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
224                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
225                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
226                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
227                     _snapmanager->snapprefs.setSnapIntersectionCS(false);
228                 }
230                 sp_item_snappoints(root_item, *_points_to_snap_to, &_snapmanager->snapprefs);
232                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
233                     _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
234                 }
235             }
237             //Collect the bounding box's corners so we can snap to them
238             if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
239                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
240                 // of the item AND the bbox of the clipping path at the same time
241                 if (!(*i).clip_or_mask) {
242                     Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
243                     getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
244                 }
245             }
246         }
247     }
250 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
251                                          Inkscape::SnapPreferences::PointType const &t,
252                                          Inkscape::SnapCandidatePoint const &p,
253                                          std::vector<SnapCandidatePoint> *unselected_nodes) const
255     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
257     _collectNodes(t, p.getSourceNum() == 0);
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<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
267         Geom::Coord dist = Geom::L2((*k).getPoint() - p.getPoint());
268         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
269             s = SnappedPoint((*k).getPoint(), p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, (*k).getTargetBBox());
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     // Although we won't snap to paths here (which would give us under constrained snaps) we can still snap to intersections of paths.
288     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
289         _collectPaths(t, true);
290         _snapPaths(sc, t, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
291         // The paths themselves should be discarded in findBestSnap(), as we should only snap to their intersections
292     }
294     SnappedPoint s;
296     Geom::Coord tol = getSnapperTolerance();
298     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
299         // Project each node (*k) on the guide line (running through point p)
300         Geom::Point p_proj = Geom::projection((*k).getPoint(), Geom::Line(p, p + Geom::rot90(guide_normal)));
301         Geom::Coord dist = Geom::L2((*k).getPoint() - p_proj); // distance from node to the guide
302         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
303         if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
304             s = SnappedPoint((*k).getPoint(), SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), true, (*k).getTargetBBox());
305             sc.points.push_back(s);
306         }
307     }
311 /**
312  * Returns index of first NR_END bpath in array.
313  */
315 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapPreferences::PointType const &t,
316                                          bool const &first_point) const
318     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
319     // e.g. when translating an item using the selector tool, then we will only do this for the
320     // first point and store the collection for later use. This significantly improves the performance
321     if (first_point) {
322         _clear_paths();
324         // Determine the type of bounding box we should snap to
325         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
327         bool p_is_a_node = t & Inkscape::SnapPreferences::SNAPPOINT_NODE;
328         bool p_is_other = t & Inkscape::SnapPreferences::SNAPPOINT_OTHER;
330         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
331             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
332             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
333             bbox_type = !prefs_bbox ?
334                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
335         }
337         // Consider the page border for snapping
338         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
339             Geom::PathVector *border_path = _getBorderPathv();
340             if (border_path != NULL) {
341                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
342             }
343         }
345         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
347             /* Transform the requested snap point to this item's coordinates */
348             Geom::Matrix i2doc(Geom::identity());
349             SPItem *root_item = NULL;
350             /* We might have a clone at hand, so make sure we get the root item */
351             if (SP_IS_USE((*i).item)) {
352                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
353                 root_item = sp_use_root(SP_USE((*i).item));
354                 g_return_if_fail(root_item);
355             } else {
356                 i2doc = sp_item_i2doc_affine((*i).item);
357                 root_item = (*i).item;
358             }
360             //Build a list of all paths considered for snapping to
362             //Add the item's path to snap to
363             if (_snapmanager->snapprefs.getSnapToItemPath()) {
364                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
365                     // Snapping to the path of characters is very cool, but for a large
366                     // chunk of text this will take ages! So limit snapping to text paths
367                     // containing max. 240 characters. Snapping the bbox will not be affected
368                     bool very_lenghty_prose = false;
369                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
370                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
371                     }
372                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
373                     // which corresponds to a lag of 500 msec. This is for snapping a rect
374                     // to a single line of text.
376                     // Snapping for example to a traced bitmap is also very stressing for
377                     // the CPU, so we'll only snap to paths having no more than 500 nodes
378                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
379                     bool very_complex_path = false;
380                     if (SP_IS_PATH(root_item)) {
381                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
382                     }
384                     if (!very_lenghty_prose && !very_complex_path) {
385                         SPCurve *curve = curve_for_item(root_item);
386                         if (curve) {
387                             // We will get our own copy of the path, which must be freed at some point
388                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
389                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(borderpathv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
390                             curve->unref();
391                         }
392                     }
393                 }
394             }
396             //Add the item's bounding box to snap to
397             if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
398                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
399                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
400                     // of the item AND the bbox of the clipping path at the same time
401                     if (!(*i).clip_or_mask) {
402                         Geom::OptRect rect;
403                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
404                         if (rect) {
405                             Geom::PathVector *path = _getPathvFromRect(*rect);
406                             rect = sp_item_bbox_desktop(root_item, bbox_type);
407                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
408                         }
409                     }
410                 }
411             }
412         }
413     }
416 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
417                                      Inkscape::SnapPreferences::PointType const &t,
418                                      Inkscape::SnapCandidatePoint const &p,
419                                      std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
420                                      SPPath const *selected_path) const
422     _collectPaths(t, p.getSourceNum() == 0);
423     // Now we can finally do the real snapping, using the paths collected above
425     g_assert(_snapmanager->getDesktop() != NULL);
426     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
428     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
430     if (p.getSourceNum() == 0) {
431         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
432          * currently being edited, because that path requires special care: when snapping to nodes
433          * only the unselected nodes of that path should be considered, and these will be passed on separately.
434          * This path must not be ignored however when snapping to the paths, so we add it here
435          * manually when applicable.
436          * */
437         if (node_tool_active) {
438             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
439             if (curve) {
440                 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
441                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
442                 curve->unref();
443             }
444         }
445     }
447     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
448         bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
449         //if true then this pathvector it_pv is currently being edited in the node tool
451         for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
452             // Find a nearest point for each curve within this path
453             // n curves will return n time values with 0 <= t <= 1
454             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
456             std::vector<double>::const_iterator np = anp.begin();
457             unsigned int index = 0;
458             for (; np != anp.end(); np++, index++) {
459                 Geom::Curve const *curve = &((*it_pv).at_index(index));
460                 Geom::Point const sp_doc = curve->pointAt(*np);
462                 bool c1 = true;
463                 bool c2 = true;
464                 if (being_edited) {
465                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
466                      * and not to the pieces that are being dragged around. This way we avoid
467                      * self-snapping. For this we check whether the nodes at both ends of the current
468                      * piece are unselected; if they are then this piece must be stationary
469                      */
470                     g_assert(unselected_nodes != NULL);
471                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
472                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
473                     c1 = isUnselectedNode(start_pt, unselected_nodes);
474                     c2 = isUnselectedNode(end_pt, unselected_nodes);
475                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
476                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
477                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
478                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
479                      *   should be in the exact same order for both classes, so we can index them
480                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
481                      */
482                 }
484                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
485                 if (!being_edited || (c1 && c2)) {
486                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
487                     if (dist < getSnapperTolerance()) {
488                         sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, p.getSourceType(), p.getSourceNum(), it_p->target_type, it_p->target_bbox));
489                     }
490                 }
491             }
492         } // End of: for (Geom::PathVector::iterator ....)
493     }
496 /* Returns true if point is coincident with one of the unselected nodes */
497 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
499     if (unselected_nodes == NULL) {
500         return false;
501     }
503     if (unselected_nodes->size() == 0) {
504         return false;
505     }
507     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
508         if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
509             return true;
510         }
511     }
513     return false;
516 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
517                                      Inkscape::SnapPreferences::PointType const &t,
518                                      Inkscape::SnapCandidatePoint const &p,
519                                      ConstraintLine const &c) const
522     _collectPaths(t, p.getSourceNum() == 0);
524     // Now we can finally do the real snapping, using the paths collected above
526     g_assert(_snapmanager->getDesktop() != NULL);
527     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
529     Geom::Point direction_vector = c.getDirection();
530     if (!is_zero(direction_vector)) {
531         direction_vector = Geom::unit_vector(direction_vector);
532     }
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 = p.getPoint(); // projection has already been taken care of in constrainedSnap in the snapmanager;
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<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
548         if (k->path_vector) {
549             Geom::CrossingSet cs = Geom::crossings(clv, *(k->path_vector));
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->first
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), p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);
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                                             Inkscape::SnapCandidatePoint const &p,
573                                             Geom::OptRect const &bbox_to_snap,
574                                             std::vector<SPItem const *> const *it,
575                                             std::vector<SnapCandidatePoint> *unselected_nodes) const
577     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false ) {
578         return;
579     }
581     /* Get a list of all the SPItems that we will try to snap to */
582     if (p.getSourceNum() == 0) {
583         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
584         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
585     }
587     if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
588         || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
589         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
590         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
591         || _snapmanager->snapprefs.getIncludeItemCenter()) {
592         _snapNodes(sc, t, p, unselected_nodes);
593     }
595     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
596         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
597         if (n > 0) {
598             /* While editing a path in the node tool, findCandidates must ignore that path because
599              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
600              * That path must not be ignored however when snapping to the paths, so we add it here
601              * manually when applicable
602              */
603             SPPath *path = NULL;
604             if (it != NULL) {
605                 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
606                     path = SP_PATH(*it->begin());
607                 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
608                 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
609             }
610             _snapPaths(sc, t, p, unselected_nodes, path);
611         } else {
612             _snapPaths(sc, t, p, NULL, NULL);
613         }
614     }
617 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
618                                                   Inkscape::SnapPreferences::PointType const &t,
619                                                   Inkscape::SnapCandidatePoint const &p,
620                                                   Geom::OptRect const &bbox_to_snap,
621                                                   ConstraintLine const &c,
622                                                   std::vector<SPItem const *> const *it) const
624     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(t) == false) {
625         return;
626     }
628     /* Get a list of all the SPItems that we will try to snap to */
629     if (p.getSourceNum() == 0) {
630         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
631         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
632     }
634     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
635     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
636     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
638     // When snapping to objects, we either snap to their nodes or their paths. It is however very
639     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
640     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
641     // so we will more or less snap to them anyhow.
643     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
644         _snapPathsConstrained(sc, t, p, c);
645     }
649 // This method is used to snap a guide to nodes, while dragging the guide around
650 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
651                                         Geom::Point const &p,
652                                         Geom::Point const &guide_normal) const
654     /* Get a list of all the SPItems that we will try to snap to */
655     std::vector<SPItem*> cand;
656     std::vector<SPItem const *> const it; //just an empty list
658     DimensionToSnap snap_dim;
659     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
660         snap_dim = GUIDE_TRANSL_SNAP_Y;
661     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
662         snap_dim = GUIDE_TRANSL_SNAP_X;
663     } else {
664         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
665     }
667     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
668     _snapTranslatingGuideToNodes(sc, Inkscape::SnapPreferences::SNAPPOINT_OTHER, p, guide_normal);
672 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
673 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
674                                         Geom::Point const &p,
675                                         Geom::Point const &guide_normal,
676                                         ConstraintLine const &/*c*/) const
678     /* Get a list of all the SPItems that we will try to snap to */
679     std::vector<SPItem*> cand;
680     std::vector<SPItem const *> const it; //just an empty list
682     DimensionToSnap snap_dim;
683     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
684         snap_dim = GUIDE_TRANSL_SNAP_Y;
685     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
686         snap_dim = GUIDE_TRANSL_SNAP_X;
687     } else {
688         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
689     }
691     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
692     _snapTranslatingGuideToNodes(sc, Inkscape::SnapPreferences::SNAPPOINT_OTHER, p, guide_normal);
696 /**
697  *  \return true if this Snapper will snap at least one kind of point.
698  */
699 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
701     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
702                         || _snapmanager->snapprefs.getSnapToItemNode()
703                         || _snapmanager->snapprefs.getSnapToBBoxPath()
704                         || _snapmanager->snapprefs.getSnapToBBoxNode()
705                         || _snapmanager->snapprefs.getSnapToPageBorder()
706                         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
707                         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
708                         || _snapmanager->snapprefs.getIncludeItemCenter();
710     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
713 bool Inkscape::ObjectSnapper::GuidesMightSnap() const // almost the same as ThisSnapperMightSnap above, but only looking at points (and not paths)
715     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode()
716                         || _snapmanager->snapprefs.getSnapToPageBorder()
717                         || (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxNode())
718                         || (_snapmanager->snapprefs.getSnapModeBBox() && (_snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()))
719                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()))
720                         || (_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getIncludeItemCenter())
721                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapIntersectionCS()));
723     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
726 void Inkscape::ObjectSnapper::_clear_paths() const
728     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
729         g_free(k->path_vector);
730     }
731     _paths_to_snap_to->clear();
734 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
736     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
737     return _getPathvFromRect(border_rect);
740 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
742     SPCurve const *border_curve = SPCurve::new_from_rect(rect);
743     if (border_curve) {
744         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
745         return dummy;
746     } else {
747         return NULL;
748     }
751 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
753     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
754     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
755     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
756     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
757     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
758     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
761 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
762                              std::vector<SnapCandidatePoint> *points,
763                              bool const /*isTarget*/,
764                              bool const includeCorners,
765                              bool const includeLineMidpoints,
766                              bool const includeObjectMidpoints)
768     if (bbox) {
769         // collect the corners of the bounding box
770         for ( unsigned k = 0 ; k < 4 ; k++ ) {
771             if (includeCorners) {
772                 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, 0, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
773             }
774             // optionally, collect the midpoints of the bounding box's edges too
775             if (includeLineMidpoints) {
776                 points->push_back(Inkscape::SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox));
777             }
778         }
779         if (includeObjectMidpoints) {
780             points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
781         }
782     }
785 /*
786   Local Variables:
787   mode:c++
788   c-file-style:"stroustrup"
789   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
790   indent-tabs-mode:nil
791   fill-column:99
792   End:
793 */
794 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :