Code

Node tool: snap while scaling a selection of nodes. Consider this as experimental...
[inkscape.git] / src / seltrans.cpp
index c3c84114994288e97eda05842674d7866fd945d1..b1d184986da06c3d2b7248c8a211beea641b5bcc 100644 (file)
@@ -6,6 +6,7 @@
  *   bulia byak <buliabyak@users.sf.net>
  *   Carl Hetherington <inkscape@carlh.net>
  *   Diederik van Lierop <mail@diedenrezi.nl>
+ *   Abhishek Sharma
  *
  * Copyright (C) 1999-2002 Lauris Kaplinski
  * Copyright (C) 1999-2008 Authors
@@ -45,6 +46,7 @@
 #include <2geom/angle.h>
 #include "display/snap-indicator.h"
 
+using Inkscape::DocumentUndo;
 
 static void sp_remove_handles(SPKnot *knot[], gint num);
 
@@ -241,8 +243,10 @@ void Inkscape::SelTrans::setCenter(Geom::Point const &p)
     _updateHandles();
 }
 
-void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool show_handles)
+void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool show_handles, bool translating)
 {
+    // While dragging a handle, we will either scale, skew, or rotate and the "translating" parameter will be false
+    // When dragging the selected item itself however, we will translate the selection and that parameter will be true
     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
 
@@ -263,7 +267,7 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s
         SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
         _items.push_back(it);
         _items_const.push_back(it);
-        _items_affines.push_back(sp_item_i2d_affine(it));
+        _items_affines.push_back(it->i2d_affine());
         _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
     }
 
@@ -273,10 +277,11 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s
     // The selector tool should snap the bbox, special snappoints, and path nodes
     // (The special points are the handles, center, rotation axis, font baseline, ends of spiral, etc.)
 
-    // First, determine the bounding box for snapping ...
+    // First, determine the bounding box
     _bbox = selection->bounds(_snap_bbox_type);
     _approximate_bbox = selection->bounds(SPItem::APPROXIMATE_BBOX); // Used for correctly scaling the strokewidth
     _geometric_bbox = selection->bounds(SPItem::GEOMETRIC_BBOX);
+
     _point = p;
     if (_geometric_bbox) {
         _point_geom = _geometric_bbox->min() + _geometric_bbox->dimensions() * Geom::Scale(x, y);
@@ -286,45 +291,59 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s
 
     // Next, get all points to consider for snapping
     SnapManager const &m = _desktop->namedview->snap_manager;
-       Inkscape::SnapPreferences local_snapprefs = m.snapprefs;
-       local_snapprefs.setSnapToItemNode(true); // We should get at least the cusp nodes here. This might
-       // have been turned off because (for example) the user only want paths as a snap target, not nodes
-       // but as a snap source we still need some nodes though!
     _snap_points.clear();
-       _snap_points = selection->getSnapPoints(&local_snapprefs);
-       std::vector<std::pair<Geom::Point, int> > snap_points_hull = selection->getSnapPointsConvexHull(&local_snapprefs);
-       if (_snap_points.size() > 100) {
-               /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
-               An average user would rarely ever try to snap such a large number of nodes anyway, because
-               (s)he could hardly discern which node would be snapping */
-               if (prefs->getBool("/options/snapclosestonly/value", false)) {
-                       _keepClosestPointOnly(_snap_points, p);
-               } else {
-                       _snap_points = snap_points_hull;
-               }
-               // Unfortunately, by now we will have lost the font-baseline snappoints :-(
-       }
+    _snap_points = selection->getSnapPoints(&m.snapprefs);
+    std::vector<Inkscape::SnapCandidatePoint> snap_points_hull = selection->getSnapPointsConvexHull(&m.snapprefs);
+    if (_snap_points.size() > 200) {
+        /* Snapping a huge number of nodes will take way too long, so limit the number of snappable nodes
+        An average user would rarely ever try to snap such a large number of nodes anyway, because
+        (s)he could hardly discern which node would be snapping */
+        if (prefs->getBool("/options/snapclosestonly/value", false)) {
+            m.keepClosestPointOnly(_snap_points, p);
+        } else {
+            _snap_points = snap_points_hull;
+        }
+        // Unfortunately, by now we will have lost the font-baseline snappoints :-(
+    }
 
     // Find bbox hulling all special points, which excludes stroke width. Here we need to include the
     // path nodes, for example because a rectangle which has been converted to a path doesn't have
     // any other special points
     Geom::Rect snap_points_bbox;
     if ( snap_points_hull.empty() == false ) {
-       std::vector<std::pair<Geom::Point, int> >::iterator i = snap_points_hull.begin();
-        snap_points_bbox = Geom::Rect((*i).first, (*i).first);
+        std::vector<Inkscape::SnapCandidatePoint>::iterator i = snap_points_hull.begin();
+        snap_points_bbox = Geom::Rect((*i).getPoint(), (*i).getPoint());
         i++;
         while (i != snap_points_hull.end()) {
-            snap_points_bbox.expandTo((*i).first);
+            snap_points_bbox.expandTo((*i).getPoint());
             i++;
         }
     }
 
     _bbox_points.clear();
+    _bbox_points_for_translating.clear();
+    // Collect the bounding box's corners and midpoints for each selected item
+    if (m.snapprefs.getSnapModeBBox()) {
+        bool mp = m.snapprefs.getSnapBBoxMidpoints();
+        bool emp = m.snapprefs.getSnapBBoxEdgeMidpoints();
+        // Preferably we'd use the bbox of each selected item, instead of the bbox of the selection as a whole; for translations
+        // this is easy to do, but when snapping the visual bbox while scaling we will have to compensate for the scaling of the
+        // stroke width. (see get_scale_transform_with_stroke()). This however is currently only implemented for a single bbox.
+        // That's why we have both _bbox_points_for_translating and _bbox_points.
+        getBBoxPoints(selection->bounds(_snap_bbox_type), &_bbox_points, false, true, emp, mp);
+        if (((_items.size() > 0) && (_items.size() < 50)) || prefs->getBool("/options/snapclosestonly/value", false)) {
+            // More than 50 items will produce at least 200 bbox points, which might make Inkscape crawl
+            // (see the comment a few lines above). In that case we will use the bbox of the selection as a whole
+            for (unsigned i = 0; i < _items.size(); i++) {
+                getBBoxPoints(_items[i]->getBboxDesktop(_snap_bbox_type), &_bbox_points_for_translating, false, true, emp, mp);
+            }
+        } else {
+            _bbox_points_for_translating = _bbox_points; // use the bbox points of the selection as a whole
+        }
+    }
+
     if (_bbox) {
-       if (m.snapprefs.getSnapModeBBox()) {
-               getBBoxPoints(_bbox, &_bbox_points, false, true, m.snapprefs.getSnapBBoxEdgeMidpoints(), m.snapprefs.getSnapBBoxMidpoints());
-       }
-       // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
+        // There are two separate "opposites" (i.e. opposite w.r.t. the handle being dragged):
         //  - one for snapping the boundingbox, which can be either visual or geometric
         //  - one for snapping the special points
         // The "opposite" in case of a geometric boundingbox always coincides with the "opposite" for the special points
@@ -339,41 +358,51 @@ void Inkscape::SelTrans::grab(Geom::Point const &p, gdouble x, gdouble y, bool s
     // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
     // points immediately.
 
-       if (prefs->getBool("/options/snapclosestonly/value", false)) {
-       if (m.snapprefs.getSnapModeNode()) {
-                       _keepClosestPointOnly(_snap_points, p);
-       } else {
-               _snap_points.clear(); // don't keep any point
-       }
-
-       if (m.snapprefs.getSnapModeBBox()) {
-                       _keepClosestPointOnly(_bbox_points, p);
-               } else {
-                       _bbox_points.clear(); // don't keep any point
-               }
-
-       g_assert(_bbox_points.size() < 2 && _snap_points.size() < 2);
-       if (_snap_points.size() == 1 && _bbox_points.size() == 1) { //both vectors can only have either one or zero elements
-               // So we have exactly one bbox corner and one node left; now find out which is closest and delete the other one
-               if (Geom::L2((_snap_points.at(0)).first - p) < Geom::L2((_bbox_points.at(0)).first - p)) {
-                       _bbox_points.clear();
-               } else {
-                       _snap_points.clear();
-               }
-               }
-
-       // Optionally, show the snap source
-       if (!(_state == STATE_ROTATE && x != 0.5 && y != 0.5)) { // but not when we're draging a rotation handle, because that won't snap
-                       // Now either _bbox_points or _snap_points has a single element, the other one has zero..... or both have zero elements
-                       g_assert((_bbox_points.size() + _snap_points.size()) < 2);
-                       if (m.snapprefs.getSnapEnabledGlobally()) {
-                               if (_bbox_points.size() == 1) {
-                                       _desktop->snapindicator->set_new_snapsource(_bbox_points.at(0));
-                               } else if (_snap_points.size() == 1){
-                                       _desktop->snapindicator->set_new_snapsource(_snap_points.at(0));
-                               }
-                       }
-       }
+    if (prefs->getBool("/options/snapclosestonly/value", false)) {
+        if (m.snapprefs.getSnapModeNode()) {
+            m.keepClosestPointOnly(_snap_points, p);
+        } else {
+            _snap_points.clear(); // don't keep any point
+        }
+
+        if (m.snapprefs.getSnapModeBBox()) {
+            m.keepClosestPointOnly(_bbox_points, p);
+            m.keepClosestPointOnly(_bbox_points_for_translating, p);
+        } else {
+            _bbox_points.clear(); // don't keep any point
+            _bbox_points_for_translating.clear();
+        }
+
+        // Each of the three vectors of snappoints now contains either one snappoint or none at all.
+        if (_snap_points.size() > 1 || _bbox_points.size() > 1 || _bbox_points_for_translating.size() > 1) {
+            g_warning("Incorrect assumption encountered while finding the snap source; nothing serious, but please report to Diederik");
+        }
+
+        // Now let's reduce this to a single closest snappoint
+        Geom::Coord dsp    = _snap_points.size()                 == 1 ? Geom::L2((_snap_points.at(0)).getPoint() - p) : NR_HUGE;
+        Geom::Coord dbbp   = _bbox_points.size()                 == 1 ? Geom::L2((_bbox_points.at(0)).getPoint() - p) : NR_HUGE;
+        Geom::Coord dbbpft = _bbox_points_for_translating.size() == 1 ? Geom::L2((_bbox_points_for_translating.at(0)).getPoint() - p) : NR_HUGE;
+
+        if (translating) {
+            _bbox_points.clear();
+            if (dsp > dbbpft) {
+                _snap_points.clear();
+            } else {
+                _bbox_points_for_translating.clear();
+            }
+        } else {
+            _bbox_points_for_translating.clear();
+            if (dsp > dbbp) {
+                _snap_points.clear();
+            } else {
+                _bbox_points.clear();
+            }
+        }
+
+        if ((_snap_points.size() + _bbox_points.size() + _bbox_points_for_translating.size()) > 1) {
+            g_warning("Checking number of snap sources failed; nothing serious, but please report to Diederik");
+        }
+
     }
 
     if ((x != -1) && (y != -1)) {
@@ -402,7 +431,7 @@ void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point c
         for (unsigned i = 0; i < _items.size(); i++) {
             SPItem &item = *_items[i];
             Geom::Matrix const &prev_transform = _items_affines[i];
-            sp_item_set_i2d_affine(&item, prev_transform * affine);
+            item.set_i2d_affine(prev_transform * affine);
         }
     } else {
         if (_bbox) {
@@ -478,17 +507,17 @@ void Inkscape::SelTrans::ungrab()
         _items_centers.clear();
 
         if (_current_relative_affine.isTranslation()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Move"));
-        } else if (_current_relative_affine.isScale()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Scale"));
-        } else if (_current_relative_affine.isRotation()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Rotate"));
+            DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                               _("Move"));
+        } else if (_current_relative_affine.without_translation().isScale()) {
+            DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                               _("Scale"));
+        } else if (_current_relative_affine.without_translation().isRotation()) {
+            DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                               _("Rotate"));
         } else {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Skew"));
+            DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                               _("Skew"));
         }
 
     } else {
@@ -499,8 +528,8 @@ void Inkscape::SelTrans::ungrab()
                 SPItem *it = (SPItem*)SP_OBJECT(l->data);
                 SP_OBJECT(it)->updateRepr();
             }
-            sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                            _("Set center"));
+            DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                               _("Set center"));
         }
 
         _items.clear();
@@ -557,15 +586,15 @@ void Inkscape::SelTrans::stamp()
 
             Geom::Matrix const *new_affine;
             if (_show == SHOW_OUTLINE) {
-                Geom::Matrix const i2d(sp_item_i2d_affine(original_item));
+                Geom::Matrix const i2d(original_item->i2d_affine());
                 Geom::Matrix const i2dnew( i2d * _current_relative_affine );
-                sp_item_set_i2d_affine(copy_item, i2dnew);
+                copy_item->set_i2d_affine(i2dnew);
                 new_affine = &copy_item->transform;
             } else {
                 new_affine = &original_item->transform;
             }
 
-            sp_item_write_transform(copy_item, copy_repr, *new_affine);
+            copy_item->doWriteTransform(copy_repr, *new_affine);
 
             if ( copy_item->isCenterSet() && _center ) {
                 copy_item->setCenter(*_center * _current_relative_affine);
@@ -574,8 +603,8 @@ void Inkscape::SelTrans::stamp()
             Inkscape::GC::release(copy_repr);
             l = l->next;
         }
-        sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                         _("Stamp"));
+        DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                           _("Stamp"));
     }
 
     if ( fixup && _stamp_cache ) {
@@ -763,8 +792,8 @@ void Inkscape::SelTrans::handleClick(SPKnot */*knot*/, guint state, SPSelTransHa
                     _center_is_set = false;  // center has changed
                     _updateHandles();
                 }
-                sp_document_done (sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                                        _("Reset center"));
+                DocumentUndo::done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
+                                   _("Reset center"));
             }
             break;
         default:
@@ -793,7 +822,7 @@ void Inkscape::SelTrans::handleGrab(SPKnot *knot, guint /*state*/, SPSelTransHan
             break;
     }
 
-    grab(sp_knot_position(knot), handle.x, handle.y, FALSE);
+    grab(sp_knot_position(knot), handle.x, handle.y, FALSE, FALSE);
 }
 
 
@@ -841,7 +870,11 @@ gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position,
     if (handle.request(this, handle, *position, state)) {
         sp_knot_set_position(knot, *position, state);
         SP_CTRL(_grip)->moveto(*position);
-        SP_CTRL(_norm)->moveto(_origin);
+        if (&handle == &handle_center) {
+            SP_CTRL(_norm)->moveto(*position);
+        } else {
+            SP_CTRL(_norm)->moveto(_origin);
+        }
     }
 
     return TRUE;
@@ -953,8 +986,6 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
         m.setup(_desktop, false, _items_const);
 
         Inkscape::SnappedPoint bb, sn;
-        Geom::Coord bd(NR_HUGE);
-        Geom::Coord sd(NR_HUGE);
 
         if ((state & GDK_CONTROL_MASK) || _desktop->isToolboxButtonActive ("lock")) {
             // Scale is locked to a 1:1 aspect ratio, so that s[X] must be made to equal s[Y].
@@ -969,29 +1000,19 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
             }
 
             // Snap along a suitable constraint vector from the origin.
-            bb = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
-            sn = m.constrainedSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
-
-            /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
-            ** just compare difference in s[X].
-            */
-            bd = bb.getSnapped() ? fabs(bb.getTransformation()[Geom::X] - default_scale[Geom::X]) : NR_HUGE;
-            sd = sn.getSnapped() ? fabs(sn.getTransformation()[Geom::X] - geom_scale[Geom::X]) : NR_HUGE;
+            bb = m.constrainedSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
+            sn = m.constrainedSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
         } else {
             /* Scale aspect ratio is unlocked */
-            bb = m.freeSnapScale(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, default_scale, _origin_for_bboxpoints);
-            sn = m.freeSnapScale(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, geom_scale, _origin_for_specpoints);
-
-            /* Pick the snap that puts us closest to the original scale */
-            bd = bb.getSnapped() ? fabs(Geom::L2(bb.getTransformation()) - Geom::L2(Geom::Point(default_scale[Geom::X], default_scale[Geom::Y]))) : NR_HUGE;
-            sd = sn.getSnapped() ? fabs(Geom::L2(sn.getTransformation()) - Geom::L2(Geom::Point(geom_scale[Geom::X], geom_scale[Geom::Y]))) : NR_HUGE;
+            bb = m.freeSnapScale(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
+            sn = m.freeSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
         }
 
         if (!(bb.getSnapped() || sn.getSnapped())) {
             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
             _calcAbsAffineDefault(default_scale);
             _desktop->snapindicator->remove_snaptarget();
-        } else if (bd < sd) {
+        } else if (bb.getSnapped() && !bb.isOtherSnapBetter(sn, false)) {
             // We snapped the bbox (which is either visual or geometric)
             _desktop->snapindicator->set_new_snaptarget(bb);
             default_scale = Geom::Scale(bb.getTransformation());
@@ -1005,6 +1026,7 @@ gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
             geom_scale = Geom::Scale(sn.getTransformation());
             pt = _calcAbsAffineGeom(geom_scale);
         }
+        m.unSetup();
     }
 
     /* Status text */
@@ -1063,22 +1085,18 @@ gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom
 
         Inkscape::SnappedPoint bb, sn;
         g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
-        Geom::Coord bd(NR_HUGE);
-        Geom::Coord sd(NR_HUGE);
 
         bool symmetrical = state & GDK_CONTROL_MASK;
 
-        bb = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
-        sn = m.constrainedSnapStretch(SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
+        bb = m.constrainedSnapStretch(_bbox_points, _point, Geom::Coord(default_scale[axis]), _origin_for_bboxpoints, Geom::Dim2(axis), symmetrical);
+        sn = m.constrainedSnapStretch(_snap_points, _point, Geom::Coord(geom_scale[axis]), _origin_for_specpoints, Geom::Dim2(axis), symmetrical);
 
         if (bb.getSnapped()) {
             // We snapped the bbox (which is either visual or geometric)
-            bd = fabs(bb.getTransformation()[axis] - default_scale[axis]);
             default_scale[axis] = bb.getTransformation()[axis];
         }
 
         if (sn.getSnapped()) {
-            sd = fabs(sn.getTransformation()[axis] - geom_scale[axis]);
             geom_scale[axis] = sn.getTransformation()[axis];
         }
 
@@ -1093,7 +1111,7 @@ gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom
             // We didn't snap at all! Don't update the handle position, just calculate the new transformation
             _calcAbsAffineDefault(default_scale);
             _desktop->snapindicator->remove_snaptarget();
-        } else if (bd < sd) {
+        } else if (bb.getSnapped() && !bb.isOtherSnapBetter(sn, false)) {
             _desktop->snapindicator->set_new_snaptarget(bb);
             // Calculate the new transformation and update the handle position
             pt = _calcAbsAffineDefault(default_scale);
@@ -1104,6 +1122,8 @@ gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom
             // will have to calculate pt taking the stroke width into account
             pt = _calcAbsAffineGeom(geom_scale);
         }
+
+        m.unSetup();
     }
 
     // status text
@@ -1183,10 +1203,10 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P
         SnapManager &m = _desktop->namedview->snap_manager;
         m.setup(_desktop, false, _items_const);
 
-        Inkscape::Snapper::ConstraintLine const constraint(component_vectors[dim_b]);
+        Inkscape::Snapper::SnapConstraint const constraint(component_vectors[dim_b]);
         // When skewing, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapSkew" for details
         Geom::Point const s(skew[dim_a], scale[dim_a]);
-        Inkscape::SnappedPoint sn = m.constrainedSnapSkew(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
+        Inkscape::SnappedPoint sn = m.constrainedSnapSkew(_snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
 
         if (sn.getSnapped()) {
             // We snapped something, so change the skew to reflect it
@@ -1196,6 +1216,8 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::P
         } else {
             _desktop->snapindicator->remove_snaptarget();
         }
+
+        m.unSetup();
     }
 
     // Update the handle position
@@ -1250,7 +1272,10 @@ gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
     if (fabs(h2) < 1e-15) return FALSE;
     Geom::Point q2 = d2 / h2; // normalized new vector to handle
 
-    double radians;
+    Geom::Rotate r1(q1);
+    Geom::Rotate r2(q2);
+
+    double radians = atan2(Geom::dot(Geom::rot90(d1), d2), Geom::dot(d1, d2));;
     if (state & GDK_CONTROL_MASK) {
         // Snap to defined angle increments
         double cos_t = Geom::dot(q1, q2);
@@ -1259,15 +1284,27 @@ gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
         if (snaps) {
             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
         }
-        q1 = Geom::Point(1, 0);
-        q2 = Geom::Point(cos(radians), sin(radians));
+        r1 = Geom::Rotate(0); //q1 = Geom::Point(1, 0);
+        r2 = Geom::Rotate(radians); //q2 = Geom::Point(cos(radians), sin(radians));
     } else {
-        radians = atan2(Geom::dot(Geom::rot90(d1), d2),
-                        Geom::dot(d1, d2));
+        SnapManager &m = _desktop->namedview->snap_manager;
+        m.setup(_desktop, false, _items_const);
+        // When rotating, we cannot snap the corners of the bounding box, see the comment in "constrainedSnapRotate" for details
+        Inkscape::SnappedPoint sn = m.constrainedSnapRotate(_snap_points, _point, radians, _origin);
+        m.unSetup();
+
+        if (sn.getSnapped()) {
+            _desktop->snapindicator->set_new_snaptarget(sn);
+            // We snapped something, so change the rotation to reflect it
+            radians = sn.getTransformation()[0];
+            r1 = Geom::Rotate(0);
+            r2 = Geom::Rotate(radians);
+        } else {
+            _desktop->snapindicator->remove_snaptarget();
+        }
+
     }
 
-    Geom::Rotate const r1(q1);
-    Geom::Rotate const r2(q2);
 
     // Calculate the relative affine
     _relative_affine = r2 * r1.inverse();
@@ -1288,37 +1325,30 @@ gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
 // Move the item's transformation center
 gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
 {
+    // When dragging the transformation center while multiple items have been selected, then those
+    // items will share a single center. While dragging that single center, it should never snap to the
+    // centers of any of the selected objects. Therefore we will have to pass the list of selected items
+    // to the snapper, to avoid self-snapping of the rotation center
+    GSList *items = (GSList *) const_cast<Selection *>(_selection)->itemList();
     SnapManager &m = _desktop->namedview->snap_manager;
     m.setup(_desktop);
-    m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, pt, Inkscape::SNAPSOURCE_HANDLE);
-
-    if (state & GDK_CONTROL_MASK) {
-        if ( fabs(_point[Geom::X] - pt[Geom::X]) > fabs(_point[Geom::Y] - pt[Geom::Y]) ) {
-            pt[Geom::Y] = _point[Geom::Y];
-        } else {
-            pt[Geom::X] = _point[Geom::X];
-        }
+    m.setRotationCenterSource(items);
+
+    if (state & GDK_CONTROL_MASK) { // with Ctrl, constrain to axes
+        std::vector<Inkscape::Snapper::SnapConstraint> constraints;
+        constraints.push_back(Inkscape::Snapper::SnapConstraint(_point, Geom::Point(1, 0)));
+        constraints.push_back(Inkscape::Snapper::SnapConstraint(_point, Geom::Point(0, 1)));
+        Inkscape::SnappedPoint sp = m.multipleConstrainedSnaps(Inkscape::SnapCandidatePoint(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER), constraints, state & GDK_SHIFT_MASK);
+        pt = sp.getPoint();
     }
-
-    if ( !(state & GDK_SHIFT_MASK) && _bbox ) {
-        // screen pixels to snap center to bbox
-#define SNAP_DIST 5
-        // FIXME: take from prefs
-        double snap_dist = SNAP_DIST / _desktop->current_zoom();
-
-        for (int i = 0; i < 2; i++) {
-            if (fabs(pt[i] - _bbox->min()[i]) < snap_dist) {
-                pt[i] = _bbox->min()[i];
-            }
-            if (fabs(pt[i] - _bbox->midpoint()[i]) < snap_dist) {
-                pt[i] = _bbox->midpoint()[i];
-            }
-            if (fabs(pt[i] - _bbox->max()[i]) < snap_dist) {
-                pt[i] = _bbox->max()[i];
-            }
+    else {
+        if (!(state & GDK_SHIFT_MASK)) { // Shift disables snapping
+            m.freeSnapReturnByRef(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER);
         }
     }
 
+    m.unSetup();
+
     // status text
     GString *xs = SP_PX_TO_METRIC_STRING(pt[Geom::X], _desktop->namedview->getDefaultMetric());
     GString *ys = SP_PX_TO_METRIC_STRING(pt[Geom::Y], _desktop->namedview->getDefaultMetric());
@@ -1393,21 +1423,26 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
 
     if (alt) {
 
-        /* Alt pressed means keep offset: snap the moved distance to the grid.
-        ** FIXME: this will snap to more than just the grid, nowadays.
-        */
-
-       m.setup(_desktop, true, _items_const);
-       m.freeSnapReturnByRef(SnapPreferences::SNAPPOINT_NODE, dxy, Inkscape::SNAPSOURCE_UNDEFINED);
+        // Alt pressed means: move only by integer multiples of the grid spacing
 
+        if (control) { // ... if also constrained to the orthogonal axes
+            if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
+                dxy[Geom::Y] = 0;
+            } else {
+                dxy[Geom::X] = 0;
+            }
+        }
+        m.setup(_desktop, true, _items_const);
+        dxy = m.multipleOfGridPitch(dxy, _point);
+        m.unSetup();
     } else if (shift) {
-       if (control) { // shift & control: constrained movement without snapping
-               if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
-                               dxy[Geom::Y] = 0;
-                       } else {
-                               dxy[Geom::X] = 0;
-                       }
-       }
+        if (control) { // shift & control: constrained movement without snapping
+            if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
+                dxy[Geom::Y] = 0;
+            } else {
+                dxy[Geom::X] = 0;
+            }
+        }
     } else { //!shift: with snapping
 
         /* We're snapping to things, possibly with a constraint to horizontal or
@@ -1415,9 +1450,9 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
         ** pick the smallest.
         */
 
-       m.setup(_desktop, false, _items_const);
+        m.setup(_desktop, false, _items_const);
 
-       /* This will be our list of possible translations */
+        /* This will be our list of possible translations */
         std::list<Inkscape::SnappedPoint> s;
 
         if (control) { // constrained movement with snapping
@@ -1425,37 +1460,36 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
             /* Snap to things, and also constrain to horizontal or vertical movement */
 
             unsigned int dim = fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y]) ? Geom::X : Geom::Y;
-                       // When doing a constrained translation, all points will move in the same direction, i.e.
-                       // either horizontally or vertically. Therefore we only have to specify the direction of
-                       // the constraint-line once. The constraint lines are parallel, but might not be colinear.
-                       // Therefore we will have to set the point through which the constraint-line runs
-                       // individually for each point to be snapped; this will be handled however by _snapTransformed()
-                       s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX,
-                                                                                                        _bbox_points,
-                                                                                                        _point,
-                                                                                                        Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
-                                                                                                        dxy));
-
-                       s.push_back(m.constrainedSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE,
-                                                                                                        _snap_points,
-                                                                                                        _point,
-                                                                                                        Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
-                                                                                                        dxy));
+            // When doing a constrained translation, all points will move in the same direction, i.e.
+            // either horizontally or vertically. Therefore we only have to specify the direction of
+            // the constraint-line once. The constraint lines are parallel, but might not be colinear.
+            // Therefore we will have to set the point through which the constraint-line runs
+            // individually for each point to be snapped; this will be handled however by _snapTransformed()
+            s.push_back(m.constrainedSnapTranslate(_bbox_points_for_translating,
+                                                     _point,
+                                                     Inkscape::Snapper::SnapConstraint(component_vectors[dim]),
+                                                     dxy));
+
+            s.push_back(m.constrainedSnapTranslate(_snap_points,
+                                                     _point,
+                                                     Inkscape::Snapper::SnapConstraint(component_vectors[dim]),
+                                                     dxy));
         } else { // !control
 
             // Let's leave this timer code here for a while. I'll probably need it in the near future (Diederik van Lierop)
             /* GTimeVal starttime;
             GTimeVal endtime;
-               g_get_current_time(&starttime); */
+            g_get_current_time(&starttime); */
 
             /* Snap to things with no constraint */
-               s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_BBOX, _bbox_points, _point, dxy));
-               s.push_back(m.freeSnapTranslation(Inkscape::SnapPreferences::SNAPPOINT_NODE, _snap_points, _point, dxy));
+            s.push_back(m.freeSnapTranslate(_bbox_points_for_translating, _point, dxy));
+            s.push_back(m.freeSnapTranslate(_snap_points, _point, dxy));
 
-               /*g_get_current_time(&endtime);
-               double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
-               std::cout << "Time spent snapping: " << elapsed << std::endl; */
+              /*g_get_current_time(&endtime);
+              double elapsed = ((((double)endtime.tv_sec - starttime.tv_sec) * G_USEC_PER_SEC + (endtime.tv_usec - starttime.tv_usec))) / 1000.0;
+              std::cout << "Time spent snapping: " << elapsed << std::endl; */
         }
+        m.unSetup();
 
         /* Pick one */
         Inkscape::SnappedPoint best_snapped_point;
@@ -1467,6 +1501,7 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
                 }
             }
         }
+
         if (best_snapped_point.getSnapped()) {
             _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
         } else {
@@ -1475,7 +1510,7 @@ void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
             if (control) {
                 // If we didn't snap, then we should still constrain horizontally or vertically
                 // (When we did snap, then this constraint has already been enforced by
-                // calling constrainedSnapTranslation() above)
+                // calling constrainedSnapTranslate() above)
                 if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
                     dxy[Geom::Y] = 0;
                 } else {
@@ -1584,29 +1619,17 @@ Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
 
     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
     bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
-    Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
-
-    // return the new handle position
-    return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
-}
-
-void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<std::pair<Geom::Point, int> > &points, const Geom::Point &reference)
-{
-       if (points.size() < 2) return;
-
-       std::pair<Geom::Point, int> closest_point = std::make_pair(Geom::Point(NR_HUGE, NR_HUGE), SNAPSOURCE_UNDEFINED);
-       Geom::Coord closest_dist = NR_HUGE;
-
-       for(std::vector<std::pair<Geom::Point, int> >::const_iterator i = points.begin(); i != points.end(); i++) {
-               Geom::Coord dist = Geom::L2((*i).first - reference);
-               if (i == points.begin() || dist < closest_dist) {
-                       closest_point = *i;
-                       closest_dist = dist;
-               }
+    if (_geometric_bbox) {
+        Geom::Rect visual_bbox = get_visual_bbox(_geometric_bbox, _absolute_affine, _strokewidth, transform_stroke);
+        // return the new handle position
+        return visual_bbox.min() + visual_bbox.dimensions() * Geom::Scale(_handle_x, _handle_y);
     }
 
-       points.clear();
-       points.push_back(closest_point);
+    // Fall back scenario, in case we don't have a geometric bounding box at hand;
+    // (Due to some bugs related to bounding boxes having at least one zero dimension; For more details
+    // see https://bugs.launchpad.net/inkscape/+bug/318726)
+    g_warning("No geometric bounding box has been calculated; this is a bug that needs fixing!");
+    return _calcAbsAffineDefault(geom_scale); // this is bogus, but we must return _something_
 }
 
 /*
@@ -1618,4 +1641,4 @@ void Inkscape::SelTrans::_keepClosestPointOnly(std::vector<std::pair<Geom::Point
   fill-column:99
   End:
 */
-// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :