Code

fix Launchpad bug 593023: crash in constrained snap due to not calling setup() before...
[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 (_snapmanager->getDesktop() == NULL) {
95         g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
96         // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
97     }
100     if (first_point) {
101         _candidates->clear();
102     }
104     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
105     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
107     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
108         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
109             // Snapping to items in a locked layer is allowed
110             // Don't snap to hidden objects, unless they're a clipped path or a mask
111             /* See if this item is on the ignore list */
112             std::vector<SPItem const *>::const_iterator i;
113             if (it != NULL) {
114                 i = it->begin();
115                 while (i != it->end() && *i != o) {
116                     i++;
117                 }
118             }
120             if (it == NULL || i == it->end()) {
121                 SPItem *item = SP_ITEM(o);
122                 if (item) {
123                     SPObject *obj = NULL;
124                     if (!clip_or_mask) { // cannot clip or mask more than once
125                         // The current item is not a clipping path or a mask, but might
126                         // still be the subject of clipping or masking itself ; if so, then
127                         // we should also consider that path or mask for snapping to
128                         obj = SP_OBJECT(item->clip_ref->getObject());
129                         if (obj) {
130                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
131                         }
132                         obj = SP_OBJECT(item->mask_ref->getObject());
133                         if (obj) {
134                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
135                         }
136                     }
137                 }
139                 if (SP_IS_GROUP(o)) {
140                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
141                 } else {
142                     Geom::OptRect bbox_of_item = Geom::Rect();
143                     if (clip_or_mask) {
144                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
145                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
146                         sp_item_invoke_bbox(item,
147                             bbox_of_item,
148                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
149                             true);
150                     } else {
151                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
152                     }
153                     if (bbox_of_item) {
154                         // See if the item is within range
155                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
156                             // This item is within snapping range, so record it as a candidate
157                             _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
158                             // For debugging: print the id of the candidate to the console
159                             // SPObject *obj = (SPObject*)item;
160                             // std::cout << "Snap candidate added: " << obj->getId() << std::endl;
161                         }
162                     }
163                 }
164             }
165         }
166     }
170 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
171                                             bool const &first_point) const
173     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
174     // e.g. when translating an item using the selector tool, then we will only do this for the
175     // first point and store the collection for later use. This significantly improves the performance
176     if (first_point) {
177         _points_to_snap_to->clear();
179          // Determine the type of bounding box we should snap to
180         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
182         bool p_is_a_node = t & Inkscape::SNAPSOURCE_NODE_CATEGORY;
183         bool p_is_a_bbox = t & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
184         bool p_is_other = t & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
186         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
187         g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
189         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
190             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
191             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
192             bbox_type = !prefs_bbox ?
193                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
194         }
196         // Consider the page border for snapping to
197         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
198             _getBorderNodes(_points_to_snap_to);
199         }
201         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
202             //Geom::Matrix i2doc(Geom::identity());
203             SPItem *root_item = (*i).item;
204             if (SP_IS_USE((*i).item)) {
205                 root_item = sp_use_root(SP_USE((*i).item));
206             }
207             g_return_if_fail(root_item);
209             //Collect all nodes so we can snap to them
210             if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
211                 // Note: there are two ways in which intersections are considered:
212                 // Method 1: Intersections are calculated for each shape individually, for both the
213                 //           snap source and snap target (see sp_shape_snappoints)
214                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
215                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
216                 // Some differences:
217                 // - Method 1 doesn't find intersections within a set of multiple objects
218                 // - Method 2 only works for targets
219                 // When considering intersections as snap targets:
220                 // - Method 1 only works when snapping to nodes, whereas
221                 // - Method 2 only works when snapping to paths
222                 // - There will be performance differences too!
223                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
225                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
226                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
227                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
228                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
229                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
230                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
231                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
232                     _snapmanager->snapprefs.setSnapIntersectionCS(false);
233                 }
235                 sp_item_snappoints(root_item, *_points_to_snap_to, &_snapmanager->snapprefs);
237                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
238                     _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
239                 }
240             }
242             //Collect the bounding box's corners so we can snap to them
243             if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
244                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
245                 // of the item AND the bbox of the clipping path at the same time
246                 if (!(*i).clip_or_mask) {
247                     Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
248                     getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
249                 }
250             }
251         }
252     }
255 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
256                                          Inkscape::SnapCandidatePoint const &p,
257                                          std::vector<SnapCandidatePoint> *unselected_nodes) const
259     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
261     _collectNodes(p.getSourceType(), p.getSourceNum() == 0);
263     if (unselected_nodes != NULL) {
264         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
265     }
267     SnappedPoint s;
268     bool success = false;
270     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
271         Geom::Coord dist = Geom::L2((*k).getPoint() - p.getPoint());
272         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
273             s = SnappedPoint((*k).getPoint(), p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
274             success = true;
275         }
276     }
278     if (success) {
279         sc.points.push_back(s);
280     }
283 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
284                                          Geom::Point const &p,
285                                          Geom::Point const &guide_normal) const
287     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
288     _collectNodes(SNAPSOURCE_GUIDE, true);
290     // Although we won't snap to paths here (which would give us under constrained snaps) we can still snap to intersections of paths.
291     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
292         _collectPaths(Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), true);
293         _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
294         // The paths themselves should be discarded in findBestSnap(), as we should only snap to their intersections
295     }
297     SnappedPoint s;
299     Geom::Coord tol = getSnapperTolerance();
301     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
302         // Project each node (*k) on the guide line (running through point p)
303         Geom::Point p_proj = Geom::projection((*k).getPoint(), Geom::Line(p, p + Geom::rot90(guide_normal)));
304         Geom::Coord dist = Geom::L2((*k).getPoint() - p_proj); // distance from node to the guide
305         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
306         if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
307             s = SnappedPoint((*k).getPoint(), SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
308             sc.points.push_back(s);
309         }
310     }
314 /**
315  * Returns index of first NR_END bpath in array.
316  */
318 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &p,
319                                          bool const &first_point) const
321     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
322     // e.g. when translating an item using the selector tool, then we will only do this for the
323     // first point and store the collection for later use. This significantly improves the performance
324     if (first_point) {
325         _clear_paths();
327         // Determine the type of bounding box we should snap to
328         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
330         bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
331         bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
333         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
334             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
335             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
336             bbox_type = !prefs_bbox ?
337                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
338         }
340         // Consider the page border for snapping
341         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
342             Geom::PathVector *border_path = _getBorderPathv();
343             if (border_path != NULL) {
344                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
345             }
346         }
348         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
350             /* Transform the requested snap point to this item's coordinates */
351             Geom::Matrix i2doc(Geom::identity());
352             SPItem *root_item = NULL;
353             /* We might have a clone at hand, so make sure we get the root item */
354             if (SP_IS_USE((*i).item)) {
355                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
356                 root_item = sp_use_root(SP_USE((*i).item));
357                 g_return_if_fail(root_item);
358             } else {
359                 i2doc = sp_item_i2doc_affine((*i).item);
360                 root_item = (*i).item;
361             }
363             //Build a list of all paths considered for snapping to
365             //Add the item's path to snap to
366             if (_snapmanager->snapprefs.getSnapToItemPath()) {
367                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
368                     // Snapping to the path of characters is very cool, but for a large
369                     // chunk of text this will take ages! So limit snapping to text paths
370                     // containing max. 240 characters. Snapping the bbox will not be affected
371                     bool very_lenghty_prose = false;
372                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
373                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
374                     }
375                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
376                     // which corresponds to a lag of 500 msec. This is for snapping a rect
377                     // to a single line of text.
379                     // Snapping for example to a traced bitmap is also very stressing for
380                     // the CPU, so we'll only snap to paths having no more than 500 nodes
381                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
382                     bool very_complex_path = false;
383                     if (SP_IS_PATH(root_item)) {
384                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
385                     }
387                     if (!very_lenghty_prose && !very_complex_path) {
388                         SPCurve *curve = curve_for_item(root_item);
389                         if (curve) {
390                             // We will get our own copy of the path, which must be freed at some point
391                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
392                             _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.
393                             curve->unref();
394                         }
395                     }
396                 }
397             }
399             //Add the item's bounding box to snap to
400             if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
401                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
402                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
403                     // of the item AND the bbox of the clipping path at the same time
404                     if (!(*i).clip_or_mask) {
405                         Geom::OptRect rect;
406                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
407                         if (rect) {
408                             Geom::PathVector *path = _getPathvFromRect(*rect);
409                             rect = sp_item_bbox_desktop(root_item, bbox_type);
410                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
411                         }
412                     }
413                 }
414             }
415         }
416     }
419 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
420                                      Inkscape::SnapCandidatePoint const &p,
421                                      std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
422                                      SPPath const *selected_path) const
424     _collectPaths(p, p.getSourceNum() == 0);
425     // Now we can finally do the real snapping, using the paths collected above
427     g_assert(_snapmanager->getDesktop() != NULL);
428     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
430     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
432     if (p.getSourceNum() == 0) {
433         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
434          * currently being edited, because that path requires special care: when snapping to nodes
435          * only the unselected nodes of that path should be considered, and these will be passed on separately.
436          * This path must not be ignored however when snapping to the paths, so we add it here
437          * manually when applicable.
438          * */
439         if (node_tool_active) {
440             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
441             if (curve) {
442                 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
443                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
444                 curve->unref();
445             }
446         }
447     }
449     int num_path = 0;
450     int num_segm = 0;
452     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
453         bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
454         //if true then this pathvector it_pv is currently being edited in the node tool
456         for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
457             // Find a nearest point for each curve within this path
458             // n curves will return n time values with 0 <= t <= 1
459             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
461             std::vector<double>::const_iterator np = anp.begin();
462             unsigned int index = 0;
463             for (; np != anp.end(); np++, index++) {
464                 Geom::Curve const *curve = &((*it_pv).at_index(index));
465                 Geom::Point const sp_doc = curve->pointAt(*np);
467                 bool c1 = true;
468                 bool c2 = true;
469                 if (being_edited) {
470                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
471                      * and not to the pieces that are being dragged around. This way we avoid
472                      * self-snapping. For this we check whether the nodes at both ends of the current
473                      * piece are unselected; if they are then this piece must be stationary
474                      */
475                     g_assert(unselected_nodes != NULL);
476                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
477                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
478                     c1 = isUnselectedNode(start_pt, unselected_nodes);
479                     c2 = isUnselectedNode(end_pt, unselected_nodes);
480                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
481                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
482                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
483                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
484                      *   should be in the exact same order for both classes, so we can index them
485                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
486                      */
487                 }
489                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
490                 if (!being_edited || (c1 && c2)) {
491                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
492                     if (dist < getSnapperTolerance()) {
493                         sc.curves.push_back(Inkscape::SnappedCurve(sp_dt, num_path, num_segm, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, curve, p.getSourceType(), p.getSourceNum(), it_p->target_type, it_p->target_bbox));
494                     }
495                 }
496             }
497             num_segm++;
498         } // End of: for (Geom::PathVector::iterator ....)
499         num_path++;
500     }
503 /* Returns true if point is coincident with one of the unselected nodes */
504 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
506     if (unselected_nodes == NULL) {
507         return false;
508     }
510     if (unselected_nodes->size() == 0) {
511         return false;
512     }
514     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
515         if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
516             return true;
517         }
518     }
520     return false;
523 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
524                                      Inkscape::SnapCandidatePoint const &p,
525                                      ConstraintLine const &c) const
528     _collectPaths(p, p.getSourceNum() == 0);
530     // Now we can finally do the real snapping, using the paths collected above
532     g_assert(_snapmanager->getDesktop() != NULL);
533     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
535     Geom::Point direction_vector = c.getDirection();
536     if (!is_zero(direction_vector)) {
537         direction_vector = Geom::unit_vector(direction_vector);
538     }
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 = p.getPoint(); // projection has already been taken care of in constrainedSnap in the snapmanager;
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<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
554         if (k->path_vector) {
555             Geom::CrossingSet cs = Geom::crossings(clv, *(k->path_vector));
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->first
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), p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);
567                         sc.points.push_back(s);
568                     }
569                 }
570             }
571         }
572     }
576 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
577                                             Inkscape::SnapCandidatePoint const &p,
578                                             Geom::OptRect const &bbox_to_snap,
579                                             std::vector<SPItem const *> const *it,
580                                             std::vector<SnapCandidatePoint> *unselected_nodes) const
582     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false ) {
583         return;
584     }
586     /* Get a list of all the SPItems that we will try to snap to */
587     if (p.getSourceNum() == 0) {
588         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
589         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
590     }
592     if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
593         || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
594         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
595         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
596         || _snapmanager->snapprefs.getIncludeItemCenter()) {
597         _snapNodes(sc, p, unselected_nodes);
598     }
600     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
601         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
602         if (n > 0) {
603             /* While editing a path in the node tool, findCandidates must ignore that path because
604              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
605              * That path must not be ignored however when snapping to the paths, so we add it here
606              * manually when applicable
607              */
608             SPPath *path = NULL;
609             if (it != NULL) {
610                 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
611                     path = SP_PATH(*it->begin());
612                 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
613                 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
614             }
615             _snapPaths(sc, p, unselected_nodes, path);
616         } else {
617             _snapPaths(sc, p, NULL, NULL);
618         }
619     }
622 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
623                                                   Inkscape::SnapCandidatePoint const &p,
624                                                   Geom::OptRect const &bbox_to_snap,
625                                                   ConstraintLine const &c,
626                                                   std::vector<SPItem const *> const *it) const
628     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
629         return;
630     }
632     /* Get a list of all the SPItems that we will try to snap to */
633     if (p.getSourceNum() == 0) {
634         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
635         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
636     }
638     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
639     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
640     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
642     // When snapping to objects, we either snap to their nodes or their paths. It is however very
643     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
644     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
645     // so we will more or less snap to them anyhow.
647     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
648         _snapPathsConstrained(sc, p, c);
649     }
653 // This method is used to snap a guide to nodes, while dragging the guide around
654 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
655                                         Geom::Point const &p,
656                                         Geom::Point const &guide_normal) const
658     /* Get a list of all the SPItems that we will try to snap to */
659     std::vector<SPItem*> cand;
660     std::vector<SPItem const *> const it; //just an empty list
662     DimensionToSnap snap_dim;
663     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
664         snap_dim = GUIDE_TRANSL_SNAP_Y;
665     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
666         snap_dim = GUIDE_TRANSL_SNAP_X;
667     } else {
668         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
669     }
671     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
672     _snapTranslatingGuideToNodes(sc, p, guide_normal);
676 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
677 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
678                                         Geom::Point const &p,
679                                         Geom::Point const &guide_normal,
680                                         ConstraintLine const &/*c*/) const
682     /* Get a list of all the SPItems that we will try to snap to */
683     std::vector<SPItem*> cand;
684     std::vector<SPItem const *> const it; //just an empty list
686     DimensionToSnap snap_dim;
687     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
688         snap_dim = GUIDE_TRANSL_SNAP_Y;
689     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
690         snap_dim = GUIDE_TRANSL_SNAP_X;
691     } else {
692         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
693     }
695     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
696     _snapTranslatingGuideToNodes(sc, p, guide_normal);
700 /**
701  *  \return true if this Snapper will snap at least one kind of point.
702  */
703 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
705     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
706                         || _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
707                         || _snapmanager->snapprefs.getSnapToBBoxPath()
708                         || _snapmanager->snapprefs.getSnapToBBoxNode()
709                         || _snapmanager->snapprefs.getSnapToPageBorder()
710                         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
711                         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
712                         || _snapmanager->snapprefs.getIncludeItemCenter();
714     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
717 bool Inkscape::ObjectSnapper::GuidesMightSnap() const // almost the same as ThisSnapperMightSnap above, but only looking at points (and not paths)
719     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
720                         || _snapmanager->snapprefs.getSnapToPageBorder()
721                         || (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxNode())
722                         || (_snapmanager->snapprefs.getSnapModeBBox() && (_snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()))
723                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()))
724                         || (_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getIncludeItemCenter())
725                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapIntersectionCS()));
727     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
730 void Inkscape::ObjectSnapper::_clear_paths() const
732     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
733         delete k->path_vector;
734     }
735     _paths_to_snap_to->clear();
738 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
740     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
741     return _getPathvFromRect(border_rect);
744 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
746     SPCurve const *border_curve = SPCurve::new_from_rect(rect, true);
747     if (border_curve) {
748         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
749         return dummy;
750     } else {
751         return NULL;
752     }
755 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
757     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
758     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
759     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
760     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
761     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
762     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
765 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
766                              std::vector<SnapCandidatePoint> *points,
767                              bool const /*isTarget*/,
768                              bool const includeCorners,
769                              bool const includeLineMidpoints,
770                              bool const includeObjectMidpoints)
772     if (bbox) {
773         // collect the corners of the bounding box
774         for ( unsigned k = 0 ; k < 4 ; k++ ) {
775             if (includeCorners) {
776                 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, 0, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
777             }
778             // optionally, collect the midpoints of the bounding box's edges too
779             if (includeLineMidpoints) {
780                 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));
781             }
782         }
783         if (includeObjectMidpoints) {
784             points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
785         }
786     }
789 /*
790   Local Variables:
791   mode:c++
792   c-file-style:"stroustrup"
793   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
794   indent-tabs-mode:nil
795   fill-column:99
796   End:
797 */
798 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :