Code

- Snap while rotating an object using the selector tool
[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 <2geom/circle.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::ObjectSnapper::ObjectSnapper(SnapManager *sm, Geom::Coord const d)
38     : Snapper(sm, d)
39 {
40     _candidates = new std::vector<SnapCandidateItem>;
41     _points_to_snap_to = new std::vector<Inkscape::SnapCandidatePoint>;
42     _paths_to_snap_to = new std::vector<Inkscape::SnapCandidatePath >;
43 }
45 Inkscape::ObjectSnapper::~ObjectSnapper()
46 {
47     _candidates->clear();
48     delete _candidates;
50     _points_to_snap_to->clear();
51     delete _points_to_snap_to;
53     _clear_paths();
54     delete _paths_to_snap_to;
55 }
57 /**
58  *  \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
59  */
60 Geom::Coord Inkscape::ObjectSnapper::getSnapperTolerance() const
61 {
62     SPDesktop const *dt = _snapmanager->getDesktop();
63     double const zoom =  dt ? dt->current_zoom() : 1;
64     return _snapmanager->snapprefs.getObjectTolerance() / zoom;
65 }
67 bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
68 {
69     return _snapmanager->snapprefs.getObjectTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
70 }
72 /**
73  *  Find all items within snapping range.
74  *  \param parent Pointer to the document's root, or to a clipped path or mask object
75  *  \param it List of items to ignore
76  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
77  *  \param DimensionToSnap Snap in X, Y, or both directions.
78  */
80 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
81                                               std::vector<SPItem const *> const *it,
82                                               bool const &first_point,
83                                               Geom::Rect const &bbox_to_snap,
84                                               DimensionToSnap const snap_dim,
85                                               bool const clip_or_mask,
86                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
87 {
88     bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
89     bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
91     if (!(c1 || c2)) {
92         return;
93     }
95     if (_snapmanager->getDesktop() == NULL) {
96         g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
97         // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
98     }
101     if (first_point) {
102         _candidates->clear();
103     }
105     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
106     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
108     for (SPObject* o = sp_object_first_child(parent); o != NULL; o = SP_OBJECT_NEXT(o)) {
109         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
110             // Snapping to items in a locked layer is allowed
111             // Don't snap to hidden objects, unless they're a clipped path or a mask
112             /* See if this item is on the ignore list */
113             std::vector<SPItem const *>::const_iterator i;
114             if (it != NULL) {
115                 i = it->begin();
116                 while (i != it->end() && *i != o) {
117                     i++;
118                 }
119             }
121             if (it == NULL || i == it->end()) {
122                 SPItem *item = SP_ITEM(o);
123                 if (item) {
124                     SPObject *obj = NULL;
125                     if (!clip_or_mask) { // cannot clip or mask more than once
126                         // The current item is not a clipping path or a mask, but might
127                         // still be the subject of clipping or masking itself ; if so, then
128                         // we should also consider that path or mask for snapping to
129                         obj = SP_OBJECT(item->clip_ref->getObject());
130                         if (obj) {
131                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
132                         }
133                         obj = SP_OBJECT(item->mask_ref->getObject());
134                         if (obj) {
135                             _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, sp_item_i2doc_affine(item));
136                         }
137                     }
138                 }
140                 if (SP_IS_GROUP(o)) {
141                     _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
142                 } else {
143                     Geom::OptRect bbox_of_item = Geom::Rect();
144                     if (clip_or_mask) {
145                         // Oh oh, this will get ugly. We cannot use sp_item_i2d_affine directly because we need to
146                         // insert an additional transformation in document coordinates (code copied from sp_item_i2d_affine)
147                         sp_item_invoke_bbox(item,
148                             bbox_of_item,
149                             sp_item_i2doc_affine(item) * additional_affine * _snapmanager->getDesktop()->doc2dt(),
150                             true);
151                     } else {
152                         sp_item_invoke_bbox(item, bbox_of_item, sp_item_i2d_affine(item), true);
153                     }
154                     if (bbox_of_item) {
155                         // See if the item is within range
156                         if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
157                             // This item is within snapping range, so record it as a candidate
158                             _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
159                             // For debugging: print the id of the candidate to the console
160                             // SPObject *obj = (SPObject*)item;
161                             // std::cout << "Snap candidate added: " << obj->getId() << std::endl;
162                         }
163                     }
164                 }
165             }
166         }
167     }
171 void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
172                                             bool const &first_point) const
174     // Now, let's first collect all points to snap to. If we have a whole bunch of points to snap,
175     // e.g. when translating an item using the selector tool, then we will only do this for the
176     // first point and store the collection for later use. This significantly improves the performance
177     if (first_point) {
178         _points_to_snap_to->clear();
180          // Determine the type of bounding box we should snap to
181         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
183         bool p_is_a_node = t & Inkscape::SNAPSOURCE_NODE_CATEGORY;
184         bool p_is_a_bbox = t & Inkscape::SNAPSOURCE_BBOX_CATEGORY;
185         bool p_is_other = t & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
187         // A point considered for snapping should be either a node, a bbox corner or a guide. Pick only ONE!
188         g_assert(!((p_is_a_node && p_is_a_bbox) || (p_is_a_bbox && p_is_other) || (p_is_a_node && p_is_other)));
190         if (_snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()) {
191             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
192             bool prefs_bbox = prefs->getBool("/tools/bounding_box");
193             bbox_type = !prefs_bbox ?
194                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
195         }
197         // Consider the page border for snapping to
198         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
199             _getBorderNodes(_points_to_snap_to);
200         }
202         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
203             //Geom::Matrix i2doc(Geom::identity());
204             SPItem *root_item = (*i).item;
205             if (SP_IS_USE((*i).item)) {
206                 root_item = sp_use_root(SP_USE((*i).item));
207             }
208             g_return_if_fail(root_item);
210             //Collect all nodes so we can snap to them
211             if (p_is_a_node || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node) || p_is_other) {
212                 // Note: there are two ways in which intersections are considered:
213                 // Method 1: Intersections are calculated for each shape individually, for both the
214                 //           snap source and snap target (see sp_shape_snappoints)
215                 // Method 2: Intersections are calculated for each curve or line that we've snapped to, i.e. only for
216                 //           the target (see the intersect() method in the SnappedCurve and SnappedLine classes)
217                 // Some differences:
218                 // - Method 1 doesn't find intersections within a set of multiple objects
219                 // - Method 2 only works for targets
220                 // When considering intersections as snap targets:
221                 // - Method 1 only works when snapping to nodes, whereas
222                 // - Method 2 only works when snapping to paths
223                 // - There will be performance differences too!
224                 // If both methods are being used simultaneously, then this might lead to duplicate targets!
226                 // Well, here we will be looking for snap TARGETS. Both methods can therefore be used.
227                 // When snapping to paths, we will get a collection of snapped lines and snapped curves. findBestSnap() will
228                 // go hunting for intersections (but only when asked to in the prefs of course). In that case we can just
229                 // temporarily block the intersections in sp_item_snappoints, we don't need duplicates. If we're not snapping to
230                 // paths though but only to item nodes then we should still look for the intersections in sp_item_snappoints()
231                 bool old_pref = _snapmanager->snapprefs.getSnapIntersectionCS();
232                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
233                     _snapmanager->snapprefs.setSnapIntersectionCS(false);
234                 }
236                 sp_item_snappoints(root_item, *_points_to_snap_to, &_snapmanager->snapprefs);
238                 if (_snapmanager->snapprefs.getSnapToItemPath()) {
239                     _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
240                 }
241             }
243             //Collect the bounding box's corners so we can snap to them
244             if (p_is_a_bbox || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_bbox) || p_is_other) {
245                 // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
246                 // of the item AND the bbox of the clipping path at the same time
247                 if (!(*i).clip_or_mask) {
248                     Geom::OptRect b = sp_item_bbox_desktop(root_item, bbox_type);
249                     getBBoxPoints(b, _points_to_snap_to, true, _snapmanager->snapprefs.getSnapToBBoxNode(), _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints(), _snapmanager->snapprefs.getSnapBBoxMidpoints());
250                 }
251             }
252         }
253     }
256 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
257                                          Inkscape::SnapCandidatePoint const &p,
258                                          std::vector<SnapCandidatePoint> *unselected_nodes) const
260     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
262     _collectNodes(p.getSourceType(), p.getSourceNum() == 0);
264     if (unselected_nodes != NULL) {
265         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
266     }
268     SnappedPoint s;
269     bool success = false;
271     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
272         Geom::Coord dist = Geom::L2((*k).getPoint() - p.getPoint());
273         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
274             s = SnappedPoint((*k).getPoint(), p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
275             success = true;
276         }
277     }
279     if (success) {
280         sc.points.push_back(s);
281     }
284 void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
285                                          Geom::Point const &p,
286                                          Geom::Point const &guide_normal) const
288     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
289     _collectNodes(SNAPSOURCE_GUIDE, true);
291     // Although we won't snap to paths here (which would give us under constrained snaps) we can still snap to intersections of paths.
292     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
293         _collectPaths(Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), true);
294         _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
295         // The paths themselves should be discarded in findBestSnap(), as we should only snap to their intersections
296     }
298     SnappedPoint s;
300     Geom::Coord tol = getSnapperTolerance();
302     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
303         // Project each node (*k) on the guide line (running through point p)
304         Geom::Point p_proj = Geom::projection((*k).getPoint(), Geom::Line(p, p + Geom::rot90(guide_normal)));
305         Geom::Coord dist = Geom::L2((*k).getPoint() - p_proj); // distance from node to the guide
306         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
307         if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
308             s = SnappedPoint((*k).getPoint(), SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
309             sc.points.push_back(s);
310         }
311     }
315 /**
316  * Returns index of first NR_END bpath in array.
317  */
319 void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &p,
320                                          bool const &first_point) const
322     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
323     // e.g. when translating an item using the selector tool, then we will only do this for the
324     // first point and store the collection for later use. This significantly improves the performance
325     if (first_point) {
326         _clear_paths();
328         // Determine the type of bounding box we should snap to
329         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
331         bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
332         bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
334         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
335             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
336             int prefs_bbox = prefs->getBool("/tools/bounding_box", 0);
337             bbox_type = !prefs_bbox ?
338                 SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
339         }
341         // Consider the page border for snapping
342         if (_snapmanager->snapprefs.getSnapToPageBorder()) {
343             Geom::PathVector *border_path = _getBorderPathv();
344             if (border_path != NULL) {
345                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
346             }
347         }
349         for (std::vector<SnapCandidateItem>::const_iterator i = _candidates->begin(); i != _candidates->end(); i++) {
351             /* Transform the requested snap point to this item's coordinates */
352             Geom::Matrix i2doc(Geom::identity());
353             SPItem *root_item = NULL;
354             /* We might have a clone at hand, so make sure we get the root item */
355             if (SP_IS_USE((*i).item)) {
356                 i2doc = sp_use_get_root_transform(SP_USE((*i).item));
357                 root_item = sp_use_root(SP_USE((*i).item));
358                 g_return_if_fail(root_item);
359             } else {
360                 i2doc = sp_item_i2doc_affine((*i).item);
361                 root_item = (*i).item;
362             }
364             //Build a list of all paths considered for snapping to
366             //Add the item's path to snap to
367             if (_snapmanager->snapprefs.getSnapToItemPath()) {
368                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
369                     // Snapping to the path of characters is very cool, but for a large
370                     // chunk of text this will take ages! So limit snapping to text paths
371                     // containing max. 240 characters. Snapping the bbox will not be affected
372                     bool very_lenghty_prose = false;
373                     if (SP_IS_TEXT(root_item) || SP_IS_FLOWTEXT(root_item)) {
374                         very_lenghty_prose =  sp_text_get_length(SP_TEXT(root_item)) > 240;
375                     }
376                     // On my AMD 3000+, the snapping lag becomes annoying at approx. 240 chars
377                     // which corresponds to a lag of 500 msec. This is for snapping a rect
378                     // to a single line of text.
380                     // Snapping for example to a traced bitmap is also very stressing for
381                     // the CPU, so we'll only snap to paths having no more than 500 nodes
382                     // This also leads to a lag of approx. 500 msec (in my lousy test set-up).
383                     bool very_complex_path = false;
384                     if (SP_IS_PATH(root_item)) {
385                         very_complex_path = sp_nodes_in_path(SP_PATH(root_item)) > 500;
386                     }
388                     if (!very_lenghty_prose && !very_complex_path) {
389                         SPCurve *curve = curve_for_item(root_item);
390                         if (curve) {
391                             // We will get our own copy of the path, which must be freed at some point
392                             Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
393                             _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.
394                             curve->unref();
395                         }
396                     }
397                 }
398             }
400             //Add the item's bounding box to snap to
401             if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
402                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
403                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
404                     // of the item AND the bbox of the clipping path at the same time
405                     if (!(*i).clip_or_mask) {
406                         Geom::OptRect rect;
407                         sp_item_invoke_bbox(root_item, rect, i2doc, TRUE, bbox_type);
408                         if (rect) {
409                             Geom::PathVector *path = _getPathvFromRect(*rect);
410                             rect = sp_item_bbox_desktop(root_item, bbox_type);
411                             _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(path, SNAPTARGET_BBOX_EDGE, rect));
412                         }
413                     }
414                 }
415             }
416         }
417     }
420 void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
421                                      Inkscape::SnapCandidatePoint const &p,
422                                      std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
423                                      SPPath const *selected_path) const
425     _collectPaths(p, p.getSourceNum() == 0);
426     // Now we can finally do the real snapping, using the paths collected above
428     g_assert(_snapmanager->getDesktop() != NULL);
429     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
431     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
433     if (p.getSourceNum() == 0) {
434         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
435          * currently being edited, because that path requires special care: when snapping to nodes
436          * only the unselected nodes of that path should be considered, and these will be passed on separately.
437          * This path must not be ignored however when snapping to the paths, so we add it here
438          * manually when applicable.
439          * */
440         if (node_tool_active) {
441             SPCurve *curve = curve_for_item(SP_ITEM(selected_path));
442             if (curve) {
443                 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
444                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pathv, SNAPTARGET_PATH, Geom::OptRect(), true));
445                 curve->unref();
446             }
447         }
448     }
450     int num_path = 0;
451     int num_segm = 0;
453     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator it_p = _paths_to_snap_to->begin(); it_p != _paths_to_snap_to->end(); it_p++) {
454         bool const being_edited = node_tool_active && (*it_p).currently_being_edited;
455         //if true then this pathvector it_pv is currently being edited in the node tool
457         for(Geom::PathVector::iterator it_pv = (it_p->path_vector)->begin(); it_pv != (it_p->path_vector)->end(); ++it_pv) {
458             // Find a nearest point for each curve within this path
459             // n curves will return n time values with 0 <= t <= 1
460             std::vector<double> anp = (*it_pv).nearestPointPerCurve(p_doc);
462             std::vector<double>::const_iterator np = anp.begin();
463             unsigned int index = 0;
464             for (; np != anp.end(); np++, index++) {
465                 Geom::Curve const *curve = &((*it_pv).at_index(index));
466                 Geom::Point const sp_doc = curve->pointAt(*np);
468                 bool c1 = true;
469                 bool c2 = true;
470                 if (being_edited) {
471                     /* If the path is being edited, then we should only snap though to stationary pieces of the path
472                      * and not to the pieces that are being dragged around. This way we avoid
473                      * self-snapping. For this we check whether the nodes at both ends of the current
474                      * piece are unselected; if they are then this piece must be stationary
475                      */
476                     g_assert(unselected_nodes != NULL);
477                     Geom::Point start_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(0));
478                     Geom::Point end_pt = _snapmanager->getDesktop()->doc2dt(curve->pointAt(1));
479                     c1 = isUnselectedNode(start_pt, unselected_nodes);
480                     c2 = isUnselectedNode(end_pt, unselected_nodes);
481                     /* Unfortunately, this might yield false positives for coincident nodes. Inkscape might therefore mistakenly
482                      * snap to path segments that are not stationary. There are at least two possible ways to overcome this:
483                      * - Linking the individual nodes of the SPPath we have here, to the nodes of the NodePath::SubPath class as being
484                      *   used in sp_nodepath_selected_nodes_move. This class has a member variable called "selected". For this the nodes
485                      *   should be in the exact same order for both classes, so we can index them
486                      * - Replacing the SPPath being used here by the the NodePath::SubPath class; but how?
487                      */
488                 }
490                 Geom::Point const sp_dt = _snapmanager->getDesktop()->doc2dt(sp_doc);
491                 if (!being_edited || (c1 && c2)) {
492                     Geom::Coord const dist = Geom::distance(sp_doc, p_doc);
493                     if (dist < getSnapperTolerance()) {
494                         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));
495                     }
496                 }
497             }
498             num_segm++;
499         } // End of: for (Geom::PathVector::iterator ....)
500         num_path++;
501     }
504 /* Returns true if point is coincident with one of the unselected nodes */
505 bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::vector<Inkscape::SnapCandidatePoint> const *unselected_nodes) const
507     if (unselected_nodes == NULL) {
508         return false;
509     }
511     if (unselected_nodes->size() == 0) {
512         return false;
513     }
515     for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator i = unselected_nodes->begin(); i != unselected_nodes->end(); i++) {
516         if (Geom::L2(point - (*i).getPoint()) < 1e-4) {
517             return true;
518         }
519     }
521     return false;
524 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
525                                      Inkscape::SnapCandidatePoint const &p,
526                                      SnapConstraint const &c) const
529     _collectPaths(p, p.getSourceNum() == 0);
531     // Now we can finally do the real snapping, using the paths collected above
533     g_assert(_snapmanager->getDesktop() != NULL);
534     Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
536     Geom::Point direction_vector = c.getDirection();
537     if (!is_zero(direction_vector)) {
538         direction_vector = Geom::unit_vector(direction_vector);
539     }
541     // The intersection point of the constraint line with any path, must lie within two points on the
542     // SnapConstraint: p_min_on_cl and p_max_on_cl. 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);
546     Geom::Coord tolerance = getSnapperTolerance();
548     // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have
549     // to convert the snapper coordinates from the desktop coordinates to document coordinates
551     std::vector<Geom::Path> constraint_path;
552     if (c.isCircular()) {
553         Geom::Circle constraint_circle(_snapmanager->getDesktop()->dt2doc(c.getPoint()), c.getRadius());
554         constraint_circle.getPath(constraint_path);
555     } else {
556         Geom::Path constraint_line;
557         constraint_line.start(p_min_on_cl);
558         constraint_line.appendNew<Geom::LineSegment>(p_max_on_cl);
559         constraint_path.push_back(constraint_line);
560     }
562     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
563         if (k->path_vector) {
564             Geom::CrossingSet cs = Geom::crossings(constraint_path, *(k->path_vector));
565             unsigned int index = 0;
566             for (Geom::CrossingSet::const_iterator i = cs.begin(); i != cs.end(); i++) {
567                 if (index >= constraint_path.size()) {
568                     break;
569                 }
570                 for (Geom::Crossings::const_iterator m = (*i).begin(); m != (*i).end(); m++) {
571                     //std::cout << "ta = " << (*m).ta << " | tb = " << (*m).tb << std::endl;
572                     // Reconstruct the point of intersection
573                     Geom::Point p_inters = constraint_path[index].pointAt((*m).ta);
574                     // .. and convert it to desktop coordinates
575                     p_inters = _snapmanager->getDesktop()->doc2dt(p_inters);
576                     Geom::Coord dist = Geom::L2(p_proj_on_cl - p_inters);
577                     SnappedPoint s = SnappedPoint(p_inters, p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);;
578                     if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it
579                         if (c.isCircular()) {
580                             Geom::Point v_orig = c.getDirection(); // vector from the origin to the original (untransformed) point
581                             Geom::Point v_inters = p_inters - c.getPoint();
582                             Geom::Coord radians = atan2(Geom::dot(Geom::rot90(v_orig), v_inters), Geom::dot(v_orig, v_inters));
583                             s.setTransformation(Geom::Point(radians, radians));
584                         }
585                         sc.points.push_back(s);
586                     }
587                 }
588                 index++;
589             }
590         }
591     }
595 void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
596                                             Inkscape::SnapCandidatePoint const &p,
597                                             Geom::OptRect const &bbox_to_snap,
598                                             std::vector<SPItem const *> const *it,
599                                             std::vector<SnapCandidatePoint> *unselected_nodes) const
601     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false ) {
602         return;
603     }
605     /* Get a list of all the SPItems that we will try to snap to */
606     if (p.getSourceNum() == 0) {
607         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
608         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
609     }
611     if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
612         || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
613         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
614         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
615         || _snapmanager->snapprefs.getIncludeItemCenter()) {
616         _snapNodes(sc, p, unselected_nodes);
617     }
619     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
620         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
621         if (n > 0) {
622             /* While editing a path in the node tool, findCandidates must ignore that path because
623              * of the node snapping requirements (i.e. only unselected nodes must be snapable).
624              * That path must not be ignored however when snapping to the paths, so we add it here
625              * manually when applicable
626              */
627             SPPath *path = NULL;
628             if (it != NULL) {
629                 if (it->size() == 1 && SP_IS_PATH(*it->begin())) {
630                     path = SP_PATH(*it->begin());
631                 } // else: *it->begin() might be a SPGroup, e.g. when editing a LPE of text that has been converted to a group of paths
632                 // as reported in bug #356743. In that case we can just ignore it, i.e. not snap to this item
633             }
634             _snapPaths(sc, p, unselected_nodes, path);
635         } else {
636             _snapPaths(sc, p, NULL, NULL);
637         }
638     }
641 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
642                                                   Inkscape::SnapCandidatePoint const &p,
643                                                   Geom::OptRect const &bbox_to_snap,
644                                                   SnapConstraint const &c,
645                                                   std::vector<SPItem const *> const *it) const
647     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
648         return;
649     }
651     /* Get a list of all the SPItems that we will try to snap to */
652     if (p.getSourceNum() == 0) {
653         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
654         _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
655     }
657     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
658     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
659     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
661     // When snapping to objects, we either snap to their nodes or their paths. It is however very
662     // unlikely that any node will be exactly at the constrained line, so for a constrained snap
663     // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
664     // so we will more or less snap to them anyhow.
666     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
667         _snapPathsConstrained(sc, p, c);
668     }
672 // This method is used to snap a guide to nodes, while dragging the guide around
673 void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
674                                         Geom::Point const &p,
675                                         Geom::Point const &guide_normal) const
677     /* Get a list of all the SPItems that we will try to snap to */
678     std::vector<SPItem*> cand;
679     std::vector<SPItem const *> const it; //just an empty list
681     DimensionToSnap snap_dim;
682     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
683         snap_dim = GUIDE_TRANSL_SNAP_Y;
684     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
685         snap_dim = GUIDE_TRANSL_SNAP_X;
686     } else {
687         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
688     }
690     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
691     _snapTranslatingGuideToNodes(sc, p, guide_normal);
695 // This method is used to snap the origin of a guide to nodes/paths, while dragging the origin along the guide
696 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
697                                         Geom::Point const &p,
698                                         Geom::Point const &guide_normal,
699                                         SnapConstraint const &/*c*/) const
701     /* Get a list of all the SPItems that we will try to snap to */
702     std::vector<SPItem*> cand;
703     std::vector<SPItem const *> const it; //just an empty list
705     DimensionToSnap snap_dim;
706     if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
707         snap_dim = GUIDE_TRANSL_SNAP_Y;
708     } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
709         snap_dim = GUIDE_TRANSL_SNAP_X;
710     } else {
711         snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
712     }
714     _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
715     _snapTranslatingGuideToNodes(sc, p, guide_normal);
719 /**
720  *  \return true if this Snapper will snap at least one kind of point.
721  */
722 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
724     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
725                         || _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
726                         || _snapmanager->snapprefs.getSnapToBBoxPath()
727                         || _snapmanager->snapprefs.getSnapToBBoxNode()
728                         || _snapmanager->snapprefs.getSnapToPageBorder()
729                         || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
730                         || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
731                         || _snapmanager->snapprefs.getIncludeItemCenter();
733     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
736 bool Inkscape::ObjectSnapper::GuidesMightSnap() const // almost the same as ThisSnapperMightSnap above, but only looking at points (and not paths)
738     bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
739                         || _snapmanager->snapprefs.getSnapToPageBorder()
740                         || (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxNode())
741                         || (_snapmanager->snapprefs.getSnapModeBBox() && (_snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()))
742                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()))
743                         || (_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getIncludeItemCenter())
744                         || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapIntersectionCS()));
746     return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
749 void Inkscape::ObjectSnapper::_clear_paths() const
751     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
752         delete k->path_vector;
753     }
754     _paths_to_snap_to->clear();
757 Geom::PathVector* Inkscape::ObjectSnapper::_getBorderPathv() const
759     Geom::Rect const border_rect = Geom::Rect(Geom::Point(0,0), Geom::Point(sp_document_width(_snapmanager->getDocument()),sp_document_height(_snapmanager->getDocument())));
760     return _getPathvFromRect(border_rect);
763 Geom::PathVector* Inkscape::ObjectSnapper::_getPathvFromRect(Geom::Rect const rect) const
765     SPCurve const *border_curve = SPCurve::new_from_rect(rect, true);
766     if (border_curve) {
767         Geom::PathVector *dummy = new Geom::PathVector(border_curve->get_pathvector());
768         return dummy;
769     } else {
770         return NULL;
771     }
774 void Inkscape::ObjectSnapper::_getBorderNodes(std::vector<SnapCandidatePoint> *points) const
776     Geom::Coord w = sp_document_width(_snapmanager->getDocument());
777     Geom::Coord h = sp_document_height(_snapmanager->getDocument());
778     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
779     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(0,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
780     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,h), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
781     points->push_back(Inkscape::SnapCandidatePoint(Geom::Point(w,0), SNAPSOURCE_UNDEFINED, SNAPTARGET_PAGE_CORNER));
784 void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
785                              std::vector<SnapCandidatePoint> *points,
786                              bool const /*isTarget*/,
787                              bool const includeCorners,
788                              bool const includeLineMidpoints,
789                              bool const includeObjectMidpoints)
791     if (bbox) {
792         // collect the corners of the bounding box
793         for ( unsigned k = 0 ; k < 4 ; k++ ) {
794             if (includeCorners) {
795                 points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, 0, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
796             }
797             // optionally, collect the midpoints of the bounding box's edges too
798             if (includeLineMidpoints) {
799                 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));
800             }
801         }
802         if (includeObjectMidpoints) {
803             points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
804         }
805     }
808 /*
809   Local Variables:
810   mode:c++
811   c-file-style:"stroustrup"
812   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
813   indent-tabs-mode:nil
814   fill-column:99
815   End:
816 */
817 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :