Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / object-snapper.cpp
index 00bd10fe2c97319af9c31f7940f29e09d9d99f2b..43651f002405e12ced35ea1743a6862668ec5bfb 100644 (file)
@@ -5,17 +5,21 @@
  * Authors:
  *   Carl Hetherington <inkscape@carlh.net>
  *   Diederik van Lierop <mail@diedenrezi.nl>
+ *   Jon A. Cruz <jon@joncruz.org>
+ *   Abhishek Sharma
  *
- * Copyright (C) 2005 - 2008 Authors
+ * Copyright (C) 2005 - 2010 Authors
  *
  * Released under GNU GPL, read the file 'COPYING' for more information
  */
 
 #include "svg/svg.h"
 #include <2geom/path-intersection.h>
+#include <2geom/pathvector.h>
 #include <2geom/point.h>
 #include <2geom/rect.h>
 #include <2geom/line.h>
+#include <2geom/circle.h>
 #include "document.h"
 #include "sp-namedview.h"
 #include "sp-image.h"
@@ -73,24 +77,24 @@ bool Inkscape::ObjectSnapper::getSnapperAlwaysSnap() const
  *  \param parent Pointer to the document's root, or to a clipped path or mask object
  *  \param it List of items to ignore
  *  \param bbox_to_snap Bounding box hulling the whole bunch of points, all from the same selection and having the same transformation
- *  \param DimensionToSnap Snap in X, Y, or both directions.
  */
 
 void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
                                               std::vector<SPItem const *> const *it,
                                               bool const &first_point,
                                               Geom::Rect const &bbox_to_snap,
-                                              DimensionToSnap const snap_dim,
                                               bool const clip_or_mask,
                                               Geom::Matrix const additional_affine) const // transformation of the item being clipped / masked
 {
-    bool const c1 = (snap_dim == TRANSL_SNAP_XY) && ThisSnapperMightSnap();
-    bool const c2 = (snap_dim != TRANSL_SNAP_XY) && GuidesMightSnap();
-
-    if (!(c1 || c2)) {
+    if (!ThisSnapperMightSnap()) {
         return;
     }
 
+    if (_snapmanager->getDesktop() == NULL) {
+        g_warning("desktop == NULL, so we cannot snap; please inform the developpers of this bug");
+        // Apparently the etup() method from the SnapManager class hasn't been called before trying to snap.
+    }
+
     if (first_point) {
         _candidates->clear();
     }
@@ -98,7 +102,7 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
     Geom::Rect bbox_to_snap_incl = bbox_to_snap; // _incl means: will include the snapper tolerance
     bbox_to_snap_incl.expandBy(getSnapperTolerance()); // see?
 
-    for (SPObject* o = parent->first_child(); o != NULL; o = SP_OBJECT_NEXT(o)) {
+    for ( SPObject *o = parent->firstChild(); o; o = o->getNext() ) {
         g_assert(_snapmanager->getDesktop() != NULL);
         if (SP_IS_ITEM(o) && !(_snapmanager->getDesktop()->itemIsHidden(SP_ITEM(o)) && !clip_or_mask)) {
             // Snapping to items in a locked layer is allowed
@@ -122,17 +126,17 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
                         // we should also consider that path or mask for snapping to
                         obj = SP_OBJECT(item->clip_ref->getObject());
                         if (obj) {
-                            _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->i2doc_affine());
+                            _findCandidates(obj, it, false, bbox_to_snap, true, item->i2doc_affine());
                         }
                         obj = SP_OBJECT(item->mask_ref->getObject());
                         if (obj) {
-                            _findCandidates(obj, it, false, bbox_to_snap, snap_dim, true, item->i2doc_affine());
+                            _findCandidates(obj, it, false, bbox_to_snap, true, item->i2doc_affine());
                         }
                     }
                 }
 
                 if (SP_IS_GROUP(o)) {
-                    _findCandidates(o, it, false, bbox_to_snap, snap_dim, clip_or_mask, additional_affine);
+                    _findCandidates(o, it, false, bbox_to_snap, clip_or_mask, additional_affine);
                 } else {
                     Geom::OptRect bbox_of_item = Geom::Rect();
                     if (clip_or_mask) {
@@ -146,7 +150,8 @@ void Inkscape::ObjectSnapper::_findCandidates(SPObject* parent,
                     }
                     if (bbox_of_item) {
                         // See if the item is within range
-                        if (bbox_to_snap_incl.intersects(*bbox_of_item)) {
+                        if (bbox_to_snap_incl.intersects(*bbox_of_item)
+                                || (_snapmanager->snapprefs.getIncludeItemCenter() && bbox_to_snap_incl.contains(item->getCenter()))) { // rotation center might be outside of the bounding box
                             // This item is within snapping range, so record it as a candidate
                             _candidates->push_back(SnapCandidateItem(item, clip_or_mask, additional_affine));
                             // For debugging: print the id of the candidate to the console
@@ -226,11 +231,24 @@ void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
                     _snapmanager->snapprefs.setSnapIntersectionCS(false);
                 }
 
+                // We should not snap a transformation center to any of the centers of the items in the
+                // current selection (see the comment in SelTrans::centerRequest())
+                bool old_pref2 = _snapmanager->snapprefs.getIncludeItemCenter();
+                if (old_pref2) {
+                    for ( GSList const *itemlist = _snapmanager->getRotationCenterSource(); itemlist != NULL; itemlist = g_slist_next(itemlist) ) {
+                        if ((*i).item == reinterpret_cast<SPItem*>(itemlist->data)) {
+                            // don't snap to this item's rotation center
+                            _snapmanager->snapprefs.setIncludeItemCenter(false);
+                            break;
+                        }
+                    }
+                }
+
                 root_item->getSnappoints(*_points_to_snap_to, &_snapmanager->snapprefs);
 
-                if (_snapmanager->snapprefs.getSnapToItemPath()) {
-                    _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
-                }
+                // restore the original snap preferences
+                _snapmanager->snapprefs.setSnapIntersectionCS(old_pref);
+                _snapmanager->snapprefs.setIncludeItemCenter(old_pref2);
             }
 
             //Collect the bounding box's corners so we can snap to them
@@ -248,13 +266,16 @@ void Inkscape::ObjectSnapper::_collectNodes(Inkscape::SnapSourceType const &t,
 
 void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
                                          Inkscape::SnapCandidatePoint const &p,
-                                         std::vector<SnapCandidatePoint> *unselected_nodes) const
+                                         std::vector<SnapCandidatePoint> *unselected_nodes,
+                                         SnapConstraint const &c,
+                                         Geom::Point const &p_proj_on_constraint) const
 {
     // Iterate through all nodes, find out which one is the closest to p, and snap to it!
 
-    _collectNodes(p.getSourceType(), p.getSourceNum() == 0);
+    _collectNodes(p.getSourceType(), p.getSourceNum() <= 0);
 
-    if (unselected_nodes != NULL) {
+    if (unselected_nodes != NULL && unselected_nodes->size() > 0) {
+        g_assert(_points_to_snap_to != NULL);
         _points_to_snap_to->insert(_points_to_snap_to->end(), unselected_nodes->begin(), unselected_nodes->end());
     }
 
@@ -262,9 +283,24 @@ void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
     bool success = false;
 
     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
-        Geom::Coord dist = Geom::L2((*k).getPoint() - p.getPoint());
+        Geom::Point target_pt = (*k).getPoint();
+        Geom::Coord dist = NR_HUGE;
+        if (!c.isUndefined()) {
+            // We're snapping to nodes along a constraint only, so find out if this node
+            // is at the constraint, while allowing for a small margin
+            if (Geom::L2(target_pt - c.projection(target_pt)) > 1e-9) {
+                // The distance from the target point to its projection on the constraint
+                // is too large, so this point is not on the constraint. Skip it!
+                continue;
+            }
+            dist = Geom::L2(target_pt - p_proj_on_constraint);
+        } else {
+            // Free (unconstrained) snapping
+            dist = Geom::L2(target_pt - p.getPoint());
+        }
+
         if (dist < getSnapperTolerance() && dist < s.getSnapDistance()) {
-            s = SnappedPoint((*k).getPoint(), p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
+            s = SnappedPoint(target_pt, p.getSourceType(), p.getSourceNum(), (*k).getTargetType(), dist, getSnapperTolerance(), getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
             success = true;
         }
     }
@@ -274,18 +310,16 @@ void Inkscape::ObjectSnapper::_snapNodes(SnappedConstraints &sc,
     }
 }
 
-void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &sc,
+void Inkscape::ObjectSnapper::_snapTranslatingGuide(SnappedConstraints &sc,
                                          Geom::Point const &p,
                                          Geom::Point const &guide_normal) const
 {
     // Iterate through all nodes, find out which one is the closest to this guide, and snap to it!
     _collectNodes(SNAPSOURCE_GUIDE, true);
 
-    // Although we won't snap to paths here (which would give us under constrained snaps) we can still snap to intersections of paths.
     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
-        _collectPaths(Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), true);
+        _collectPaths(p, SNAPSOURCE_GUIDE, true);
         _snapPaths(sc, Inkscape::SnapCandidatePoint(p, SNAPSOURCE_GUIDE), NULL, NULL);
-        // The paths themselves should be discarded in findBestSnap(), as we should only snap to their intersections
     }
 
     SnappedPoint s;
@@ -293,12 +327,13 @@ void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &s
     Geom::Coord tol = getSnapperTolerance();
 
     for (std::vector<SnapCandidatePoint>::const_iterator k = _points_to_snap_to->begin(); k != _points_to_snap_to->end(); k++) {
+        Geom::Point target_pt = (*k).getPoint();
         // Project each node (*k) on the guide line (running through point p)
-        Geom::Point p_proj = Geom::projection((*k).getPoint(), Geom::Line(p, p + Geom::rot90(guide_normal)));
-        Geom::Coord dist = Geom::L2((*k).getPoint() - p_proj); // distance from node to the guide
+        Geom::Point p_proj = Geom::projection(target_pt, Geom::Line(p, p + Geom::rot90(guide_normal)));
+        Geom::Coord dist = Geom::L2(target_pt - p_proj); // distance from node to the guide
         Geom::Coord dist2 = Geom::L2(p - p_proj); // distance from projection of node on the guide, to the mouse location
         if ((dist < tol && dist2 < tol) || getSnapperAlwaysSnap()) {
-            s = SnappedPoint((*k).getPoint(), SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
+            s = SnappedPoint(target_pt, SNAPSOURCE_GUIDE, 0, (*k).getTargetType(), dist, tol, getSnapperAlwaysSnap(), false, true, (*k).getTargetBBox());
             sc.points.push_back(s);
         }
     }
@@ -309,7 +344,8 @@ void Inkscape::ObjectSnapper::_snapTranslatingGuideToNodes(SnappedConstraints &s
  * Returns index of first NR_END bpath in array.
  */
 
-void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &p,
+void Inkscape::ObjectSnapper::_collectPaths(Geom::Point /*p*/,
+                                         Inkscape::SnapSourceType const source_type,
                                          bool const &first_point) const
 {
     // Now, let's first collect all paths to snap to. If we have a whole bunch of points to snap,
@@ -321,8 +357,8 @@ void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &
         // Determine the type of bounding box we should snap to
         SPItem::BBoxType bbox_type = SPItem::GEOMETRIC_BBOX;
 
-        bool p_is_a_node = p.getSourceType() & Inkscape::SNAPSOURCE_NODE_CATEGORY;
-        bool p_is_other = p.getSourceType() & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
+        bool p_is_a_node = source_type & Inkscape::SNAPSOURCE_NODE_CATEGORY;
+        bool p_is_other = source_type & Inkscape::SNAPSOURCE_OTHER_CATEGORY;
 
         if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
@@ -332,7 +368,7 @@ void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &
         }
 
         // Consider the page border for snapping
-        if (_snapmanager->snapprefs.getSnapToPageBorder()) {
+        if (_snapmanager->snapprefs.getSnapToPageBorder() && _snapmanager->snapprefs.getSnapModeBBoxOrNodes()) {
             Geom::PathVector *border_path = _getBorderPathv();
             if (border_path != NULL) {
                 _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(border_path, SNAPTARGET_PAGE_BORDER, Geom::OptRect()));
@@ -357,7 +393,7 @@ void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &
             //Build a list of all paths considered for snapping to
 
             //Add the item's path to snap to
-            if (_snapmanager->snapprefs.getSnapToItemPath()) {
+            if (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapModeNode()) {
                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && !p_is_a_node)) {
                     // Snapping to the path of characters is very cool, but for a large
                     // chunk of text this will take ages! So limit snapping to text paths
@@ -381,9 +417,14 @@ void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &
                     if (!very_lenghty_prose && !very_complex_path) {
                         SPCurve *curve = curve_for_item(root_item);
                         if (curve) {
-                            // We will get our own copy of the path, which must be freed at some point
-                            Geom::PathVector *borderpathv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
-                            _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.
+                            // We will get our own copy of the pathvector, which must be freed at some point
+
+                            // Geom::PathVector *pv = pathvector_for_curve(root_item, curve, true, true, Geom::identity(), (*i).additional_affine);
+
+                            Geom::PathVector *pv = new Geom::PathVector(curve->get_pathvector());
+                            (*pv) *= root_item->i2d_affine() * (*i).additional_affine * _snapmanager->getDesktop()->doc2dt(); // (_edit_transform * _i2d_transform);
+
+                            _paths_to_snap_to->push_back(Inkscape::SnapCandidatePath(pv, SNAPTARGET_PATH, Geom::OptRect())); // Perhaps for speed, get a reference to the Geom::pathvector, and store the transformation besides it.
                             curve->unref();
                         }
                     }
@@ -391,7 +432,7 @@ void Inkscape::ObjectSnapper::_collectPaths(Inkscape::SnapCandidatePoint const &
             }
 
             //Add the item's bounding box to snap to
-            if (_snapmanager->snapprefs.getSnapToBBoxPath()) {
+            if (_snapmanager->snapprefs.getSnapToBBoxPath() && _snapmanager->snapprefs.getSnapModeBBox()) {
                 if (p_is_other || !(_snapmanager->snapprefs.getStrictSnapping() && p_is_a_node)) {
                     // Discard the bbox of a clipped path / mask, because we don't want to snap to both the bbox
                     // of the item AND the bbox of the clipping path at the same time
@@ -415,7 +456,7 @@ void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
                                      std::vector<Inkscape::SnapCandidatePoint> *unselected_nodes,
                                      SPPath const *selected_path) const
 {
-    _collectPaths(p, p.getSourceNum() == 0);
+    _collectPaths(p.getPoint(), p.getSourceType(), p.getSourceNum() <= 0);
     // Now we can finally do the real snapping, using the paths collected above
 
     g_assert(_snapmanager->getDesktop() != NULL);
@@ -423,7 +464,7 @@ void Inkscape::ObjectSnapper::_snapPaths(SnappedConstraints &sc,
 
     bool const node_tool_active = _snapmanager->snapprefs.getSnapToItemPath() && selected_path != NULL;
 
-    if (p.getSourceNum() == 0) {
+    if (p.getSourceNum() <= 0) {
         /* findCandidates() is used for snapping to both paths and nodes. It ignores the path that is
          * currently being edited, because that path requires special care: when snapping to nodes
          * only the unselected nodes of that path should be considered, and these will be passed on separately.
@@ -516,52 +557,92 @@ bool Inkscape::ObjectSnapper::isUnselectedNode(Geom::Point const &point, std::ve
 
 void Inkscape::ObjectSnapper::_snapPathsConstrained(SnappedConstraints &sc,
                                      Inkscape::SnapCandidatePoint const &p,
-                                     ConstraintLine const &c) const
+                                     SnapConstraint const &c,
+                                     Geom::Point const &p_proj_on_constraint) const
 {
 
-    _collectPaths(p, p.getSourceNum() == 0);
+    _collectPaths(p_proj_on_constraint, p.getSourceType(), p.getSourceNum() <= 0);
 
     // Now we can finally do the real snapping, using the paths collected above
 
     g_assert(_snapmanager->getDesktop() != NULL);
-    Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p.getPoint());
+    Geom::Point const p_doc = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint);
 
     Geom::Point direction_vector = c.getDirection();
     if (!is_zero(direction_vector)) {
         direction_vector = Geom::unit_vector(direction_vector);
     }
 
-    // The intersection point of the constraint line with any path,
-    // must lie within two points on the constraintline: p_min_on_cl and p_max_on_cl
-    // The distance between those points is twice the snapping tolerance
-    Geom::Point const p_proj_on_cl = p.getPoint(); // projection has already been taken care of in constrainedSnap in the snapmanager;
-    Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl - getSnapperTolerance() * direction_vector);
-    Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_cl + getSnapperTolerance() * direction_vector);
+    // The intersection point of the constraint line with any path, must lie within two points on the
+    // SnapConstraint: p_min_on_cl and p_max_on_cl. The distance between those points is twice the snapping tolerance
+    Geom::Point const p_min_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint - getSnapperTolerance() * direction_vector);
+    Geom::Point const p_max_on_cl = _snapmanager->getDesktop()->dt2doc(p_proj_on_constraint + getSnapperTolerance() * direction_vector);
+    Geom::Coord tolerance = getSnapperTolerance();
+
+    // PS: Because the paths we're about to snap to are all expressed relative to document coordinate system, we will have
+    // to convert the snapper coordinates from the desktop coordinates to document coordinates
 
-    Geom::Path cl;
-    std::vector<Geom::Path> clv;
-    cl.start(p_min_on_cl);
-    cl.appendNew<Geom::LineSegment>(p_max_on_cl);
-    clv.push_back(cl);
+    std::vector<Geom::Path> constraint_path;
+    if (c.isCircular()) {
+        Geom::Circle constraint_circle(_snapmanager->getDesktop()->dt2doc(c.getPoint()), c.getRadius());
+        constraint_circle.getPath(constraint_path);
+    } else {
+        Geom::Path constraint_line;
+        constraint_line.start(p_min_on_cl);
+        constraint_line.appendNew<Geom::LineSegment>(p_max_on_cl);
+        constraint_path.push_back(constraint_line);
+    }
+    // Length of constraint_path will always be one
 
+    // Find all intersections of the constrained path with the snap target candidates
+    std::vector<Geom::Point> intersections;
     for (std::vector<Inkscape::SnapCandidatePath >::const_iterator k = _paths_to_snap_to->begin(); k != _paths_to_snap_to->end(); k++) {
         if (k->path_vector) {
-            Geom::CrossingSet cs = Geom::crossings(clv, *(k->path_vector));
-            if (cs.size() > 0) {
-                // We need only the first element of cs, because cl is only a single straight linesegment
-                // This first element contains a vector filled with crossings of cl with k->first
-                for (std::vector<Geom::Crossing>::const_iterator m = cs[0].begin(); m != cs[0].end(); m++) {
-                    if ((*m).ta >= 0 && (*m).ta <= 1 ) {
-                        // Reconstruct the point of intersection
-                        Geom::Point p_inters = p_min_on_cl + ((*m).ta) * (p_max_on_cl - p_min_on_cl);
-                        // When it's within snapping range, then return it
-                        // (within snapping range == between p_min_on_cl and p_max_on_cl == 0 < ta < 1)
-                        Geom::Coord dist = Geom::L2(_snapmanager->getDesktop()->dt2doc(p_proj_on_cl) - p_inters);
-                        SnappedPoint s(_snapmanager->getDesktop()->doc2dt(p_inters), p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);
-                        sc.points.push_back(s);
+            // Do the intersection math
+            Geom::CrossingSet cs = Geom::crossings(constraint_path, *(k->path_vector));
+            // Store the results as intersection points
+            unsigned int index = 0;
+            for (Geom::CrossingSet::const_iterator i = cs.begin(); i != cs.end(); i++) {
+                if (index >= constraint_path.size()) {
+                    break;
+                }
+                // Reconstruct and store the points of intersection
+                for (Geom::Crossings::const_iterator m = (*i).begin(); m != (*i).end(); m++) {
+                    intersections.push_back(constraint_path[index].pointAt((*m).ta));
+                }
+                index++;
+            }
+
+            //Geom::crossings will not consider the closing segment apparently, so we'll handle that separately here
+            //TODO: This should have been fixed in rev. #9859, which makes this workaround obsolete
+            for(Geom::PathVector::iterator it_pv = k->path_vector->begin(); it_pv != k->path_vector->end(); ++it_pv) {
+                if (it_pv->closed()) {
+                    // Get the closing linesegment and convert it to a path
+                    Geom::Path cls;
+                    cls.close(false);
+                    cls.append(it_pv->back_closed());
+                    // Intersect that closing path with the constrained path
+                    Geom::Crossings cs = Geom::crossings(constraint_path.front(), cls);
+                    // Reconstruct and store the points of intersection
+                    index = 0; // assuming the constraint path vector has only one path
+                    for (Geom::Crossings::const_iterator m = cs.begin(); m != cs.end(); m++) {
+                        intersections.push_back(constraint_path[index].pointAt((*m).ta));
                     }
                 }
             }
+
+            // Convert the collected points of intersection to snapped points
+            for (std::vector<Geom::Point>::iterator p_inters = intersections.begin(); p_inters != intersections.end(); p_inters++) {
+                // Convert to desktop coordinates
+                (*p_inters) = _snapmanager->getDesktop()->doc2dt(*p_inters);
+                // Construct a snapped point
+                Geom::Coord dist = Geom::L2(p.getPoint() - *p_inters);
+                SnappedPoint s = SnappedPoint(*p_inters, p.getSourceType(), p.getSourceNum(), k->target_type, dist, getSnapperTolerance(), getSnapperAlwaysSnap(), true, k->target_bbox);;
+                // Store the snapped point
+                if (dist <= tolerance) { // If the intersection is within snapping range, then we might snap to it
+                    sc.points.push_back(s);
+                }
+            }
         }
     }
 }
@@ -578,20 +659,33 @@ void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
     }
 
     /* Get a list of all the SPItems that we will try to snap to */
-    if (p.getSourceNum() == 0) {
+    if (p.getSourceNum() <= 0) {
         Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
-        _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
+        _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
     }
 
-    if (_snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
-        || _snapmanager->snapprefs.getSnapToBBoxNode() || _snapmanager->snapprefs.getSnapToPageBorder()
-        || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
-        || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
-        || _snapmanager->snapprefs.getIncludeItemCenter()) {
+    // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
+    bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
+                            _snapmanager->snapprefs.getSnapToItemNode() ||
+                            _snapmanager->snapprefs.getSnapSmoothNodes() ||
+                            _snapmanager->snapprefs.getSnapLineMidpoints() ||
+                            _snapmanager->snapprefs.getSnapObjectMidpoints()
+                        )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
+                            _snapmanager->snapprefs.getSnapToBBoxNode() ||
+                            _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
+                            _snapmanager->snapprefs.getSnapBBoxMidpoints()
+                        )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
+                            _snapmanager->snapprefs.getIncludeItemCenter() ||
+                            _snapmanager->snapprefs.getSnapToPageBorder()
+                        ));
+
+    if (snap_nodes) {
         _snapNodes(sc, p, unselected_nodes);
     }
 
-    if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
+    if ((_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getSnapToItemPath()) ||
+        (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxPath()) ||
+        (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && _snapmanager->snapprefs.getSnapToPageBorder())) {
         unsigned n = (unselected_nodes == NULL) ? 0 : unselected_nodes->size();
         if (n > 0) {
             /* While editing a path in the node tool, findCandidates must ignore that path because
@@ -616,30 +710,48 @@ void Inkscape::ObjectSnapper::freeSnap(SnappedConstraints &sc,
 void Inkscape::ObjectSnapper::constrainedSnap( SnappedConstraints &sc,
                                                   Inkscape::SnapCandidatePoint const &p,
                                                   Geom::OptRect const &bbox_to_snap,
-                                                  ConstraintLine const &c,
-                                                  std::vector<SPItem const *> const *it) const
+                                                  SnapConstraint const &c,
+                                                  std::vector<SPItem const *> const *it,
+                                                  std::vector<SnapCandidatePoint> *unselected_nodes) const
 {
     if (_snap_enabled == false || _snapmanager->snapprefs.getSnapFrom(p.getSourceType()) == false) {
         return;
     }
 
+    // project the mouse pointer onto the constraint. Only the projected point will be considered for snapping
+    Geom::Point pp = c.projection(p.getPoint());
+
     /* Get a list of all the SPItems that we will try to snap to */
-    if (p.getSourceNum() == 0) {
-        Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(p.getPoint(), p.getPoint());
-        _findCandidates(sp_document_root(_snapmanager->getDocument()), it, p.getSourceNum() == 0, local_bbox_to_snap, TRANSL_SNAP_XY, false, Geom::identity());
+    if (p.getSourceNum() <= 0) {
+        Geom::Rect const local_bbox_to_snap = bbox_to_snap ? *bbox_to_snap : Geom::Rect(pp, pp);
+        _findCandidates(_snapmanager->getDocument()->getRoot(), it, p.getSourceNum() <= 0, local_bbox_to_snap, false, Geom::identity());
     }
 
     // A constrained snap, is a snap in only one degree of freedom (specified by the constraint line).
     // This is useful for example when scaling an object while maintaining a fixed aspect ratio. It's
     // nodes are only allowed to move in one direction (i.e. in one degree of freedom).
 
-    // When snapping to objects, we either snap to their nodes or their paths. It is however very
-    // unlikely that any node will be exactly at the constrained line, so for a constrained snap
-    // to objects we will only consider the object's paths. Beside, the nodes will be at these paths,
-    // so we will more or less snap to them anyhow.
+    // TODO: Argh, UGLY! Get rid of this here, move this logic to the snap manager
+    bool snap_nodes = (_snapmanager->snapprefs.getSnapModeNode() && (
+                                _snapmanager->snapprefs.getSnapToItemNode() ||
+                                _snapmanager->snapprefs.getSnapSmoothNodes() ||
+                                _snapmanager->snapprefs.getSnapLineMidpoints() ||
+                                _snapmanager->snapprefs.getSnapObjectMidpoints()
+                            )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
+                                _snapmanager->snapprefs.getSnapToBBoxNode() ||
+                                _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
+                                _snapmanager->snapprefs.getSnapBBoxMidpoints()
+                            )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
+                                _snapmanager->snapprefs.getIncludeItemCenter() ||
+                                _snapmanager->snapprefs.getSnapToPageBorder()
+                            ));
+
+    if (snap_nodes) {
+        _snapNodes(sc, p, unselected_nodes, c, pp);
+    }
 
     if (_snapmanager->snapprefs.getSnapToItemPath() || _snapmanager->snapprefs.getSnapToBBoxPath() || _snapmanager->snapprefs.getSnapToPageBorder()) {
-        _snapPathsConstrained(sc, p, c);
+        _snapPathsConstrained(sc, p, c, pp);
     }
 }
 
@@ -653,17 +765,8 @@ void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
     std::vector<SPItem*> cand;
     std::vector<SPItem const *> const it; //just an empty list
 
-    DimensionToSnap snap_dim;
-    if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
-        snap_dim = GUIDE_TRANSL_SNAP_Y;
-    } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
-        snap_dim = GUIDE_TRANSL_SNAP_X;
-    } else {
-        snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
-    }
-
-    _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
-    _snapTranslatingGuideToNodes(sc, p, guide_normal);
+    _findCandidates(_snapmanager->getDocument()->getRoot(), &it, true, Geom::Rect(p, p), false, Geom::identity());
+    _snapTranslatingGuide(sc, p, guide_normal);
 
 }
 
@@ -671,23 +774,14 @@ void Inkscape::ObjectSnapper::guideFreeSnap(SnappedConstraints &sc,
 void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
                                         Geom::Point const &p,
                                         Geom::Point const &guide_normal,
-                                        ConstraintLine const &/*c*/) const
+                                        SnapConstraint const &/*c*/) const
 {
     /* Get a list of all the SPItems that we will try to snap to */
     std::vector<SPItem*> cand;
     std::vector<SPItem const *> const it; //just an empty list
 
-    DimensionToSnap snap_dim;
-    if (guide_normal == to_2geom(component_vectors[Geom::Y])) {
-        snap_dim = GUIDE_TRANSL_SNAP_Y;
-    } else if (guide_normal == to_2geom(component_vectors[Geom::X])) {
-        snap_dim = GUIDE_TRANSL_SNAP_X;
-    } else {
-        snap_dim = ANGLED_GUIDE_TRANSL_SNAP;
-    }
-
-    _findCandidates(sp_document_root(_snapmanager->getDocument()), &it, true, Geom::Rect(p, p), snap_dim, false, Geom::identity());
-    _snapTranslatingGuideToNodes(sc, p, guide_normal);
+    _findCandidates(_snapmanager->getDocument()->getRoot(), &it, true, Geom::Rect(p, p), false, Geom::identity());
+    _snapTranslatingGuide(sc, p, guide_normal);
 
 }
 
@@ -696,29 +790,23 @@ void Inkscape::ObjectSnapper::guideConstrainedSnap(SnappedConstraints &sc,
  */
 bool Inkscape::ObjectSnapper::ThisSnapperMightSnap() const
 {
-    bool snap_to_something = _snapmanager->snapprefs.getSnapToItemPath()
-                        || _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
-                        || _snapmanager->snapprefs.getSnapToBBoxPath()
-                        || _snapmanager->snapprefs.getSnapToBBoxNode()
-                        || _snapmanager->snapprefs.getSnapToPageBorder()
-                        || _snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()
-                        || _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()
-                        || _snapmanager->snapprefs.getIncludeItemCenter();
-
-    return (_snap_enabled && _snapmanager->snapprefs.getSnapModeBBoxOrNodes() && snap_to_something);
-}
-
-bool Inkscape::ObjectSnapper::GuidesMightSnap() const // almost the same as ThisSnapperMightSnap above, but only looking at points (and not paths)
-{
-    bool snap_to_something = _snapmanager->snapprefs.getSnapToItemNode() || _snapmanager->snapprefs.getSnapSmoothNodes()
-                        || _snapmanager->snapprefs.getSnapToPageBorder()
-                        || (_snapmanager->snapprefs.getSnapModeBBox() && _snapmanager->snapprefs.getSnapToBBoxNode())
-                        || (_snapmanager->snapprefs.getSnapModeBBox() && (_snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() || _snapmanager->snapprefs.getSnapBBoxMidpoints()))
-                        || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapLineMidpoints() || _snapmanager->snapprefs.getSnapObjectMidpoints()))
-                        || (_snapmanager->snapprefs.getSnapModeNode() && _snapmanager->snapprefs.getIncludeItemCenter())
-                        || (_snapmanager->snapprefs.getSnapModeNode() && (_snapmanager->snapprefs.getSnapToItemPath() && _snapmanager->snapprefs.getSnapIntersectionCS()));
-
-    return (_snap_enabled && _snapmanager->snapprefs.getSnapModeGuide() && snap_to_something);
+    bool snap_to_something = (_snapmanager->snapprefs.getSnapModeNode() && (
+                                _snapmanager->snapprefs.getSnapToItemPath() ||
+                                _snapmanager->snapprefs.getSnapToItemNode() ||
+                                _snapmanager->snapprefs.getSnapSmoothNodes() ||
+                                _snapmanager->snapprefs.getSnapLineMidpoints() ||
+                                _snapmanager->snapprefs.getSnapObjectMidpoints()
+                            )) || (_snapmanager->snapprefs.getSnapModeBBox() && (
+                                _snapmanager->snapprefs.getSnapToBBoxPath() ||
+                                _snapmanager->snapprefs.getSnapToBBoxNode() ||
+                                _snapmanager->snapprefs.getSnapBBoxEdgeMidpoints() ||
+                                _snapmanager->snapprefs.getSnapBBoxMidpoints()
+                            )) || (_snapmanager->snapprefs.getSnapModeBBoxOrNodes() && (
+                                _snapmanager->snapprefs.getSnapToPageBorder() ||
+                                _snapmanager->snapprefs.getIncludeItemCenter()
+                            ));
+
+    return (_snap_enabled && snap_to_something);
 }
 
 void Inkscape::ObjectSnapper::_clear_paths() const
@@ -767,15 +855,15 @@ void Inkscape::getBBoxPoints(Geom::OptRect const bbox,
         // collect the corners of the bounding box
         for ( unsigned k = 0 ; k < 4 ; k++ ) {
             if (includeCorners) {
-                points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, 0, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
+                points->push_back(Inkscape::SnapCandidatePoint(bbox->corner(k), Inkscape::SNAPSOURCE_BBOX_CORNER, -1, Inkscape::SNAPTARGET_BBOX_CORNER, *bbox));
             }
             // optionally, collect the midpoints of the bounding box's edges too
             if (includeLineMidpoints) {
-                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));
+                points->push_back(Inkscape::SnapCandidatePoint((bbox->corner(k) + bbox->corner((k+1) % 4))/2, Inkscape::SNAPSOURCE_BBOX_EDGE_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_EDGE_MIDPOINT, *bbox));
             }
         }
         if (includeObjectMidpoints) {
-            points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, 0, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
+            points->push_back(Inkscape::SnapCandidatePoint(bbox->midpoint(), Inkscape::SNAPSOURCE_BBOX_MIDPOINT, -1, Inkscape::SNAPTARGET_BBOX_MIDPOINT, *bbox));
         }
     }
 }