Code

Node tool: snap while scaling a selection of nodes. Consider this as experimental...
[inkscape.git] / src / seltrans.cpp
index a3f34384107f93300bf100471b2dcdb57dc09d0f..b1d184986da06c3d2b7248c8a211beea641b5bcc 100644 (file)
@@ -1,14 +1,15 @@
-#define __SELTRANS_C__
-
-/*
- * Helper object for transforming selected items
- *
- * Author:
+/** @file
+ * @brief Helper object for transforming selected items
+ */
+/* Authors:
  *   Lauris Kaplinski <lauris@kaplinski.com>
  *   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
  *
  * Released under GNU GPL, read the file 'COPYING' for more information
  */
 #ifdef HAVE_CONFIG_H
 # include <config.h>
 #endif
+#include <cstring>
+#include <string>
 
-#include <libnr/nr-matrix-ops.h>
-#include <libnr/nr-matrix-translate-ops.h>
-#include <libnr/nr-rotate-ops.h>
-#include <libnr/nr-scale-ops.h>
-#include <libnr/nr-translate-matrix-ops.h>
-#include <libnr/nr-translate-ops.h>
+#include <2geom/transforms.h>
 #include <gdk/gdkkeysyms.h>
 #include "document.h"
 #include "sp-namedview.h"
 #include "verbs.h"
 #include <glibmm/i18n.h>
 #include "display/sp-ctrlline.h"
-#include "prefs-utils.h"
+#include "preferences.h"
 #include "xml/repr.h"
+#include "mod360.h"
+#include <2geom/angle.h>
+#include "display/snap-indicator.h"
 
-#include "isnan.h" //temp fix.  make sure included last
+using Inkscape::DocumentUndo;
 
 static void sp_remove_handles(SPKnot *knot[], gint num);
 
 static void sp_sel_trans_handle_grab(SPKnot *knot, guint state, gpointer data);
 static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint state, gpointer data);
 static void sp_sel_trans_handle_click(SPKnot *knot, guint state, gpointer data);
-static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint32 state, gpointer data);
-static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *p, guint state, gboolean *data);
+static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint32 state, gpointer data);
+static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *p, guint state, gboolean *data);
 
 extern GdkPixbuf *handles[];
 
@@ -88,14 +89,22 @@ Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
     _show(SHOW_CONTENT),
     _grabbed(false),
     _show_handles(true),
-    _bbox(NR::Nothing()),
-    _approximate_bbox(NR::Nothing()),
+    _bbox(),
+    _approximate_bbox(),
+    _absolute_affine(Geom::Scale(1,1)),
+    _opposite(Geom::Point(0,0)),
+    _opposite_for_specpoints(Geom::Point(0,0)),
+    _opposite_for_bboxpoints(Geom::Point(0,0)),
+    _origin_for_specpoints(Geom::Point(0,0)),
+    _origin_for_bboxpoints(Geom::Point(0,0)),
     _chandle(NULL),
     _stamp_cache(NULL),
     _message_context(desktop->messageStack())
 {
-    gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
-    _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    int prefs_bbox = prefs->getBool("/tools/bounding_box");
+    _snap_bbox_type = !prefs_bbox ?
+        SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
 
     g_return_if_fail(desktop != NULL);
 
@@ -105,7 +114,7 @@ Inkscape::SelTrans::SelTrans(SPDesktop *desktop) :
     }
 
     _updateVolatileState();
-    _current.set_identity();
+    _current_relative_affine.setIdentity();
 
     _center_is_set = false; // reread _center from items, or set to bbox midpoint
 
@@ -192,10 +201,12 @@ Inkscape::SelTrans::~SelTrans()
     }
 
     for (unsigned i = 0; i < _items.size(); i++) {
-        sp_object_unref(SP_OBJECT(_items[i].first), NULL);
+        sp_object_unref(SP_OBJECT(_items[i]), NULL);
     }
 
     _items.clear();
+    _items_const.clear();
+    _items_affines.clear();
     _items_centers.clear();
 }
 
@@ -217,7 +228,7 @@ void Inkscape::SelTrans::increaseState()
     _updateHandles();
 }
 
-void Inkscape::SelTrans::setCenter(NR::Point const &p)
+void Inkscape::SelTrans::setCenter(Geom::Point const &p)
 {
     _center = p;
     _center_is_set = true;
@@ -232,16 +243,19 @@ void Inkscape::SelTrans::setCenter(NR::Point const &p)
     _updateHandles();
 }
 
-void Inkscape::SelTrans::grab(NR::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();
 
     g_return_if_fail(!_grabbed);
 
     _grabbed = true;
     _show_handles = show_handles;
     _updateVolatileState();
-    _current.set_identity();
+    _current_relative_affine.setIdentity();
 
     _changed = false;
 
@@ -250,79 +264,146 @@ void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool sho
     }
 
     for (GSList const *l = selection->itemList(); l; l = l->next) {
-        SPItem *it = (SPItem*)sp_object_ref(SP_OBJECT(l->data), NULL);
-        _items.push_back(std::pair<SPItem *, NR::Matrix>(it, sp_item_i2d_affine(it)));
-        _items_centers.push_back(std::pair<SPItem *, NR::Point>(it, it->getCenter())); // for content-dragging, we need to remember original centers
+        SPItem *it = (SPItem *)sp_object_ref(SP_OBJECT(l->data), NULL);
+        _items.push_back(it);
+        _items_const.push_back(it);
+        _items_affines.push_back(it->i2d_affine());
+        _items_centers.push_back(it->getCenter()); // for content-dragging, we need to remember original centers
     }
 
-    _current.set_identity();
-
-    _point = p;
+    _handle_x = x;
+    _handle_y = y;
 
     // 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);
+    } else {
+        _point_geom = p;
+    }
 
     // Next, get all points to consider for snapping
     SnapManager const &m = _desktop->namedview->snap_manager;
-    _snap_points = selection->getSnapPoints(m.getIncludeItemCenter());
-    std::vector<NR::Point> snap_points_hull = selection->getSnapPointsConvexHull();
-    if (_snap_points.size() > 100) {
+    _snap_points.clear();
+    _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 */
-        _snap_points = snap_points_hull;
+        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
-    NR::Rect snap_points_bbox;
+    Geom::Rect snap_points_bbox;
     if ( snap_points_hull.empty() == false ) {
-        std::vector<NR::Point>::iterator i = snap_points_hull.begin();
-        snap_points_bbox = NR::Rect(*i, *i);
+        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);
+            snap_points_bbox.expandTo((*i).getPoint());
             i++;
         }
     }
 
     _bbox_points.clear();
-    if (_bbox) {
-        // ... and add the bbox corners to _bbox_points
-        for ( unsigned i = 0 ; i < 4 ; i++ ) {
-            _bbox_points.push_back(_bbox->corner(i));
+    _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) {
         // 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
-        // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #1540195 (in which
-        // a box is caught between to guides)
-        _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * NR::scale(1-x, 1-y);
-        _opposite_for_specpoints = (snap_points_bbox.min() + (snap_points_bbox.dimensions() * NR::scale(1-x, 1-y) ) );
-        // Only a single "opposite" can be used in calculating transformations.
+        // These distinct "opposites" are needed in the snapmanager to avoid bugs such as #sf1540195 (in which
+        // a box is caught between two guides)
+        _opposite_for_bboxpoints = _bbox->min() + _bbox->dimensions() * Geom::Scale(1-x, 1-y);
+        _opposite_for_specpoints = snap_points_bbox.min() + snap_points_bbox.dimensions() * Geom::Scale(1-x, 1-y);
         _opposite = _opposite_for_bboxpoints;
     }
 
-    // The lines below are usefull for debugging any snapping issues, as they'll spit out all points that are considered for snapping
+    // When snapping the node closest to the mouse pointer is absolutely preferred over the closest snap
+    // (i.e. when weight == 1), then we will not even try to snap to other points and discard those other
+    // points immediately.
 
-    /*std::cout << "Number of snap points:  " << _snap_points.size() << std::endl;
-    for (std::vector<NR::Point>::const_iterator i = _snap_points.begin(); i != _snap_points.end(); i++)
-    {
-        std::cout << "    " << *i << std::endl;
-    }
+    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
+        }
 
-    std::cout << "Number of bbox points:  " << _bbox_points.size() << std::endl;
-    for (std::vector<NR::Point>::const_iterator i = _bbox_points.begin(); i != _bbox_points.end(); i++)
-    {
-        std::cout << "    " << *i << std::endl;
-    }*/
+        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)) {
         sp_canvas_item_show(_norm);
@@ -338,23 +419,23 @@ void Inkscape::SelTrans::grab(NR::Point const &p, gdouble x, gdouble y, bool sho
     g_return_if_fail(_stamp_cache == NULL);
 }
 
-void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const &norm)
+void Inkscape::SelTrans::transform(Geom::Matrix const &rel_affine, Geom::Point const &norm)
 {
     g_return_if_fail(_grabbed);
     g_return_if_fail(!_empty);
 
-    NR::Matrix const affine( NR::translate(-norm) * rel_affine * NR::translate(norm) );
+    Geom::Matrix const affine( Geom::Translate(-norm) * rel_affine * Geom::Translate(norm) );
 
     if (_show == SHOW_CONTENT) {
         // update the content
         for (unsigned i = 0; i < _items.size(); i++) {
-            SPItem &item = *_items[i].first;
-            NR::Matrix const &prev_transform = _items[i].second;
-            sp_item_set_i2d_affine(&item, prev_transform * affine);
+            SPItem &item = *_items[i];
+            Geom::Matrix const &prev_transform = _items_affines[i];
+            item.set_i2d_affine(prev_transform * affine);
         }
     } else {
         if (_bbox) {
-            NR::Point p[4];
+            Geom::Point p[4];
             /* update the outline */
             for (unsigned i = 0 ; i < 4 ; i++) {
                 p[i] = _bbox->corner(i) * affine;
@@ -365,7 +446,7 @@ void Inkscape::SelTrans::transform(NR::Matrix const &rel_affine, NR::Point const
         }
     }
 
-    _current = affine;
+    _current_relative_affine = affine;
     _changed = true;
     _updateHandles();
 }
@@ -376,11 +457,13 @@ void Inkscape::SelTrans::ungrab()
     _grabbed = false;
     _show_handles = true;
 
+    _desktop->snapindicator->remove_snapsource();
+
     Inkscape::Selection *selection = sp_desktop_selection(_desktop);
     _updateVolatileState();
 
     for (unsigned i = 0; i < _items.size(); i++) {
-        sp_object_unref(SP_OBJECT(_items[i].first), NULL);
+        sp_object_unref(SP_OBJECT(_items[i]), NULL);
     }
 
     sp_canvas_item_hide(_norm);
@@ -399,40 +482,42 @@ void Inkscape::SelTrans::ungrab()
     _message_context.clear();
 
     if (!_empty && _changed) {
-        sp_selection_apply_affine(selection, _current, (_show == SHOW_OUTLINE)? true : false);
+        sp_selection_apply_affine(selection, _current_relative_affine, (_show == SHOW_OUTLINE)? true : false);
         if (_center) {
-            *_center *= _current;
+            *_center *= _current_relative_affine;
             _center_is_set = true;
         }
 
 // If dragging showed content live, sp_selection_apply_affine cannot change the centers
 // appropriately - it does not know the original positions of the centers (all objects already have
 // the new bboxes). So we need to reset the centers from our saved array.
-        if (_show != SHOW_OUTLINE && !_current.is_translation()) {
+        if (_show != SHOW_OUTLINE && !_current_relative_affine.isTranslation()) {
             for (unsigned i = 0; i < _items_centers.size(); i++) {
-                SPItem *currentItem = _items_centers[i].first;
+                SPItem *currentItem = _items[i];
                 if (currentItem->isCenterSet()) { // only if it's already set
-                    currentItem->setCenter (_items_centers[i].second * _current);
+                    currentItem->setCenter (_items_centers[i] * _current_relative_affine);
                     SP_OBJECT(currentItem)->updateRepr();
                 }
             }
         }
 
         _items.clear();
+        _items_const.clear();
+        _items_affines.clear();
         _items_centers.clear();
 
-        if (_current.is_translation()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Move"));
-        } else if (_current.is_scale()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Scale"));
-        } else if (_current.is_rotation()) {
-            sp_document_done(sp_desktop_document(_desktop), SP_VERB_CONTEXT_SELECT,
-                             _("Rotate"));
+        if (_current_relative_affine.isTranslation()) {
+            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 {
@@ -443,11 +528,13 @@ 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();
+        _items_const.clear();
+        _items_affines.clear();
         _items_centers.clear();
         _updateHandles();
     }
@@ -497,27 +584,27 @@ void Inkscape::SelTrans::stamp()
 
             SPItem *copy_item = (SPItem *) sp_desktop_document(_desktop)->getObjectByRepr(copy_repr);
 
-            NR::Matrix const *new_affine;
+            Geom::Matrix const *new_affine;
             if (_show == SHOW_OUTLINE) {
-                NR::Matrix const i2d(sp_item_i2d_affine(original_item));
-                NR::Matrix const i2dnew( i2d * _current );
-                sp_item_set_i2d_affine(copy_item, i2dnew);
+                Geom::Matrix const i2d(original_item->i2d_affine());
+                Geom::Matrix const i2dnew( i2d * _current_relative_affine );
+                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);
+                copy_item->setCenter(*_center * _current_relative_affine);
             }
 
             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 ) {
@@ -584,7 +671,7 @@ void Inkscape::SelTrans::_updateHandles()
         sp_knot_hide(_chandle);
     } else {
         sp_knot_show(_chandle);
-        sp_knot_moveto(_chandle, &*_center);
+        sp_knot_moveto(_chandle, *_center);
     }
 }
 
@@ -648,14 +735,14 @@ void Inkscape::SelTrans::_showHandles(SPKnot *knot[], SPSelTransHandle const han
         }
         sp_knot_show(knot[i]);
 
-        NR::Point const handle_pt(handle[i].x, handle[i].y);
+        Geom::Point const handle_pt(handle[i].x, handle[i].y);
         // shouldn't have nullary bbox, but knots
         g_assert(_bbox);
-        NR::Point p( _bbox->min()
+        Geom::Point p( _bbox->min()
                      + ( _bbox->dimensions()
-                         * NR::scale(handle_pt) ) );
+                         * Geom::Scale(handle_pt) ) );
 
-        sp_knot_moveto(knot[i], &p);
+        sp_knot_moveto(knot[i], p);
     }
 }
 
@@ -671,14 +758,14 @@ static void sp_sel_trans_handle_ungrab(SPKnot *knot, guint /*state*/, gpointer /
     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->ungrab();
 }
 
-static void sp_sel_trans_handle_new_event(SPKnot *knot, NR::Point *position, guint state, gpointer data)
+static void sp_sel_trans_handle_new_event(SPKnot *knot, Geom::Point *position, guint state, gpointer data)
 {
     SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleNewEvent(
         knot, position, state, *(SPSelTransHandle const *) data
         );
 }
 
-static gboolean sp_sel_trans_handle_request(SPKnot *knot, NR::Point *position, guint state, gboolean *data)
+static gboolean sp_sel_trans_handle_request(SPKnot *knot, Geom::Point *position, guint state, gboolean *data)
 {
     return SP_SELECT_CONTEXT(knot->desktop->event_context)->_seltrans->handleRequest(
         knot, position, state, *(SPSelTransHandle const *) data
@@ -705,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:
@@ -735,11 +822,11 @@ 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);
 }
 
 
-void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
+void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
 {
     if (!SP_KNOT_IS_GRABBED(knot)) {
         return;
@@ -748,7 +835,7 @@ void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint
     // in case items have been unhooked from the document, don't
     // try to continue processing events for them.
     for (unsigned int i = 0; i < _items.size(); i++) {
-        if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i].first)) ) {
+        if (!SP_OBJECT_DOCUMENT(SP_OBJECT(_items[i])) ) {
             return;
         }
     }
@@ -757,7 +844,7 @@ void Inkscape::SelTrans::handleNewEvent(SPKnot *knot, NR::Point *position, guint
 }
 
 
-gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, guint state, SPSelTransHandle const &handle)
+gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, Geom::Point *position, guint state, SPSelTransHandle const &handle)
 {
     if (!SP_KNOT_IS_GRABBED(knot)) {
         return TRUE;
@@ -765,6 +852,9 @@ gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, gu
 
     knot->desktop->setPosition(*position);
 
+    // When holding shift while rotating or skewing, the transformation will be
+    // relative to the point opposite of the handle; otherwise it will be relative
+    // to the center as set for the selection
     if ((!(state & GDK_SHIFT_MASK) == !(_state == STATE_ROTATE)) && (&handle != &handle_center)) {
         _origin = _opposite;
         _origin_for_bboxpoints = _opposite_for_bboxpoints;
@@ -778,9 +868,13 @@ gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, gu
         return TRUE;
     }
     if (handle.request(this, handle, *position, state)) {
-        sp_knot_set_position(knot, 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;
@@ -790,13 +884,15 @@ gboolean Inkscape::SelTrans::handleRequest(SPKnot *knot, NR::Point *position, gu
 void Inkscape::SelTrans::_selChanged(Inkscape::Selection */*selection*/)
 {
     if (!_grabbed) {
+        Inkscape::Preferences *prefs = Inkscape::Preferences::get();
         // reread in case it changed on the fly:
-        gchar const *prefs_bbox = prefs_get_string_attribute("tools", "bounding_box");
-        _snap_bbox_type = (prefs_bbox != NULL && strcmp(prefs_bbox, "geometric")==0)? SPItem::GEOMETRIC_BBOX : SPItem::APPROXIMATE_BBOX;
+        int prefs_bbox = prefs->getBool("/tools/bounding_box");
+         _snap_bbox_type = !prefs_bbox ?
+            SPItem::APPROXIMATE_BBOX : SPItem::GEOMETRIC_BBOX;
         //SPItem::APPROXIMATE_BBOX will be replaced by SPItem::VISUAL_BBOX, as soon as the latter is implemented properly
 
         _updateVolatileState();
-        _current.set_identity();
+        _current_relative_affine.setIdentity();
         _center_is_set = false; // center(s) may have changed
         _updateHandles();
     }
@@ -806,7 +902,7 @@ void Inkscape::SelTrans::_selModified(Inkscape::Selection */*selection*/, guint
 {
     if (!_grabbed) {
         _updateVolatileState();
-        _current.set_identity();
+        _current_relative_affine.setIdentity();
 
         // reset internal flag
         _changed = false;
@@ -830,363 +926,320 @@ static double sign(double const x)
 }
 
 gboolean sp_sel_trans_scale_request(Inkscape::SelTrans *seltrans,
-                                    SPSelTransHandle const &, NR::Point &pt, guint state)
+                                    SPSelTransHandle const &, Geom::Point &pt, guint state)
 {
     return seltrans->scaleRequest(pt, state);
 }
 
 gboolean sp_sel_trans_stretch_request(Inkscape::SelTrans *seltrans,
-                                      SPSelTransHandle const &handle, NR::Point &pt, guint state)
+                                      SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
     return seltrans->stretchRequest(handle, pt, state);
 }
 
 gboolean sp_sel_trans_skew_request(Inkscape::SelTrans *seltrans,
-                                   SPSelTransHandle const &handle, NR::Point &pt, guint state)
+                                   SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
     return seltrans->skewRequest(handle, pt, state);
 }
 
 gboolean sp_sel_trans_rotate_request(Inkscape::SelTrans *seltrans,
-                                     SPSelTransHandle const &, NR::Point &pt, guint state)
+                                     SPSelTransHandle const &, Geom::Point &pt, guint state)
 {
     return seltrans->rotateRequest(pt, state);
 }
 
 gboolean sp_sel_trans_center_request(Inkscape::SelTrans *seltrans,
-                                     SPSelTransHandle const &, NR::Point &pt, guint state)
+                                     SPSelTransHandle const &, Geom::Point &pt, guint state)
 {
     return seltrans->centerRequest(pt, state);
 }
 
-gboolean Inkscape::SelTrans::scaleRequest(NR::Point &pt, guint state)
+gboolean Inkscape::SelTrans::scaleRequest(Geom::Point &pt, guint state)
 {
-    using NR::X;
-    using NR::Y;
 
-    NR::Point d = _point - _origin;
-    NR::scale s(0, 0);
+    // Calculate the scale factors, which can be either visual or geometric
+    // depending on which type of bbox is currently being used (see preferences -> selector tool)
+    Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
 
-    /* Work out the new scale factors `s' */
-    for ( unsigned int i = 0 ; i < 2 ; i++ ) {
-        if ( fabs(d[i]) > 0.001 ) {
-            s[i] = ( pt[i] - _origin[i] ) / d[i];
-            if ( fabs(s[i]) < 1e-9 ) {
-                s[i] = 1e-9;
-            }
-        }
-    }
+    // Find the scale factors for the geometric bbox
+    Geom::Point pt_geom = _getGeomHandlePos(pt);
+    Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
+
+    _absolute_affine = Geom::identity(); //Initialize the scaler
 
     if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
+        // We're scaling either the visual or the geometric bbox here (see the comment above)
         for ( unsigned int i = 0 ; i < 2 ; i++ ) {
-            if (fabs(s[i]) > 1)
-                s[i] = round(s[i]);
-            else
-                s[i] = 1/round(1/(MIN(s[i], 10)));
+            if (fabs(default_scale[i]) > 1) {
+                default_scale[i] = round(default_scale[i]);
+            } else if (default_scale[i] != 0) {
+                default_scale[i] = 1/round(1/(MIN(default_scale[i], 10)));
+            }
         }
-    }
-
-    SnapManager const &m = _desktop->namedview->snap_manager;
-
-    /* Get a STL list of the selected items.
-    ** FIXME: this should probably be done by Inkscape::Selection.
-    */
-    std::list<SPItem const*> it;
-    for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
-        it.push_back(reinterpret_cast<SPItem*>(i->data));
-    }
-
-    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].
-        //
-        // The aspect-ratio must be locked before snapping
-        if (fabs(s[NR::X]) > fabs(s[NR::Y])) {
-                s[NR::X] = fabs(s[NR::Y]) * sign(s[NR::X]);
+        // Update the knot position
+        pt = _calcAbsAffineDefault(default_scale);
+        // When scaling by an integer, snapping is not needed
+    } else {
+        // In all other cases we should try to snap now
+        SnapManager &m = _desktop->namedview->snap_manager;
+        m.setup(_desktop, false, _items_const);
+
+        Inkscape::SnappedPoint bb, sn;
+
+        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].
+            //
+            // The aspect-ratio must be locked before snapping
+            if (fabs(default_scale[Geom::X]) > fabs(default_scale[Geom::Y])) {
+                default_scale[Geom::X] = fabs(default_scale[Geom::Y]) * sign(default_scale[Geom::X]);
+                geom_scale[Geom::X] = fabs(geom_scale[Geom::Y]) * sign(geom_scale[Geom::X]);
             } else {
-                s[NR::Y] = fabs(s[NR::X]) * sign(s[NR::Y]);
+                default_scale[Geom::Y] = fabs(default_scale[Geom::X]) * sign(default_scale[Geom::Y]);
+                geom_scale[Geom::Y] = fabs(geom_scale[Geom::X]) * sign(geom_scale[Geom::Y]);
             }
 
-        // Snap along a suitable constraint vector from the origin.
-        std::pair<NR::scale, bool> bb = m.constrainedSnapScale(Snapper::SNAPPOINT_BBOX,
-                                                               _bbox_points,
-                                                               it,
-                                                               s,
-                                                               _origin_for_bboxpoints);
-
-        std::pair<NR::scale, bool> sn = m.constrainedSnapScale(Snapper::SNAPPOINT_NODE,
-                                                               _snap_points,
-                                                               it,
-                                                               s,
-                                                               _origin_for_specpoints);
-
-        if (bb.second || sn.second) { // If we snapped to something
-            /* Choose the smaller difference in scale.  Since s[X] == s[Y] we can
-            ** just compare difference in s[X].
-            */
-            double const bd = bb.second ? fabs(bb.first[NR::X] - s[NR::X]) : NR_HUGE;
-            double const sd = sn.second ? fabs(sn.first[NR::X] - s[NR::X]) : NR_HUGE;
-            s = (bd < sd) ? bb.first : sn.first;
+            // Snap along a suitable constraint vector from the origin.
+            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(_bbox_points, _point, default_scale, _origin_for_bboxpoints);
+            sn = m.freeSnapScale(_snap_points, _point, geom_scale, _origin_for_specpoints);
         }
 
-    } else {
-        /* Scale aspect ratio is unlocked */
-
-        std::pair<NR::scale, bool> bb = m.freeSnapScale(Snapper::SNAPPOINT_BBOX,
-                                                        _bbox_points,
-                                                        it,
-                                                        s,
-                                                        _origin_for_bboxpoints);
-        std::pair<NR::scale, bool> sn = m.freeSnapScale(Snapper::SNAPPOINT_NODE,
-                                                        _snap_points,
-                                                        it,
-                                                        s,
-                                                        _origin_for_specpoints);
-
-        if (bb.second || sn.second) { // If we snapped to something
-            /* Pick the snap that puts us closest to the original scale */
-            NR::Coord bd = bb.second ?
-                fabs(NR::L2(NR::Point(bb.first[NR::X], bb.first[NR::Y])) -
-                     NR::L2(NR::Point(s[NR::X], s[NR::Y])))
-                : NR_HUGE;
-            NR::Coord sd = sn.second ?
-                fabs(NR::L2(NR::Point(sn.first[NR::X], sn.first[NR::Y])) -
-                     NR::L2(NR::Point(s[NR::X], s[NR::Y])))
-                : NR_HUGE;
-            s = (bd < sd) ? bb.first : sn.first;
+        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 (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());
+            // Calculate the new transformation and update the handle position
+            pt = _calcAbsAffineDefault(default_scale);
+        } else {
+            _desktop->snapindicator->set_new_snaptarget(sn);
+            // We snapped the special points (e.g. nodes), which are not at the visual bbox
+            // The handle location however (pt) might however be at the visual bbox, so we
+            // will have to calculate pt taking the stroke width into account
+            geom_scale = Geom::Scale(sn.getTransformation());
+            pt = _calcAbsAffineGeom(geom_scale);
         }
+        m.unSetup();
     }
 
-    /* Update the knot position */
-    pt = ( _point - _origin ) * s + _origin;
-
     /* Status text */
-    _message_context.setF(Inkscape::NORMAL_MESSAGE,
+    _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
-                          100 * s[NR::X], 100 * s[NR::Y]);
+                          100 * _absolute_affine[0], 100 * _absolute_affine[3]);
 
     return TRUE;
 }
 
-gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
+gboolean Inkscape::SelTrans::stretchRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
-    using NR::X;
-    using NR::Y;
-
-    NR::Dim2 axis, perp;
-
+    Geom::Dim2 axis, perp;
     switch (handle.cursor) {
         case GDK_TOP_SIDE:
         case GDK_BOTTOM_SIDE:
-           axis = NR::Y;
-           perp = NR::X;
-           break;
+            axis = Geom::Y;
+            perp = Geom::X;
+            break;
         case GDK_LEFT_SIDE:
         case GDK_RIGHT_SIDE:
-           axis = NR::X;
-           perp = NR::Y;
-           break;
+            axis = Geom::X;
+            perp = Geom::Y;
+            break;
         default:
             g_assert_not_reached();
             return TRUE;
     };
 
-    if ( fabs( _point[axis] - _origin[axis] ) < 1e-15 ) {
-        return FALSE;
-    }
+    // Calculate the scale factors, which can be either visual or geometric
+    // depending on which type of bbox is currently being used (see preferences -> selector tool)
+    Geom::Scale default_scale = calcScaleFactors(_point, pt, _origin);
+    default_scale[perp] = 1;
 
-    NR::scale s(1, 1);
-    s[axis] = ( ( pt[axis] - _origin[axis] )
-                / ( _point[axis] - _origin[axis] ) );
-    if ( fabs(s[axis]) < 1e-15 ) {
-        s[axis] = 1e-15;
-    }
+    // Find the scale factors for the geometric bbox
+    Geom::Point pt_geom = _getGeomHandlePos(pt);
+    Geom::Scale geom_scale = calcScaleFactors(_point_geom, pt_geom, _origin_for_specpoints);
+    geom_scale[perp] = 1;
 
-    if (state & GDK_MOD1_MASK) { // scale by an integer multiplier/divider
-        if (fabs(s[axis]) > 1)
-            s[axis] = round(s[axis]);
-        else
-            s[axis] = 1/round(1/(MIN(s[axis], 10)));
-    }
+    _absolute_affine = Geom::identity(); //Initialize the scaler
 
-    /* Get a STL list of the selected items.
-    ** FIXME: this should probably be done by Inkscape::Selection.
-    */
-    std::list<SPItem const*> it;
-    for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
-        it.push_back(reinterpret_cast<SPItem*>(i->data));
-    }
+    if (state & GDK_MOD1_MASK) { // stretch by an integer multiplier/divider
+        if (fabs(default_scale[axis]) > 1) {
+            default_scale[axis] = round(default_scale[axis]);
+        } else if (default_scale[axis] != 0) {
+            default_scale[axis] = 1/round(1/(MIN(default_scale[axis], 10)));
+        }
+        // Calculate the new transformation and update the handle position
+        pt = _calcAbsAffineDefault(default_scale);
+        // When stretching by an integer, snapping is not needed
+    } else {
+        // In all other cases we should try to snap now
 
-    SnapManager const &m = _desktop->namedview->snap_manager;
+        SnapManager &m = _desktop->namedview->snap_manager;
+        m.setup(_desktop, false, _items_const);
 
-    if ( state & GDK_CONTROL_MASK ) {
-        // on ctrl, apply symmetrical scaling instead of stretching
-        s[perp] = fabs(s[axis]);
-
-        std::pair<NR::Coord, bool> const bb = m.constrainedSnapStretch(
-            Snapper::SNAPPOINT_BBOX,
-            _bbox_points,
-            it,
-            s[axis],
-            _origin_for_bboxpoints,
-            axis,
-            true);
-
-        std::pair<NR::Coord, bool> const sn = m.constrainedSnapStretch(
-            Snapper::SNAPPOINT_NODE,
-            _snap_points,
-            it,
-            s[axis],
-            _origin_for_specpoints,
-            axis,
-            true);
-
-        if (bb.second || sn.second) { // If we snapped to something
-            /* Choose the smaller difference in scale */
-            NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
-            NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
-            NR::Coord const ratio = (bd < sd) ? bb.first : sn.first;
-            
-            if (fabs(ratio) < NR_HUGE) {
-                s[axis] = fabs(ratio) * sign(s[axis]);
-            }
-            s[perp] = fabs(s[axis]);
+        Inkscape::SnappedPoint bb, sn;
+        g_assert(bb.getSnapped() == false); // Check initialization to catch any regression
+
+        bool symmetrical = state & GDK_CONTROL_MASK;
+
+        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)
+            default_scale[axis] = bb.getTransformation()[axis];
         }
-    } else {
 
-        std::pair<NR::Coord, bool> const bb = m.constrainedSnapStretch(
-            Snapper::SNAPPOINT_BBOX,
-            _bbox_points,
-            it,
-            s[axis],
-            _origin_for_bboxpoints,
-            axis,
-            false);
-
-        std::pair<NR::Coord, bool> const sn = m.constrainedSnapStretch(
-            Snapper::SNAPPOINT_NODE,
-            _snap_points,
-            it,
-            s[axis],
-            _origin_for_specpoints,
-            axis,
-            false);
-
-        if (bb.second || sn.second) { // If we snapped to something
-            /* Choose the smaller difference in scale */
-            NR::Coord const bd = bb.second ? fabs(bb.first - s[axis]) : NR_HUGE;
-            NR::Coord const sd = sn.second ? fabs(sn.first - s[axis]) : NR_HUGE;
-            NR::Coord const nw = (bd < sd) ? bb.first : sn.first; // new stretch scale
-            if (fabs(nw) < NR_HUGE) {
-                s[axis] = nw;
-            }
-            s[perp] = 1;
+        if (sn.getSnapped()) {
+            geom_scale[axis] = sn.getTransformation()[axis];
+        }
+
+        if (symmetrical) {
+            // on ctrl, apply symmetrical scaling instead of stretching
+            // Preserve aspect ratio, but never flip in the dimension not being edited (by using fabs())
+            default_scale[perp] = fabs(default_scale[axis]);
+            geom_scale[perp] = fabs(geom_scale[axis]);
+        }
+
+        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 (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);
+        } else {
+            _desktop->snapindicator->set_new_snaptarget(sn);
+            // We snapped the special points (e.g. nodes), which are not at the visual bbox
+            // The handle location however (pt) might however be at the visual bbox, so we
+            // will have to calculate pt taking the stroke width into account
+            pt = _calcAbsAffineGeom(geom_scale);
         }
-    }
 
-    pt = ( _point - _origin ) * NR::scale(s) + _origin;
-    if (isNaN(pt[X] + pt[Y])) {
-        g_warning("point=(%g, %g), norm=(%g, %g), s=(%g, %g)\n",
-                  _point[X], _point[Y], _origin[X], _origin[Y], s[X], s[Y]);
+        m.unSetup();
     }
 
     // status text
-    _message_context.setF(Inkscape::NORMAL_MESSAGE,
+    _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
                           _("<b>Scale</b>: %0.2f%% x %0.2f%%; with <b>Ctrl</b> to lock ratio"),
-                          100 * s[NR::X], 100 * s[NR::Y]);
+                          100 * _absolute_affine[0], 100 * _absolute_affine[3]);
 
     return TRUE;
 }
 
-gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Point &pt, guint state)
+gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
-    using NR::X;
-    using NR::Y;
+    /* When skewing (or rotating):
+     * 1) the stroke width will not change. This makes life much easier because we don't have to
+     *    account for that (like for scaling or stretching). As a consequence, all points will
+     *    have the same origin for the transformation and for the snapping.
+     * 2) When holding shift, the transformation will be relative to the point opposite of
+     *    the handle; otherwise it will be relative to the center as set for the selection
+     */
 
-    if (handle.cursor != GDK_SB_V_DOUBLE_ARROW && handle.cursor != GDK_SB_H_DOUBLE_ARROW) {
-        return FALSE;
-    }
+    Geom::Dim2 dim_a;
+    Geom::Dim2 dim_b;
 
-    NR::Dim2 dim_a;
-    NR::Dim2 dim_b;
-    if (handle.cursor == GDK_SB_V_DOUBLE_ARROW) {
-        dim_a = X;
-        dim_b = Y;
-    } else {
-        dim_a = Y;
-        dim_b = X;
+    switch (handle.cursor) {
+        case GDK_SB_H_DOUBLE_ARROW:
+            dim_a = Geom::Y;
+            dim_b = Geom::X;
+            break;
+        case GDK_SB_V_DOUBLE_ARROW:
+            dim_a = Geom::X;
+            dim_b = Geom::Y;
+            break;
+        default:
+            g_assert_not_reached();
+            abort();
+            break;
     }
 
-    double skew[2];
-    double s[2] = { 1.0, 1.0 };
+    Geom::Point const initial_delta = _point - _origin;
 
-    if (fabs(_point[dim_a] - _origin[dim_a]) < NR_EPSILON) {
-        return FALSE;
+    if (fabs(initial_delta[dim_a]) < 1e-15) {
+        return false;
     }
 
-    skew[dim_a] = ( pt[dim_b] - _point[dim_b] ) / ( _point[dim_a] - _origin[dim_a] );
+    // Calculate the scale factors, which can be either visual or geometric
+    // depending on which type of bbox is currently being used (see preferences -> selector tool)
+    Geom::Scale scale = calcScaleFactors(_point, pt, _origin, false);
+    Geom::Scale skew = calcScaleFactors(_point, pt, _origin, true);
+    scale[dim_b] = 1;
+    skew[dim_b] = 1;
 
-    s[dim_a] = ( pt[dim_a] - _origin[dim_a] ) / ( _point[dim_a] - _origin[dim_a] );
-
-    if ( fabs(s[dim_a]) < 1 ) {
-        s[dim_a] = sign(s[dim_a]);
+    if (fabs(scale[dim_a]) < 1) {
+        // Prevent shrinking of the selected object, while allowing mirroring
+        scale[dim_a] = sign(scale[dim_a]);
     } else {
-        s[dim_a] = floor( s[dim_a] + 0.5 );
+        // Allow expanding of the selected object by integer multiples
+        scale[dim_a] = floor(scale[dim_a] + 0.5);
     }
 
-    double radians = atan(skew[dim_a] / s[dim_a]);
+    double radians = atan(skew[dim_a] / scale[dim_a]);
 
     if (state & GDK_CONTROL_MASK) {
-
-        int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
-
+        Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+        // Snap to defined angle increments
+        int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
         if (snaps) {
-            double sections = floor( radians * snaps / M_PI + .5 );
-            if (fabs(sections) >= snaps / 2) sections = sign(sections) * (snaps / 2 - 1);
-            radians = ( M_PI / snaps ) * sections;
+            double sections = floor(radians * snaps / M_PI + .5);
+            if (fabs(sections) >= snaps / 2) {
+                sections = sign(sections) * (snaps / 2 - 1);
+            }
+            radians = (M_PI / snaps) * sections;
         }
-        skew[dim_a] = tan(radians) * s[dim_a];
+        skew[dim_a] = tan(radians) * scale[dim_a];
     } else {
-        /* Get a STL list of the selected items.
-           ** FIXME: this should probably be done by Inkscape::Selection.
-           */
-           std::list<SPItem const*> it;
-           for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
-               it.push_back(reinterpret_cast<SPItem*>(i->data));
-           }
-        
-        SnapManager const &m = _desktop->namedview->snap_manager;
-
-        std::pair<NR::Coord, bool> bb = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_BBOX,
-                                                       _bbox_points,
-                                                       it,
-                                                       skew[dim_a],
-                                                       _origin_for_bboxpoints,
-                                                       dim_b);
-
-        std::pair<NR::Coord, bool> sn = m.freeSnapSkew(Inkscape::Snapper::SNAPPOINT_NODE,
-                                                       _snap_points,
-                                                       it,
-                                                       skew[dim_a],
-                                                       _origin_for_specpoints,
-                                                       dim_b);
-
-        if (bb.second || sn.second) {
-            /* We snapped something, so change the skew to reflect it */
-            NR::Coord const bd = bb.second ? bb.first : NR_HUGE;
-            NR::Coord const sd = sn.second ? sn.first : NR_HUGE;
-            skew[dim_a] = std::min(bd, sd);
+        // Snap to objects, grids, guides
+
+        SnapManager &m = _desktop->namedview->snap_manager;
+        m.setup(_desktop, false, _items_const);
+
+        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(_snap_points, _point, constraint, s, _origin, Geom::Dim2(dim_b));
+
+        if (sn.getSnapped()) {
+            // We snapped something, so change the skew to reflect it
+            Geom::Coord const sd = sn.getSnapped() ? sn.getTransformation()[0] : NR_HUGE;
+             _desktop->snapindicator->set_new_snaptarget(sn);
+            skew[dim_a] = sd;
+        } else {
+            _desktop->snapindicator->remove_snaptarget();
         }
+
+        m.unSetup();
     }
 
-    pt[dim_b] = ( _point[dim_a] - _origin[dim_a] ) * skew[dim_a] + _point[dim_b];
-    pt[dim_a] = ( _point[dim_a] - _origin[dim_a] ) * s[dim_a] + _origin[dim_a];
+    // Update the handle position
+    pt[dim_b] = initial_delta[dim_a] * skew[dim_a] + _point[dim_b];
+    pt[dim_a] = initial_delta[dim_a] * scale[dim_a] + _origin[dim_a];
+
+    // Calculate the relative affine
+    _relative_affine = Geom::identity();
+    _relative_affine[2*dim_a + dim_a] = (pt[dim_a] - _origin[dim_a]) / initial_delta[dim_a];
+    _relative_affine[2*dim_a + (dim_b)] = (pt[dim_b] - _point[dim_b]) / initial_delta[dim_a];
+    _relative_affine[2*(dim_b) + (dim_a)] = 0;
+    _relative_affine[2*(dim_b) + (dim_b)] = 1;
 
-    /* status text */
-    double degrees = 180 / M_PI * radians;
-    if (degrees > 180) degrees -= 360;
-    if (degrees < -180) degrees += 360;
+    for (int i = 0; i < 2; i++) {
+        if (fabs(_relative_affine[3*i]) < 1e-15) {
+            _relative_affine[3*i] = 1e-15;
+        }
+    }
 
-    _message_context.setF(Inkscape::NORMAL_MESSAGE,
+    // Update the status text
+    double degrees = mod360symm(Geom::rad_to_deg(radians));
+    _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
                           // TRANSLATORS: don't modify the first ";"
                           // (it will NOT be displayed as ";" - only the second one will be)
                           _("<b>Skew</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"),
@@ -1195,47 +1248,73 @@ gboolean Inkscape::SelTrans::skewRequest(SPSelTransHandle const &handle, NR::Poi
     return TRUE;
 }
 
-gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
+gboolean Inkscape::SelTrans::rotateRequest(Geom::Point &pt, guint state)
 {
-    int snaps = prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12);
+    /* When rotating (or skewing):
+     * 1) the stroke width will not change. This makes life much easier because we don't have to
+     *    account for that (like for scaling or stretching). As a consequence, all points will
+     *    have the same origin for the transformation and for the snapping.
+     * 2) When holding shift, the transformation will be relative to the point opposite of
+     *    the handle; otherwise it will be relative to the center as set for the selection
+     */
+
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    int snaps = prefs->getInt("/options/rotationsnapsperpi/value", 12);
 
     // rotate affine in rotate
-    NR::Point const d1 = _point - _origin;
-    NR::Point const d2 = pt     - _origin;
+    Geom::Point const d1 = _point - _origin;
+    Geom::Point const d2 = pt     - _origin;
 
-    NR::Coord const h1 = NR::L2(d1);
+    Geom::Coord const h1 = Geom::L2(d1); // initial radius
     if (h1 < 1e-15) return FALSE;
-    NR::Point q1 = d1 / h1;
-    NR::Coord const h2 = NR::L2(d2);
+    Geom::Point q1 = d1 / h1; // normalized initial vector to handle
+    Geom::Coord const h2 = Geom::L2(d2); // new radius
     if (fabs(h2) < 1e-15) return FALSE;
-    NR::Point q2 = d2 / h2;
+    Geom::Point q2 = d2 / h2; // normalized new vector to handle
+
+    Geom::Rotate r1(q1);
+    Geom::Rotate r2(q2);
 
-    double radians;
+    double radians = atan2(Geom::dot(Geom::rot90(d1), d2), Geom::dot(d1, d2));;
     if (state & GDK_CONTROL_MASK) {
-        /* Have to restrict movement. */
-        double cos_t = NR::dot(q1, q2);
-        double sin_t = NR::dot(NR::rot90(q1), q2);
+        // Snap to defined angle increments
+        double cos_t = Geom::dot(q1, q2);
+        double sin_t = Geom::dot(Geom::rot90(q1), q2);
         radians = atan2(sin_t, cos_t);
         if (snaps) {
             radians = ( M_PI / snaps ) * floor( radians * snaps / M_PI + .5 );
         }
-        q1 = NR::Point(1, 0);
-        q2 = NR::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(NR::dot(NR::rot90(d1), d2),
-                        NR::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();
+        }
+
     }
 
-    NR::rotate const r1(q1);
-    NR::rotate const r2(q2);
-    pt = _point * NR::translate(-_origin) * ( r2 / r1 ) * NR::translate(_origin);
 
-    /* status text */
-    double degrees = 180 / M_PI * radians;
-    if (degrees > 180) degrees -= 360;
-    if (degrees < -180) degrees += 360;
+    // Calculate the relative affine
+    _relative_affine = r2 * r1.inverse();
+
+    // Update the handle position
+    pt = _point * Geom::Translate(-_origin) * _relative_affine * Geom::Translate(_origin);
 
-    _message_context.setF(Inkscape::NORMAL_MESSAGE,
+    // Update the status text
+    double degrees = mod360symm(Geom::rad_to_deg(radians));
+    _message_context.setF(Inkscape::IMMEDIATE_MESSAGE,
                           // TRANSLATORS: don't modify the first ";"
                           // (it will NOT be displayed as ";" - only the second one will be)
                           _("<b>Rotate</b>: %0.2f&#176;; with <b>Ctrl</b> to snap angle"), degrees);
@@ -1243,44 +1322,36 @@ gboolean Inkscape::SelTrans::rotateRequest(NR::Point &pt, guint state)
     return TRUE;
 }
 
-gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
+// Move the item's transformation center
+gboolean Inkscape::SelTrans::centerRequest(Geom::Point &pt, guint state)
 {
-    using NR::X;
-    using NR::Y;
-
-    SnapManager const &m = _desktop->namedview->snap_manager;
-    pt = m.freeSnap(Snapper::SNAPPOINT_NODE, pt, NULL).getPoint();
-
-    if (state & GDK_CONTROL_MASK) {
-        if ( fabs(_point[X] - pt[X]) > fabs(_point[Y] - pt[Y]) ) {
-            pt[Y] = _point[Y];
-        } else {
-            pt[X] = _point[X];
+    // 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.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();
+    }
+    else {
+        if (!(state & GDK_SHIFT_MASK)) { // Shift disables snapping
+            m.freeSnapReturnByRef(pt, Inkscape::SNAPSOURCE_ROTATION_CENTER);
         }
     }
 
-    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];
-            }
-        }
-    }
+    m.unSetup();
 
     // status text
-    GString *xs = SP_PX_TO_METRIC_STRING(pt[X], _desktop->namedview->getDefaultMetric());
-    GString *ys = SP_PX_TO_METRIC_STRING(pt[Y], _desktop->namedview->getDefaultMetric());
+    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());
     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("Move <b>center</b> to %s, %s"), xs->str, ys->str);
     g_string_free(xs, FALSE);
     g_string_free(ys, FALSE);
@@ -1293,195 +1364,58 @@ gboolean Inkscape::SelTrans::centerRequest(NR::Point &pt, guint state)
  *
  */
 
-void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
+void sp_sel_trans_stretch(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
     seltrans->stretch(handle, pt, state);
 }
 
-void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
+void sp_sel_trans_scale(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
 {
     seltrans->scale(pt, state);
 }
 
-void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, NR::Point &pt, guint state)
+void sp_sel_trans_skew(Inkscape::SelTrans *seltrans, SPSelTransHandle const &handle, Geom::Point &pt, guint state)
 {
     seltrans->skew(handle, pt, state);
 }
 
-void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint state)
+void sp_sel_trans_rotate(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint state)
 {
     seltrans->rotate(pt, state);
 }
 
-void Inkscape::SelTrans::stretch(SPSelTransHandle const &handle, NR::Point &pt, guint state)
+void Inkscape::SelTrans::stretch(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
 {
-    using NR::X;
-    using NR::Y;
-
-    NR::Dim2 dim;
-    switch (handle.cursor) {
-        case GDK_LEFT_SIDE:
-        case GDK_RIGHT_SIDE:
-            dim = X;
-            break;
-        case GDK_TOP_SIDE:
-        case GDK_BOTTOM_SIDE:
-            dim = Y;
-            break;
-        default:
-            g_assert_not_reached();
-            abort();
-            break;
-    }
-
-    NR::Point const scale_origin(_origin);
-    double const offset = _point[dim] - scale_origin[dim];
-    if (!( fabs(offset) >= 1e-15 )) {
-        return;
-    }
-    NR::scale s(1, 1);
-    s[dim] = ( pt[dim] - scale_origin[dim] ) / offset;
-    if (isNaN(s[dim])) {
-        g_warning("s[dim]=%g, pt[dim]=%g, scale_origin[dim]=%g, point[dim]=%g\n",
-                  s[dim], pt[dim], scale_origin[dim], _point[dim]);
-    }
-    if (!( fabs(s[dim]) >= 1e-15 )) {
-        s[dim] = 1e-15;
-    }
-    if (state & GDK_CONTROL_MASK) {
-        /* Preserve aspect ratio, but never flip in the dimension not being edited. */
-        s[!dim] = fabs(s[dim]);
-    }
-
-    if (!_bbox) {
-        return;
-    }
-
-    NR::Point new_bbox_min = _approximate_bbox->min() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
-    NR::Point new_bbox_max = _approximate_bbox->max() * (NR::translate(-scale_origin) * NR::Matrix(s) * NR::translate(scale_origin));
-
-    int transform_stroke = false;
-    gdouble strokewidth = 0;
-
-    if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
-        transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
-        strokewidth = _strokewidth;
-    }
-
-    NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
-                    new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
-
-    transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
+    transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
 }
 
-void Inkscape::SelTrans::scale(NR::Point &pt, guint /*state*/)
+void Inkscape::SelTrans::scale(Geom::Point &/*pt*/, guint /*state*/)
 {
-    if (!_bbox) {
-        return;
-    }
-
-    NR::Point const offset = _point - _origin;
-
-    NR::scale s (1, 1);
-    for (int i = NR::X; i <= NR::Y; i++) {
-        if (fabs(offset[i]) > 1e-9)
-            s[i] = (pt[i] - _origin[i]) / offset[i];
-        if (fabs(s[i]) < 1e-9)
-            s[i] = 1e-9;
-    }
-
-    NR::Point new_bbox_min = _approximate_bbox->min() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
-    NR::Point new_bbox_max = _approximate_bbox->max() * (NR::translate(-_origin) * NR::Matrix(s) * NR::translate(_origin));
-
-    int transform_stroke = false;
-    gdouble strokewidth = 0;
-
-    if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
-        transform_stroke = prefs_get_int_attribute ("options.transform", "stroke", 1);
-        strokewidth = _strokewidth;
-    }
-
-    NR::Matrix scaler = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
-                    new_bbox_min[NR::X], new_bbox_min[NR::Y], new_bbox_max[NR::X], new_bbox_max[NR::Y]);
-
-    transform(scaler, NR::Point(0, 0)); // we have already accounted for origin, so pass 0,0
+    transform(_absolute_affine, Geom::Point(0, 0)); // we have already accounted for origin, so pass 0,0
 }
 
-void Inkscape::SelTrans::skew(SPSelTransHandle const &handle, NR::Point &pt, guint /*state*/)
+void Inkscape::SelTrans::skew(SPSelTransHandle const &/*handle*/, Geom::Point &/*pt*/, guint /*state*/)
 {
-    NR::Point const offset = _point - _origin;
-
-    unsigned dim;
-    switch (handle.cursor) {
-        case GDK_SB_H_DOUBLE_ARROW:
-            dim = NR::Y;
-            break;
-        case GDK_SB_V_DOUBLE_ARROW:
-            dim = NR::X;
-            break;
-        default:
-            g_assert_not_reached();
-            abort();
-            break;
-    }
-    if (fabs(offset[dim]) < 1e-15) {
-        return;
-    }
-    NR::Matrix skew = NR::identity();
-    skew[2*dim + dim] = (pt[dim] - _origin[dim]) / offset[dim];
-    skew[2*dim + (1-dim)] = (pt[1-dim] - _point[1-dim]) / offset[dim];
-    skew[2*(1-dim) + (dim)] = 0;
-    skew[2*(1-dim) + (1-dim)] = 1;
-
-    for (int i = 0; i < 2; i++) {
-        if (fabs(skew[3*i]) < 1e-15) {
-            skew[3*i] = 1e-15;
-        }
-    }
-    transform(skew, _origin);
+    transform(_relative_affine, _origin);
 }
 
-void Inkscape::SelTrans::rotate(NR::Point &pt, guint /*state*/)
+void Inkscape::SelTrans::rotate(Geom::Point &/*pt*/, guint /*state*/)
 {
-    NR::Point const offset = _point - _origin;
-
-    NR::Coord const h1 = NR::L2(offset);
-    if (h1 < 1e-15) {
-        return;
-    }
-    NR::Point const q1 = offset / h1;
-    NR::Coord const h2 = NR::L2( pt - _origin );
-    if (h2 < 1e-15) {
-        return;
-    }
-    NR::Point const q2 = (pt - _origin) / h2;
-    NR::rotate const r1(q1);
-    NR::rotate const r2(q2);
-
-    NR::Matrix rotate( r2 / r1 );
-    transform(rotate, _origin);
+    transform(_relative_affine, _origin);
 }
 
-void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, NR::Point &pt, guint /*state*/)
+void sp_sel_trans_center(Inkscape::SelTrans *seltrans, SPSelTransHandle const &, Geom::Point &pt, guint /*state*/)
 {
     seltrans->setCenter(pt);
 }
 
 
-void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
+void Inkscape::SelTrans::moveTo(Geom::Point const &xy, guint state)
 {
-    SnapManager const &m = _desktop->namedview->snap_manager;
+    SnapManager &m = _desktop->namedview->snap_manager;
 
     /* The amount that we've moved by during this drag */
-    NR::Point dxy = xy - _point;
-
-    /* Get a STL list of the selected items.
-    ** FIXME: this should probably be done by Inkscape::Selection.
-    */
-    std::list<SPItem const*> it;
-    for (GSList const *i = _selection->itemList(); i != NULL; i = i->next) {
-        it.push_back(reinterpret_cast<SPItem*>(i->data));
-    }
+    Geom::Point dxy = xy - _point;
 
     bool const alt = (state & GDK_MOD1_MASK);
     bool const control = (state & GDK_CONTROL_MASK);
@@ -1489,92 +1423,214 @@ void Inkscape::SelTrans::moveTo(NR::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.
-        */
-
-        dxy = m.freeSnap(Snapper::SNAPPOINT_NODE, dxy, NULL).getPoint();
+        // Alt pressed means: move only by integer multiples of the grid spacing
 
-    } else if (!shift) {
+        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;
+            }
+        }
+    } else { //!shift: with snapping
 
         /* We're snapping to things, possibly with a constraint to horizontal or
         ** vertical movement.  Obtain a list of possible translations and then
         ** pick the smallest.
         */
 
+        m.setup(_desktop, false, _items_const);
+
         /* This will be our list of possible translations */
-        std::list<std::pair<NR::Point, bool> > s;
+        std::list<Inkscape::SnappedPoint> s;
 
-        if (control) {
+        if (control) { // constrained movement with snapping
 
             /* Snap to things, and also constrain to horizontal or vertical movement */
 
-            for (unsigned int dim = 0; dim < 2; dim++) {
-                s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_BBOX,
-                                                         _bbox_points,
-                                                         it,
-                                                         Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
-                                                         dxy));
-
-                s.push_back(m.constrainedSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
-                                                         _snap_points,
-                                                         it,
-                                                         Inkscape::Snapper::ConstraintLine(component_vectors[dim]),
-                                                         dxy));
-            }
-
-        } else {
+            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.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::Snapper::SNAPPOINT_BBOX,
-                                              _bbox_points, it, dxy));
-            s.push_back(m.freeSnapTranslation(Inkscape::Snapper::SNAPPOINT_NODE,
-                                              _snap_points, it, 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; */
+            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; */
         }
+        m.unSetup();
 
         /* Pick one */
-        NR::Coord best = NR_HUGE;
-        for (std::list<std::pair<NR::Point, bool> >::const_iterator i = s.begin(); i != s.end(); i++) {
-            if (i->second) {
-                NR::Coord const m = NR::L2(i->first);
-                if (m < best) {
-                    best = m;
-                    dxy = i->first;
+        Inkscape::SnappedPoint best_snapped_point;
+        for (std::list<Inkscape::SnappedPoint>::const_iterator i = s.begin(); i != s.end(); i++) {
+            if (i->getSnapped()) {
+                if (best_snapped_point.isOtherSnapBetter(*i, true)) {
+                    best_snapped_point = *i;
+                    dxy = i->getTransformation();
                 }
             }
         }
-    }
 
-    if (control) {
-        /* Ensure that the horizontal and vertical constraint has been applied */
-        if (fabs(dxy[NR::X]) > fabs(dxy[NR::Y])) {
-            dxy[NR::Y] = 0;
+        if (best_snapped_point.getSnapped()) {
+            _desktop->snapindicator->set_new_snaptarget(best_snapped_point);
         } else {
-            dxy[NR::X] = 0;
+            // We didn't snap, so remove any previous snap indicator
+            _desktop->snapindicator->remove_snaptarget();
+            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 constrainedSnapTranslate() above)
+                if (fabs(dxy[Geom::X]) > fabs(dxy[Geom::Y])) {
+                    dxy[Geom::Y] = 0;
+                } else {
+                    dxy[Geom::X] = 0;
+                }
+            }
         }
     }
 
-    NR::Matrix const move((NR::translate(dxy)));
-    NR::Point const norm(0, 0);
+    Geom::Matrix const move((Geom::Translate(dxy)));
+    Geom::Point const norm(0, 0);
     transform(move, norm);
 
     // status text
-    GString *xs = SP_PX_TO_METRIC_STRING(dxy[NR::X], _desktop->namedview->getDefaultMetric());
-    GString *ys = SP_PX_TO_METRIC_STRING(dxy[NR::Y], _desktop->namedview->getDefaultMetric());
+    GString *xs = SP_PX_TO_METRIC_STRING(dxy[Geom::X], _desktop->namedview->getDefaultMetric());
+    GString *ys = SP_PX_TO_METRIC_STRING(dxy[Geom::Y], _desktop->namedview->getDefaultMetric());
     _message_context.setF(Inkscape::NORMAL_MESSAGE, _("<b>Move</b> by %s, %s; with <b>Ctrl</b> to restrict to horizontal/vertical; with <b>Shift</b> to disable snapping"), xs->str, ys->str);
     g_string_free(xs, TRUE);
     g_string_free(ys, TRUE);
 }
 
+// Given a location of a handle at the visual bounding box, find the corresponding location at the
+// geometrical bounding box
+Geom::Point Inkscape::SelTrans::_getGeomHandlePos(Geom::Point const &visual_handle_pos)
+{
+    if ( _snap_bbox_type == SPItem::GEOMETRIC_BBOX) {
+        // When the selector tool is using geometric bboxes, then the handle is already
+        // located at one of the geometric bbox corners
+        return visual_handle_pos;
+    }
+
+    if (!_geometric_bbox) {
+        //_getGeomHandlePos() can only be used after _geometric_bbox has been defined!
+        return visual_handle_pos;
+    }
+
+    // Using the Geom::Rect constructor below ensures that "min() < max()", which is important
+    // because this will also hold for _bbox, and which is required for get_scale_transform_with_stroke()
+    Geom::Rect new_bbox = Geom::Rect(_origin_for_bboxpoints, visual_handle_pos); // new visual bounding box
+    // Please note that the new_bbox might in fact be just a single line, for example when stretching (in
+    // which case the handle and origin will be aligned vertically or horizontally)
+    Geom::Point normalized_handle_pos = (visual_handle_pos - new_bbox.min()) * Geom::Scale(new_bbox.dimensions()).inverse();
+
+    // Calculate the absolute affine while taking into account the scaling of the stroke width
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    bool transform_stroke = prefs->getBool("/options/transform/stroke", true);
+    Geom::Matrix abs_affine = get_scale_transform_with_stroke (*_bbox, _strokewidth, transform_stroke,
+                    new_bbox.min()[Geom::X], new_bbox.min()[Geom::Y], new_bbox.max()[Geom::X], new_bbox.max()[Geom::Y]);
+
+    // Calculate the scaled geometrical bbox
+    Geom::Rect new_geom_bbox = Geom::Rect(_geometric_bbox->min() * abs_affine, _geometric_bbox->max() * abs_affine);
+    // Find the location of the handle on this new geometrical bbox
+    return normalized_handle_pos * Geom::Scale(new_geom_bbox.dimensions()) + new_geom_bbox.min(); //new position of the geometric handle
+}
+
+Geom::Scale Inkscape::calcScaleFactors(Geom::Point const &initial_point, Geom::Point const &new_point, Geom::Point const &origin, bool const skew)
+{
+    // Work out the new scale factors for the bbox
+
+    Geom::Point const initial_delta = initial_point - origin;
+    Geom::Point const new_delta = new_point - origin;
+    Geom::Point const offset = new_point - initial_point;
+    Geom::Scale scale(1, 1);
+
+    for ( unsigned int i = 0 ; i < 2 ; i++ ) {
+        if ( fabs(initial_delta[i]) > 1e-6 ) {
+            if (skew) {
+                scale[i] = offset[1-i] / initial_delta[i];
+            } else {
+                scale[i] = new_delta[i] / initial_delta[i];
+            }
+        }
+    }
+
+    return scale;
+}
+
+// Only for scaling/stretching
+Geom::Point Inkscape::SelTrans::_calcAbsAffineDefault(Geom::Scale const default_scale)
+{
+    Geom::Matrix abs_affine = Geom::Translate(-_origin) * Geom::Matrix(default_scale) * Geom::Translate(_origin);
+    Geom::Point new_bbox_min = _approximate_bbox->min() * abs_affine;
+    Geom::Point new_bbox_max = _approximate_bbox->max() * abs_affine;
+
+    bool transform_stroke = false;
+    gdouble strokewidth = 0;
+
+    if ( _snap_bbox_type != SPItem::GEOMETRIC_BBOX) {
+        Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+        transform_stroke = prefs->getBool("/options/transform/stroke", true);
+        strokewidth = _strokewidth;
+    }
+
+    _absolute_affine = get_scale_transform_with_stroke (*_approximate_bbox, strokewidth, transform_stroke,
+                    new_bbox_min[Geom::X], new_bbox_min[Geom::Y], new_bbox_max[Geom::X], new_bbox_max[Geom::Y]);
+
+    // return the new handle position
+    return ( _point - _origin ) * default_scale + _origin;
+}
+
+// Only for scaling/stretching
+Geom::Point Inkscape::SelTrans::_calcAbsAffineGeom(Geom::Scale const geom_scale)
+{
+    _relative_affine = Geom::Matrix(geom_scale);
+    _absolute_affine = Geom::Translate(-_origin_for_specpoints) * _relative_affine * Geom::Translate(_origin_for_specpoints);
+
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    bool const transform_stroke = prefs->getBool("/options/transform/stroke", true);
+    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);
+    }
+
+    // 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_
+}
 
 /*
   Local Variables:
@@ -1585,4 +1641,4 @@ void Inkscape::SelTrans::moveTo(NR::Point const &xy, guint state)
   fill-column:99
   End:
 */
-// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :