Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / gradient-chemistry.cpp
index 0690ef140c480efe083600cad8c5f71b2cbc8b76..fb5dab648249b11873d83796c86b256a48b483d4 100644 (file)
@@ -1,5 +1,3 @@
-#define __SP_GRADIENT_CHEMISTRY_C__
-
 /*
  * Various utility methods for gradients
  *
@@ -7,7 +5,10 @@
  *   Lauris Kaplinski <lauris@kaplinski.com>
  *   bulia byak
  *   Johan Engelen <j.b.c.engelen@ewi.utwente.nl>
+ *   Jon A. Cruz <jon@joncruz.org>
+ *   Abhishek Sharma
  *
+ * Copyright (C) 2010 Authors
  * Copyright (C) 2007 Johan Engelen
  * Copyright (C) 2001-2005 authors
  * Copyright (C) 2001 Ximian, Inc.
 #include "sp-text.h"
 #include "sp-tspan.h"
 #include <libnr/nr-matrix-fns.h>
+#include <libnr/nr-point-fns.h>
+#include <libnr/nr-matrix-ops.h>
+#include <libnr/nr-rotate-ops.h>
+#include <2geom/transforms.h>
 #include "xml/repr.h"
 #include "svg/svg.h"
 #include "svg/svg-color.h"
+#include "svg/css-ostringstream.h"
+#include "preferences.h"
 
+#define noSP_GR_VERBOSE
 
 // Terminology:
 //
 
 static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *gr);
 
-SPGradient *
-sp_gradient_ensure_vector_normalized(SPGradient *gr)
+SPGradient *sp_gradient_ensure_vector_normalized(SPGradient *gr)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_ensure_vector_normalized(%p)", gr);
+#endif
     g_return_val_if_fail(gr != NULL, NULL);
     g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
 
@@ -56,14 +66,14 @@ sp_gradient_ensure_vector_normalized(SPGradient *gr)
     if (gr->state == SP_GRADIENT_STATE_VECTOR) return gr;
     /* Fail, if we have wrong state set */
     if (gr->state != SP_GRADIENT_STATE_UNKNOWN) {
-        g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, SP_OBJECT_ID(gr));
+        g_warning("file %s: line %d: Cannot normalize private gradient to vector (%s)", __FILE__, __LINE__, gr->getId());
         return NULL;
     }
 
     /* First make sure we have vector directly defined (i.e. gr has its own stops) */
-    if (!gr->has_stops) {
+    if ( !gr->hasStops() ) {
         /* We do not have stops ourselves, so flatten stops as well */
-        sp_gradient_ensure_vector(gr);
+        gr->ensureVector();
         g_assert(gr->vector.built);
         // this adds stops from gr->vector as children to gr
         sp_gradient_repr_write_vector (gr);
@@ -72,7 +82,7 @@ sp_gradient_ensure_vector_normalized(SPGradient *gr)
     /* If gr hrefs some other gradient, remove the href */
     if (gr->ref->getObject()) {
         /* We are hrefing someone, so require flattening */
-        SP_OBJECT(gr)->updateRepr(((SPObject *) gr)->repr, SP_OBJECT_WRITE_EXT | SP_OBJECT_WRITE_ALL);
+        SP_OBJECT(gr)->updateRepr(SP_OBJECT_WRITE_EXT | SP_OBJECT_WRITE_ALL);
         sp_gradient_repr_set_link(SP_OBJECT_REPR(gr), NULL);
     }
 
@@ -85,17 +95,20 @@ sp_gradient_ensure_vector_normalized(SPGradient *gr)
  * Creates new private gradient for the given vector
  */
 
-static SPGradient *
-sp_gradient_get_private_normalized(SPDocument *document, SPGradient *vector, SPGradientType type)
+static SPGradient *sp_gradient_get_private_normalized(SPDocument *document, SPGradient *vector, SPGradientType type)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_get_private_normalized(%p, %p, %d)", document, vector, type);
+#endif
+
     g_return_val_if_fail(document != NULL, NULL);
     g_return_val_if_fail(vector != NULL, NULL);
     g_return_val_if_fail(SP_IS_GRADIENT(vector), NULL);
-    g_return_val_if_fail(SP_GRADIENT_HAS_STOPS(vector), NULL);
+    g_return_val_if_fail(vector->hasStops(), NULL);
 
     SPDefs *defs = (SPDefs *) SP_DOCUMENT_DEFS(document);
 
-    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
+    Inkscape::XML::Document *xml_doc = document->getReprDoc();
     // create a new private gradient of the requested type
     Inkscape::XML::Node *repr;
     if (type == SP_GRADIENT_TYPE_LINEAR) {
@@ -125,8 +138,7 @@ sp_gradient_get_private_normalized(SPDocument *document, SPGradient *vector, SPG
 /**
 Count how many times gr is used by the styles of o and its descendants
 */
-guint
-count_gradient_hrefs(SPObject *o, SPGradient *gr)
+guint count_gradient_hrefs(SPObject *o, SPGradient *gr)
 {
     if (!o)
         return 1;
@@ -149,8 +161,7 @@ count_gradient_hrefs(SPObject *o, SPGradient *gr)
         i ++;
     }
 
-    for (SPObject *child = sp_object_first_child(o);
-         child != NULL; child = SP_OBJECT_NEXT(child)) {
+    for ( SPObject *child = o->firstChild(); child; child = child->getNext() ) {
         i += count_gradient_hrefs(child, gr);
     }
 
@@ -161,18 +172,21 @@ count_gradient_hrefs(SPObject *o, SPGradient *gr)
 /**
  * If gr has other users, create a new private; also check if gr links to vector, relink if not
  */
-SPGradient *
-sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
-                                      SPGradientType type, SPObject *o)
+SPGradient *sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
+                                                  SPGradientType type, SPObject *o)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_fork_private_if_necessary(%p, %p, %d, %p)", gr, vector, type, o);
+#endif
     g_return_val_if_fail(gr != NULL, NULL);
     g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
 
     // Orphaned gradient, no vector with stops at the end of the line; this used to be an assert
     // but i think we should not abort on this - maybe just write a validity warning into some sort
     // of log
-    if (!vector || !SP_GRADIENT_HAS_STOPS(vector))
+    if ( !vector || !vector->hasStops() ) {
         return (gr);
+    }
 
     // user is the object that uses this gradient; normally it's item but for tspans, we
     // check its ancestor text so that tspans don't get different gradients from their
@@ -184,7 +198,7 @@ sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
 
     // Check the number of uses of the gradient within this object;
     // if we are private and there are no other users,
-    if (SP_OBJECT_HREFCOUNT(gr) <= count_gradient_hrefs(user, gr)) {
+    if (!vector->isSwatch() && (gr->hrefcount <= count_gradient_hrefs(user, gr))) {
         // check vector
         if ( gr != vector && gr->ref->getObject() != vector ) {
             /* our href is not the vector, and vector is different from gr; relink */
@@ -196,10 +210,10 @@ sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
     SPDocument *doc = SP_OBJECT_DOCUMENT(gr);
     SPObject *defs = SP_DOCUMENT_DEFS(doc);
 
-    if ((gr->has_stops) ||
+    if ((gr->hasStops()) ||
         (gr->state != SP_GRADIENT_STATE_UNKNOWN) ||
         (SP_OBJECT_PARENT(gr) != SP_OBJECT(defs)) ||
-        (SP_OBJECT_HREFCOUNT(gr) > 1)) {
+        (gr->hrefcount > 1)) {
         // we have to clone a fresh new private gradient for the given vector
 
         // create an empty one
@@ -230,12 +244,19 @@ sp_gradient_fork_private_if_necessary(SPGradient *gr, SPGradient *vector,
     }
 }
 
-SPGradient *
-sp_gradient_fork_vector_if_necessary (SPGradient *gr)
+SPGradient *sp_gradient_fork_vector_if_necessary(SPGradient *gr)
 {
-    if (SP_OBJECT_HREFCOUNT(gr) > 1) {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_fork_vector_if_necessary(%p)", gr);
+#endif
+    // Some people actually prefer their gradient vectors to be shared...
+    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
+    if (!prefs->getBool("/options/forkgradientvectors/value", true))
+        return gr;
+
+    if (gr->hrefcount > 1) {
         SPDocument *doc = SP_OBJECT_DOCUMENT(gr);
-        Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
+        Inkscape::XML::Document *xml_doc = doc->getReprDoc();
 
         Inkscape::XML::Node *repr = SP_OBJECT_REPR (gr)->duplicate(xml_doc);
         SP_OBJECT_REPR (SP_DOCUMENT_DEFS (doc))->addChild(repr, NULL);
@@ -250,10 +271,12 @@ sp_gradient_fork_vector_if_necessary (SPGradient *gr)
 /**
  *  Obtain the vector from the gradient. A forked vector will be created and linked to this gradient if another gradient uses it.
  */
-SPGradient *
-sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector)
+SPGradient *sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vector)
 {
-    SPGradient *vector = sp_gradient_get_vector (gradient, force_vector);
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_get_forked_vector_if_necessary(%p, %d)", gradient, force_vector);
+#endif
+    SPGradient *vector = gradient->getVector(force_vector);
     vector = sp_gradient_fork_vector_if_necessary (vector);
     if ( gradient != vector && gradient->ref->getObject() != vector ) {
         sp_gradient_repr_set_link(SP_OBJECT_REPR(gradient), vector);
@@ -267,34 +290,36 @@ sp_gradient_get_forked_vector_if_necessary(SPGradient *gradient, bool force_vect
  * instead. No forking or reapplying is done because this is only called for newly created privates.
  * @return The new gradient.
  */
-SPGradient *
-sp_gradient_reset_to_userspace (SPGradient *gr, SPItem *item)
+SPGradient *sp_gradient_reset_to_userspace(SPGradient *gr, SPItem *item)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_reset_to_userspace(%p, %p)", gr, item);
+#endif
     Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
 
     // calculate the bbox of the item
-    sp_document_ensure_up_to_date(SP_OBJECT_DOCUMENT(item));
-    NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity()); // we need "true" bbox without item_i2d_affine
+    SP_OBJECT_DOCUMENT(item)->ensureUpToDate();
+    Geom::OptRect bbox = item->getBounds(Geom::identity()); // we need "true" bbox without item_i2d_affine
 
-    if ( !bbox || bbox->isEmpty() )
+    if (!bbox)
         return gr;
 
-    NR::Coord const width = bbox->dimensions()[NR::X];
-    NR::Coord const height = bbox->dimensions()[NR::Y];
+    Geom::Coord const width = bbox->dimensions()[Geom::X];
+    Geom::Coord const height = bbox->dimensions()[Geom::Y];
 
-    NR::Point const center = bbox->midpoint();
+    Geom::Point const center = bbox->midpoint();
 
     if (SP_IS_RADIALGRADIENT(gr)) {
-        sp_repr_set_svg_double(repr, "cx", center[NR::X]);
-        sp_repr_set_svg_double(repr, "cy", center[NR::Y]);
-        sp_repr_set_svg_double(repr, "fx", center[NR::X]);
-        sp_repr_set_svg_double(repr, "fy", center[NR::Y]);
+        sp_repr_set_svg_double(repr, "cx", center[Geom::X]);
+        sp_repr_set_svg_double(repr, "cy", center[Geom::Y]);
+        sp_repr_set_svg_double(repr, "fx", center[Geom::X]);
+        sp_repr_set_svg_double(repr, "fy", center[Geom::Y]);
         sp_repr_set_svg_double(repr, "r", width/2);
 
         // we want it to be elliptic, not circular
-        NR::Matrix squeeze = NR::Matrix (NR::translate (-center)) *
-            NR::Matrix (NR::scale(1, height/width)) *
-            NR::Matrix (NR::translate (center));
+        Geom::Matrix squeeze = Geom::Translate (-center) *
+            Geom::Scale(1, height/width) *
+            Geom::Translate (center);
 
         gr->gradientTransform = squeeze;
         {
@@ -303,10 +328,10 @@ sp_gradient_reset_to_userspace (SPGradient *gr, SPItem *item)
             g_free(c);
         }
     } else {
-        sp_repr_set_svg_double(repr, "x1", (center - NR::Point(width/2, 0))[NR::X]);
-        sp_repr_set_svg_double(repr, "y1", (center - NR::Point(width/2, 0))[NR::Y]);
-        sp_repr_set_svg_double(repr, "x2", (center + NR::Point(width/2, 0))[NR::X]);
-        sp_repr_set_svg_double(repr, "y2", (center + NR::Point(width/2, 0))[NR::Y]);
+        sp_repr_set_svg_double(repr, "x1", (center - Geom::Point(width/2, 0))[Geom::X]);
+        sp_repr_set_svg_double(repr, "y1", (center - Geom::Point(width/2, 0))[Geom::Y]);
+        sp_repr_set_svg_double(repr, "x2", (center + Geom::Point(width/2, 0))[Geom::X]);
+        sp_repr_set_svg_double(repr, "y2", (center + Geom::Point(width/2, 0))[Geom::Y]);
     }
 
     // set the gradientUnits
@@ -319,30 +344,36 @@ sp_gradient_reset_to_userspace (SPGradient *gr, SPItem *item)
  * Convert an item's gradient to userspace if necessary, also fork it if necessary.
  * @return The new gradient.
  */
-SPGradient *
-sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *property)
+SPGradient *sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *property)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_convert_to_userspace(%p, %p, \"%s\")", gr, item, property);
+#endif
     g_return_val_if_fail(SP_IS_GRADIENT(gr), NULL);
 
+    if ( gr && gr->isSolid() ) {
+        return gr;
+    }
+
     // First, fork it if it is shared
-    gr = sp_gradient_fork_private_if_necessary(gr, sp_gradient_get_vector(gr, FALSE),
+    gr = sp_gradient_fork_private_if_necessary(gr, gr->getVector(),
                                                SP_IS_RADIALGRADIENT(gr) ? SP_GRADIENT_TYPE_RADIAL : SP_GRADIENT_TYPE_LINEAR, SP_OBJECT(item));
 
-    if (gr->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
+    if (gr->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
 
         Inkscape::XML::Node *repr = SP_OBJECT_REPR(gr);
 
         // calculate the bbox of the item
-        sp_document_ensure_up_to_date(SP_OBJECT_DOCUMENT(item));
-        NR::Matrix bbox2user;
-        NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity()); // we need "true" bbox without item_i2d_affine
-        if ( bbox && !bbox->isEmpty() ) {
-            bbox2user = NR::Matrix(bbox->dimensions()[NR::X], 0,
-                                   0, bbox->dimensions()[NR::Y],
-                                   bbox->min()[NR::X], bbox->min()[NR::Y]);
+        SP_OBJECT_DOCUMENT(item)->ensureUpToDate();
+        Geom::Matrix bbox2user;
+        Geom::OptRect bbox = item->getBounds(Geom::identity()); // we need "true" bbox without item_i2d_affine
+        if ( bbox ) {
+            bbox2user = Geom::Matrix(bbox->dimensions()[Geom::X], 0,
+                                   0, bbox->dimensions()[Geom::Y],
+                                   bbox->min()[Geom::X], bbox->min()[Geom::Y]);
         } else {
             // would be degenerate otherwise
-            bbox2user = NR::identity();
+            bbox2user = Geom::identity();
         }
 
         /* skew is the additional transform, defined by the proportions of the item, that we need
@@ -359,8 +390,8 @@ sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *prop
          *   gradient vector in user space due to application of the non-uniform scaling
          *   transformation from bounding box space to user space.
          */
-        NR::Matrix skew = bbox2user;
-        double exp = skew.expansion();
+        Geom::Matrix skew = bbox2user;
+        double exp = skew.descrim();
         skew[0] /= exp;
         skew[1] /= exp;
         skew[2] /= exp;
@@ -378,40 +409,40 @@ sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *prop
 
         // Matrix to convert points to userspace coords; postmultiply by inverse of skew so
         // as to cancel it out when it's applied to the gradient during rendering
-        NR::Matrix point_convert = bbox2user * skew.inverse();
+        Geom::Matrix point_convert = bbox2user * skew.inverse();
 
         if (SP_IS_RADIALGRADIENT(gr)) {
             SPRadialGradient *rg = SP_RADIALGRADIENT(gr);
 
             // original points in the bbox coords
-            NR::Point c_b = NR::Point(rg->cx.computed, rg->cy.computed);
-            NR::Point f_b = NR::Point(rg->fx.computed, rg->fy.computed);
+            Geom::Point c_b = Geom::Point(rg->cx.computed, rg->cy.computed);
+            Geom::Point f_b = Geom::Point(rg->fx.computed, rg->fy.computed);
             double r_b = rg->r.computed;
 
             // converted points in userspace coords
-            NR::Point c_u = c_b * point_convert;
-            NR::Point f_u = f_b * point_convert;
-            double r_u = r_b * point_convert.expansion();
-
-            sp_repr_set_svg_double(repr, "cx", c_u[NR::X]);
-            sp_repr_set_svg_double(repr, "cy", c_u[NR::Y]);
-            sp_repr_set_svg_double(repr, "fx", f_u[NR::X]);
-            sp_repr_set_svg_double(repr, "fy", f_u[NR::Y]);
+            Geom::Point c_u = c_b * point_convert;
+            Geom::Point f_u = f_b * point_convert;
+            double r_u = r_b * point_convert.descrim();
+
+            sp_repr_set_svg_double(repr, "cx", c_u[Geom::X]);
+            sp_repr_set_svg_double(repr, "cy", c_u[Geom::Y]);
+            sp_repr_set_svg_double(repr, "fx", f_u[Geom::X]);
+            sp_repr_set_svg_double(repr, "fy", f_u[Geom::Y]);
             sp_repr_set_svg_double(repr, "r", r_u);
 
         } else {
             SPLinearGradient *lg = SP_LINEARGRADIENT(gr);
 
-            NR::Point p1_b = NR::Point(lg->x1.computed, lg->y1.computed);
-            NR::Point p2_b = NR::Point(lg->x2.computed, lg->y2.computed);
+            Geom::Point p1_b = Geom::Point(lg->x1.computed, lg->y1.computed);
+            Geom::Point p2_b = Geom::Point(lg->x2.computed, lg->y2.computed);
 
-            NR::Point p1_u = p1_b * point_convert;
-            NR::Point p2_u = p2_b * point_convert;
+            Geom::Point p1_u = p1_b * point_convert;
+            Geom::Point p2_u = p2_b * point_convert;
 
-            sp_repr_set_svg_double(repr, "x1", p1_u[NR::X]);
-            sp_repr_set_svg_double(repr, "y1", p1_u[NR::Y]);
-            sp_repr_set_svg_double(repr, "x2", p2_u[NR::X]);
-            sp_repr_set_svg_double(repr, "y2", p2_u[NR::Y]);
+            sp_repr_set_svg_double(repr, "x1", p1_u[Geom::X]);
+            sp_repr_set_svg_double(repr, "y1", p1_u[Geom::Y]);
+            sp_repr_set_svg_double(repr, "x2", p2_u[Geom::X]);
+            sp_repr_set_svg_double(repr, "y2", p2_u[Geom::Y]);
         }
 
         // set the gradientUnits
@@ -431,9 +462,11 @@ sp_gradient_convert_to_userspace(SPGradient *gr, SPItem *item, gchar const *prop
     return gr;
 }
 
-void
-sp_gradient_transform_multiply(SPGradient *gradient, NR::Matrix postmul, bool set)
+void sp_gradient_transform_multiply(SPGradient *gradient, Geom::Matrix postmul, bool set)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_transform_multiply(%p, , %d)", gradient, set);
+#endif
     if (set) {
         gradient->gradientTransform = postmul;
     } else {
@@ -446,24 +479,23 @@ sp_gradient_transform_multiply(SPGradient *gradient, NR::Matrix postmul, bool se
     g_free(c);
 }
 
-SPGradient *
-sp_item_gradient (SPItem *item, bool fill_or_stroke)
+SPGradient *sp_item_gradient(SPItem *item, bool fill_or_stroke)
 {
-    SPStyle *style = SP_OBJECT_STYLE (item);
-    SPGradient *gradient = NULL;
+    SPStyle *style = item->style;
+    SPGradient *gradient = 0;
 
     if (fill_or_stroke) {
         if (style && (style->fill.isPaintserver())) {
-            SPObject *server = SP_OBJECT_STYLE_FILL_SERVER(item);
-            if (SP_IS_GRADIENT (server)) {
-                gradient = SP_GRADIENT (server);
+            SPPaintServer *server = item->style->getFillPaintServer();
+            if ( SP_IS_GRADIENT(server) ) {
+                gradient = SP_GRADIENT(server);
             }
         }
     } else {
         if (style && (style->stroke.isPaintserver())) {
-            SPObject *server = SP_OBJECT_STYLE_STROKE_SERVER(item);
-            if (SP_IS_GRADIENT (server)) {
-                gradient = SP_GRADIENT (server);
+            SPPaintServer *server = item->style->getStrokePaintServer();
+            if ( SP_IS_GRADIENT(server) ) {
+                gradient = SP_GRADIENT(server);
             }
         }
     }
@@ -471,83 +503,86 @@ sp_item_gradient (SPItem *item, bool fill_or_stroke)
    return gradient;
 }
 
-
-SPStop*
-sp_first_stop(SPGradient *gradient)
+SPStop *sp_last_stop(SPGradient *gradient)
 {
-  for (SPObject *ochild = sp_object_first_child(gradient); ochild != NULL; ochild = SP_OBJECT_NEXT(ochild)) {
-       if (SP_IS_STOP (ochild))
-               return SP_STOP(ochild);
-  }
-  return NULL;
+    for (SPStop *stop = gradient->getFirstStop(); stop != NULL; stop = stop->getNextStop()) {
+        if (stop->getNextStop() == NULL)
+            return stop;
+    }
+    return NULL;
 }
 
-SPStop*
-sp_prev_stop(SPStop *stop, SPGradient *gradient)
+SPStop *sp_get_stop_i(SPGradient *gradient, guint stop_i)
 {
-       if (sp_object_first_child(SP_OBJECT(gradient)) == SP_OBJECT(stop))
-               return NULL;
-       SPObject *found = NULL;
-       for ( SPObject *ochild = sp_object_first_child(SP_OBJECT(gradient)) ; ochild != NULL ; ochild = SP_OBJECT_NEXT(ochild) ) {
-               if (SP_IS_STOP (ochild)) {
-                       found = ochild;
-               }
-               if (SP_OBJECT_NEXT(ochild) == SP_OBJECT(stop) || SP_OBJECT(ochild) == SP_OBJECT(stop)) {
-                       break;
-               }
-       }
-       return SP_STOP(found);
+    SPStop *stop = gradient->getFirstStop();
+
+    // if this is valid but weird gradient without an offset-zero stop element,
+    // inkscape has created a handle for the start of gradient anyway,
+    // so when it asks for stop N that corresponds to stop element N-1
+    if (stop->offset != 0)
+        stop_i --;
+
+    for (guint i = 0; i < stop_i; i++) {
+        if (!stop) {
+            return NULL;
+        }
+        stop = stop->getNextStop();
+    }
+
+    return stop;
 }
 
-SPStop*
-sp_next_stop(SPStop *stop)
+guint32 average_color(guint32 c1, guint32 c2, gdouble p)
 {
-  for (SPObject *ochild = SP_OBJECT_NEXT(stop); ochild != NULL; ochild = SP_OBJECT_NEXT(ochild)) {
-       if (SP_IS_STOP (ochild))
-               return SP_STOP(ochild);
-  }
-  return NULL;
+    guint32 r = (guint32) (SP_RGBA32_R_U (c1) * (1 - p) + SP_RGBA32_R_U (c2) * p);
+    guint32 g = (guint32) (SP_RGBA32_G_U (c1) * (1 - p) + SP_RGBA32_G_U (c2) * p);
+    guint32 b = (guint32) (SP_RGBA32_B_U (c1) * (1 - p) + SP_RGBA32_B_U (c2) * p);
+    guint32 a = (guint32) (SP_RGBA32_A_U (c1) * (1 - p) + SP_RGBA32_A_U (c2) * p);
+
+    return SP_RGBA32_U_COMPOSE(r, g, b, a);
 }
 
-SPStop*
-sp_last_stop(SPGradient *gradient)
+SPStop *sp_vector_add_stop(SPGradient *vector, SPStop* prev_stop, SPStop* next_stop, gfloat offset)
 {
-    for (SPStop *stop = sp_first_stop (gradient); stop != NULL; stop = sp_next_stop (stop)) {
-        if (sp_next_stop (stop) == NULL)
-               return stop;
-  }
-  return NULL;
-} 
-
-SPStop*
-sp_get_stop_i(SPGradient *gradient, guint stop_i)
-{            
-  SPStop *stop = sp_first_stop (gradient);
-  
-  for (guint i=0; i < stop_i; i++) {
-    if (!stop) return NULL;  
-    stop = sp_next_stop (stop);    
-  }  
-    
-  return stop;
+#ifdef SP_GR_VERBOSE
+    g_message("sp_vector_add_stop(%p, %p, %p, %f)", vector, prev_stop, next_stop, offset);
+#endif
+
+    Inkscape::XML::Node *new_stop_repr = NULL;
+    new_stop_repr = SP_OBJECT_REPR(prev_stop)->duplicate(SP_OBJECT_REPR(vector)->document());
+    SP_OBJECT_REPR(vector)->addChild(new_stop_repr, SP_OBJECT_REPR(prev_stop));
+
+    SPStop *newstop = (SPStop *) SP_OBJECT_DOCUMENT(vector)->getObjectByRepr(new_stop_repr);
+    newstop->offset = offset;
+    sp_repr_set_css_double( SP_OBJECT_REPR(newstop), "offset", (double)offset);
+    guint32 const c1 = sp_stop_get_rgba32(prev_stop);
+    guint32 const c2 = sp_stop_get_rgba32(next_stop);
+    guint32 cnew = average_color (c1, c2, (offset - prev_stop->offset) / (next_stop->offset - prev_stop->offset));
+    Inkscape::CSSOStringStream os;
+    gchar c[64];
+    sp_svg_write_color (c, sizeof(c), cnew);
+    gdouble opacity = (gdouble) SP_RGBA32_A_F (cnew);
+    os << "stop-color:" << c << ";stop-opacity:" << opacity <<";";
+    SP_OBJECT_REPR (newstop)->setAttribute("style", os.str().c_str());
+    Inkscape::GC::release(new_stop_repr);
+
+    return newstop;
 }
 
-
-void
-sp_item_gradient_edit_stop (SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
+void sp_item_gradient_edit_stop(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
 {
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
     if (!gradient || !SP_IS_GRADIENT(gradient))
         return;
 
-    SPGradient *vector = sp_gradient_get_vector (gradient, false);
+    SPGradient *vector = gradient->getVector();
     switch (point_type) {
         case POINT_LG_BEGIN:
         case POINT_RG_CENTER:
         case POINT_RG_FOCUS:
         {
-            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, sp_first_stop (vector));
+            GtkWidget *dialog = sp_gradient_vector_editor_new (vector, vector->getFirstStop());
             gtk_widget_show (dialog);
         }
         break;
@@ -560,7 +595,7 @@ sp_item_gradient_edit_stop (SPItem *item, guint point_type, guint point_i, bool
             gtk_widget_show (dialog);
         }
         break;
-        
+
         case POINT_LG_MID:
         case POINT_RG_MID1:
         case POINT_RG_MID2:
@@ -574,15 +609,14 @@ sp_item_gradient_edit_stop (SPItem *item, guint point_type, guint point_i, bool
     }
 }
 
-guint32
-sp_item_gradient_stop_query_style (SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
+guint32 sp_item_gradient_stop_query_style(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
 {
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
     if (!gradient || !SP_IS_GRADIENT(gradient))
         return 0;
 
-    SPGradient *vector = sp_gradient_get_vector (gradient, false);
+    SPGradient *vector = gradient->getVector();
 
     if (!vector) // orphan!
         return 0; // what else to do?
@@ -592,7 +626,7 @@ sp_item_gradient_stop_query_style (SPItem *item, guint point_type, guint point_i
         case POINT_RG_CENTER:
         case POINT_RG_FOCUS:
         {
-            SPStop *first = sp_first_stop (vector);
+            SPStop *first = vector->getFirstStop();
             if (first) {
                 return sp_stop_get_rgba32(first);
             }
@@ -609,7 +643,7 @@ sp_item_gradient_stop_query_style (SPItem *item, guint point_type, guint point_i
             }
         }
         break;
-        
+
         case POINT_LG_MID:
         case POINT_RG_MID1:
         case POINT_RG_MID2:
@@ -627,15 +661,17 @@ sp_item_gradient_stop_query_style (SPItem *item, guint point_type, guint point_i
     return 0;
 }
 
-void
-sp_item_gradient_stop_set_style (SPItem *item, guint point_type, guint point_i, bool fill_or_stroke, SPCSSAttr *stop)
+void sp_item_gradient_stop_set_style(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke, SPCSSAttr *stop)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_item_gradient_stop_set_style(%p, %d, %d, %d, %p)", item, point_type, point_i, fill_or_stroke, stop);
+#endif
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
     if (!gradient || !SP_IS_GRADIENT(gradient))
         return;
 
-    SPGradient *vector = sp_gradient_get_vector (gradient, false);
+    SPGradient *vector = gradient->getVector();
 
     if (!vector) // orphan!
         return;
@@ -650,7 +686,7 @@ sp_item_gradient_stop_set_style (SPItem *item, guint point_type, guint point_i,
         case POINT_RG_CENTER:
         case POINT_RG_FOCUS:
         {
-            SPStop *first = sp_first_stop (vector);
+            SPStop *first = vector->getFirstStop();
             if (first) {
                 sp_repr_css_change (SP_OBJECT_REPR (first), stop, "style");
             }
@@ -667,7 +703,7 @@ sp_item_gradient_stop_set_style (SPItem *item, guint point_type, guint point_i,
             }
         }
         break;
-        
+
         case POINT_LG_MID:
         case POINT_RG_MID1:
         case POINT_RG_MID2:
@@ -678,20 +714,22 @@ sp_item_gradient_stop_set_style (SPItem *item, guint point_type, guint point_i,
             }
         }
         break;
-           
+
         default:
             break;
     }
 }
 
-void
-sp_item_gradient_reverse_vector (SPItem *item, bool fill_or_stroke)
+void sp_item_gradient_reverse_vector(SPItem *item, bool fill_or_stroke)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_item_gradient_reverse_vector(%p, %d)", item, fill_or_stroke);
+#endif
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
     if (!gradient || !SP_IS_GRADIENT(gradient))
         return;
 
-    SPGradient *vector = sp_gradient_get_vector (gradient, false);
+    SPGradient *vector = gradient->getVector();
     if (!vector) // orphan!
         return;
 
@@ -703,8 +741,7 @@ sp_item_gradient_reverse_vector (SPItem *item, bool fill_or_stroke)
     GSList *child_reprs = NULL;
     GSList *child_objects = NULL;
     std::vector<double> offsets;
-    for (SPObject *child = sp_object_first_child(vector);
-         child != NULL; child = SP_OBJECT_NEXT(child)) {
+    for ( SPObject *child = vector->firstChild(); child; child = child->getNext()) {
         child_reprs = g_slist_prepend (child_reprs, SP_OBJECT_REPR(child));
         child_objects = g_slist_prepend (child_objects, child);
         offsets.push_back(sp_repr_get_double_attribute(SP_OBJECT_REPR(child), "offset", 0));
@@ -738,28 +775,15 @@ sp_item_gradient_reverse_vector (SPItem *item, bool fill_or_stroke)
 }
 
 
-// FIXME: make general global function
-static double
-get_offset_between_points (NR::Point p, NR::Point begin, NR::Point end)
-{
-    double length = NR::L2(end - begin);
-    NR::Point be = (end - begin) / length;
-    double r = NR::dot(p - begin, be);
-        
-    if (r < 0.0) return 0.0;
-    if (r > length) return 1.0;    
-    
-    return (r / length);
-}
-
-
 /**
 Set the position of point point_type of the gradient applied to item (either fill_or_stroke) to
 p_w (in desktop coordinates). Write_repr if you want the change to become permanent.
 */
-void
-sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::Point p_w, bool fill_or_stroke, bool write_repr, bool scale)
+void sp_item_gradient_set_coords(SPItem *item, guint point_type, guint point_i, Geom::Point p_w, bool fill_or_stroke, bool write_repr, bool scale)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_item_gradient_set_coords(%p, %d, %d, ...)", item, point_type, point_i );
+#endif
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
     if (!gradient || !SP_IS_GRADIENT(gradient))
@@ -767,8 +791,8 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
 
     gradient = sp_gradient_convert_to_userspace (gradient, item, fill_or_stroke? "fill" : "stroke");
 
-    NR::Matrix i2d = sp_item_i2d_affine (item);
-    NR::Point p = p_w * i2d.inverse();
+    Geom::Matrix i2d (item->i2d_affine ());
+    Geom::Point p = p_w * i2d.inverse();
     p *= (gradient->gradientTransform).inverse();
     // now p is in gradient's original coordinates
 
@@ -779,11 +803,11 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
         switch (point_type) {
             case POINT_LG_BEGIN:
                 if (scale) {
-                    lg->x2.computed += (lg->x1.computed - p[NR::X]);
-                    lg->y2.computed += (lg->y1.computed - p[NR::Y]);
+                    lg->x2.computed += (lg->x1.computed - p[Geom::X]);
+                    lg->y2.computed += (lg->y1.computed - p[Geom::Y]);
                 }
-                lg->x1.computed = p[NR::X];
-                lg->y1.computed = p[NR::Y];
+                lg->x1.computed = p[Geom::X];
+                lg->y1.computed = p[Geom::Y];
                 if (write_repr) {
                     if (scale) {
                         sp_repr_set_svg_double(repr, "x2", lg->x2.computed);
@@ -797,11 +821,11 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
                 break;
             case POINT_LG_END:
                 if (scale) {
-                    lg->x1.computed += (lg->x2.computed - p[NR::X]);
-                    lg->y1.computed += (lg->y2.computed - p[NR::Y]);
+                    lg->x1.computed += (lg->x2.computed - p[Geom::X]);
+                    lg->y1.computed += (lg->y2.computed - p[Geom::Y]);
                 }
-                lg->x2.computed = p[NR::X];
-                lg->y2.computed = p[NR::Y];
+                lg->x2.computed = p[Geom::X];
+                lg->y2.computed = p[Geom::Y];
                 if (write_repr) {
                     if (scale) {
                         sp_repr_set_svg_double(repr, "x1", lg->x1.computed);
@@ -812,13 +836,13 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
                 } else {
                     SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
                 }
-                       break;
+                break;
             case POINT_LG_MID:
-            {                              
+            {
                 // using X-coordinates only to determine the offset, assuming p has been snapped to the vector from begin to end.
-                double offset = get_offset_between_points (p, NR::Point(lg->x1.computed, lg->y1.computed), NR::Point(lg->x2.computed, lg->y2.computed));
+                double offset = get_offset_between_points (p, Geom::Point(lg->x1.computed, lg->y1.computed), Geom::Point(lg->x2.computed, lg->y2.computed));
                 SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (lg, false);
-                sp_gradient_ensure_vector(lg);
+                lg->ensureVector();
                 lg->vector.stops.at(point_i).offset = offset;
                 SPStop* stopi = sp_get_stop_i(vector, point_i);
                 stopi->offset = offset;
@@ -829,91 +853,91 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
                 }
             }
             break;
-               default:
-                       break;
-               }
-       } else if (SP_IS_RADIALGRADIENT(gradient)) {
+            default:
+                break;
+        }
+    } else if (SP_IS_RADIALGRADIENT(gradient)) {
         SPRadialGradient *rg = SP_RADIALGRADIENT(gradient);
-        NR::Point c (rg->cx.computed, rg->cy.computed);
-        NR::Point c_w = c * gradient->gradientTransform * i2d; // now in desktop coords
-        if ((point_type == POINT_RG_R1 || point_type == POINT_RG_R2) && NR::L2 (p_w - c_w) < 1e-3) {
+        Geom::Point c (rg->cx.computed, rg->cy.computed);
+        Geom::Point c_w = c * gradient->gradientTransform * i2d; // now in desktop coords
+        if ((point_type == POINT_RG_R1 || point_type == POINT_RG_R2) && Geom::L2 (p_w - c_w) < 1e-3) {
             // prevent setting a radius too close to the center
             return;
         }
-        NR::Matrix new_transform;
+        Geom::Matrix new_transform;
         bool transform_set = false;
 
-               switch (point_type) {
-               case POINT_RG_CENTER:
-                       rg->fx.computed = p[NR::X] + (rg->fx.computed - rg->cx.computed);
-                       rg->fy.computed = p[NR::Y] + (rg->fy.computed - rg->cy.computed);
-                       rg->cx.computed = p[NR::X];
-                       rg->cy.computed = p[NR::Y];
-                       if (write_repr) {
-                               sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
-                               sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
-                               sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
-                               sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
-                       } else {
-                               SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
-                       }
-                       break;
-               case POINT_RG_FOCUS:
-                       rg->fx.computed = p[NR::X];
-                       rg->fy.computed = p[NR::Y];
-                       if (write_repr) {
-                               sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
-                               sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
-                       } else {
-                               SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
-                       }
-                       break;
-               case POINT_RG_R1:
-                       {
-                NR::Point r1_w = (c + NR::Point(rg->r.computed, 0)) * gradient->gradientTransform * i2d;
-                               double r1_angle = NR::atan2(r1_w - c_w);
-                               double move_angle = NR::atan2(p_w - c_w) - r1_angle;
-                               double move_stretch = NR::L2(p_w - c_w) / NR::L2(r1_w - c_w);
-
-                               NR::Matrix move = NR::Matrix (NR::translate (-c_w)) *
-                                                                                                NR::Matrix (NR::rotate(-r1_angle)) *
-                                                                                                NR::Matrix (NR::scale(move_stretch, scale? move_stretch : 1)) *
-                                                                                                NR::Matrix (NR::rotate(r1_angle)) *
-                                                                                                NR::Matrix (NR::rotate(move_angle)) *
-                                                                                                NR::Matrix (NR::translate (c_w));
-
-                               new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
-                               transform_set = true;
-
-                               break;
-                       }
-               case POINT_RG_R2:
-                       {
-                               NR::Point r2_w = (c + NR::Point(0, -rg->r.computed)) * gradient->gradientTransform * i2d;
-                               double r2_angle = NR::atan2(r2_w - c_w);
-                               double move_angle = NR::atan2(p_w - c_w) - r2_angle;
-                               double move_stretch = NR::L2(p_w - c_w) / NR::L2(r2_w - c_w);
-
-                               NR::Matrix move = NR::Matrix (NR::translate (-c_w)) *
-                                                                                                NR::Matrix (NR::rotate(-r2_angle)) *
-                                                                                                NR::Matrix (NR::scale(move_stretch, scale? move_stretch : 1)) *
-                                                                                                NR::Matrix (NR::rotate(r2_angle)) *
-                                                                                                NR::Matrix (NR::rotate(move_angle)) *
-                                                                                                NR::Matrix (NR::translate (c_w));
-
-                               new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
-                               transform_set = true;
+        switch (point_type) {
+            case POINT_RG_CENTER:
+                rg->fx.computed = p[Geom::X] + (rg->fx.computed - rg->cx.computed);
+                rg->fy.computed = p[Geom::Y] + (rg->fy.computed - rg->cy.computed);
+                rg->cx.computed = p[Geom::X];
+                rg->cy.computed = p[Geom::Y];
+                if (write_repr) {
+                    sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
+                    sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
+                    sp_repr_set_svg_double(repr, "cx", rg->cx.computed);
+                    sp_repr_set_svg_double(repr, "cy", rg->cy.computed);
+                } else {
+                    SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
+                }
+                break;
+            case POINT_RG_FOCUS:
+                rg->fx.computed = p[Geom::X];
+                rg->fy.computed = p[Geom::Y];
+                if (write_repr) {
+                    sp_repr_set_svg_double(repr, "fx", rg->fx.computed);
+                    sp_repr_set_svg_double(repr, "fy", rg->fy.computed);
+                } else {
+                    SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
+                }
+                break;
+            case POINT_RG_R1:
+            {
+                Geom::Point r1_w = (c + Geom::Point(rg->r.computed, 0)) * gradient->gradientTransform * i2d;
+                double r1_angle = Geom::atan2(r1_w - c_w);
+                double move_angle = Geom::atan2(p_w - c_w) - r1_angle;
+                double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r1_w - c_w);
+
+                Geom::Matrix move = Geom::Matrix (Geom::Translate (-c_w)) *
+                    Geom::Matrix (Geom::Rotate(-r1_angle)) *
+                    Geom::Matrix (Geom::Scale(move_stretch, scale? move_stretch : 1)) *
+                    Geom::Matrix (Geom::Rotate(r1_angle)) *
+                    Geom::Matrix (Geom::Rotate(move_angle)) *
+                    Geom::Matrix (Geom::Translate (c_w));
+
+                new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
+                transform_set = true;
+
+                break;
+            }
+            case POINT_RG_R2:
+            {
+                Geom::Point r2_w = (c + Geom::Point(0, -rg->r.computed)) * gradient->gradientTransform * i2d;
+                double r2_angle = Geom::atan2(r2_w - c_w);
+                double move_angle = Geom::atan2(p_w - c_w) - r2_angle;
+                double move_stretch = Geom::L2(p_w - c_w) / Geom::L2(r2_w - c_w);
+
+                Geom::Matrix move = Geom::Matrix (Geom::Translate (-c_w)) *
+                    Geom::Matrix (Geom::Rotate(-r2_angle)) *
+                    Geom::Matrix (Geom::Scale(move_stretch, scale? move_stretch : 1)) *
+                    Geom::Matrix (Geom::Rotate(r2_angle)) *
+                    Geom::Matrix (Geom::Rotate(move_angle)) *
+                    Geom::Matrix (Geom::Translate (c_w));
+
+                new_transform = gradient->gradientTransform * i2d * move * i2d.inverse();
+                transform_set = true;
 
                 break;
             }
         case POINT_RG_MID1:
             {
-                NR::Point start = NR::Point (rg->cx.computed, rg->cy.computed);
-                 NR::Point end   = NR::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
+                Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed);
+                 Geom::Point end   = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
                 double offset = get_offset_between_points (p, start, end);
                 SPGradient *vector = sp_gradient_get_forked_vector_if_necessary (rg, false);
-                sp_gradient_ensure_vector(rg);
-                rg->vector.stops.at(point_i).offset = offset; 
+                rg->ensureVector();
+                rg->vector.stops.at(point_i).offset = offset;
                 SPStop* stopi = sp_get_stop_i(vector, point_i);
                 stopi->offset = offset;
                 if (write_repr) {
@@ -924,11 +948,11 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
                 break;
             }
         case POINT_RG_MID2:
-                NR::Point start = NR::Point (rg->cx.computed, rg->cy.computed);
-                NR::Point end   = NR::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
+                Geom::Point start = Geom::Point (rg->cx.computed, rg->cy.computed);
+                Geom::Point end   = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
                 double offset = get_offset_between_points (p, start, end);
                 SPGradient *vector = sp_gradient_get_forked_vector_if_necessary(rg, false);
-                sp_gradient_ensure_vector(rg);
+                rg->ensureVector();
                 rg->vector.stops.at(point_i).offset = offset;
                 SPStop* stopi = sp_get_stop_i(vector, point_i);
                 stopi->offset = offset;
@@ -938,39 +962,41 @@ sp_item_gradient_set_coords (SPItem *item, guint point_type, guint point_i, NR::
                     SP_OBJECT (stopi)->requestModified(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG);
                 }
                 break;
+        }
+
+        if (transform_set) {
+            gradient->gradientTransform = new_transform;
+            gradient->gradientTransform_set = TRUE;
+            if (write_repr) {
+                gchar *s=sp_svg_transform_write(gradient->gradientTransform);
+                SP_OBJECT_REPR(gradient)->setAttribute("gradientTransform", s);
+                g_free(s);
+            } else {
+                SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
             }
-               if (transform_set) {
-                               gradient->gradientTransform = new_transform;
-                               gradient->gradientTransform_set = TRUE;
-                               if (write_repr) {
-                                       gchar *s=sp_svg_transform_write(gradient->gradientTransform);
-                                       SP_OBJECT_REPR(gradient)->setAttribute("gradientTransform", s);
-                                        g_free(s);
-                               } else {
-                                       SP_OBJECT (gradient)->requestModified(SP_OBJECT_MODIFIED_FLAG);
-                               }
-               }
-       }
+        }
+    }
 }
 
-SPGradient *
-sp_item_gradient_get_vector (SPItem *item, bool fill_or_stroke)
+SPGradient *sp_item_gradient_get_vector(SPItem *item, bool fill_or_stroke)
 {
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
-    if (gradient)
-        return sp_gradient_get_vector (gradient, false);
+    if (gradient) {
+        return gradient->getVector();
+    }
     return NULL;
 }
 
-SPGradientSpread
-sp_item_gradient_get_spread (SPItem *item, bool fill_or_stroke)
+SPGradientSpread sp_item_gradient_get_spread(SPItem *item, bool fill_or_stroke)
 {
+    SPGradientSpread spread = SP_GRADIENT_SPREAD_PAD;
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
-    if (gradient)
-        return sp_gradient_get_spread (gradient);
-    return SP_GRADIENT_SPREAD_PAD;
+    if (gradient) {
+        spread = gradient->fetchSpread();
+    }
+    return spread;
 }
 
 
@@ -979,29 +1005,31 @@ Returns the position of point point_type of the gradient applied to item (either
 in desktop coordinates.
 */
 
-NR::Point
-sp_item_gradient_get_coords (SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
+Geom::Point sp_item_gradient_get_coords(SPItem *item, guint point_type, guint point_i, bool fill_or_stroke)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_item_gradient_get_coords(%p, %d, %d, %d)", item, point_type, point_i, fill_or_stroke);
+#endif
     SPGradient *gradient = sp_item_gradient (item, fill_or_stroke);
 
-    NR::Point p (0, 0);
+    Geom::Point p (0, 0);
 
     if (!gradient)
-        return p;
+        return from_2geom(p);
 
     if (SP_IS_LINEARGRADIENT(gradient)) {
         SPLinearGradient *lg = SP_LINEARGRADIENT(gradient);
         switch (point_type) {
             case POINT_LG_BEGIN:
-                p = NR::Point (lg->x1.computed, lg->y1.computed);
+                p = Geom::Point (lg->x1.computed, lg->y1.computed);
                 break;
             case POINT_LG_END:
-                p = NR::Point (lg->x2.computed, lg->y2.computed);
+                p = Geom::Point (lg->x2.computed, lg->y2.computed);
                 break;
             case POINT_LG_MID:
-                {   
+                {
                     gdouble offset = lg->vector.stops.at(point_i).offset;
-                    p = (1-offset) * NR::Point(lg->x1.computed, lg->y1.computed) + offset * NR::Point(lg->x2.computed, lg->y2.computed);
+                    p = (1-offset) * Geom::Point(lg->x1.computed, lg->y1.computed) + offset * Geom::Point(lg->x2.computed, lg->y2.computed);
                 }
                 break;
         }
@@ -1009,43 +1037,43 @@ sp_item_gradient_get_coords (SPItem *item, guint point_type, guint point_i, bool
         SPRadialGradient *rg = SP_RADIALGRADIENT(gradient);
         switch (point_type) {
             case POINT_RG_CENTER:
-                p = NR::Point (rg->cx.computed, rg->cy.computed);
+                p = Geom::Point (rg->cx.computed, rg->cy.computed);
                 break;
             case POINT_RG_FOCUS:
-                p = NR::Point (rg->fx.computed, rg->fy.computed);
+                p = Geom::Point (rg->fx.computed, rg->fy.computed);
                 break;
             case POINT_RG_R1:
-                p = NR::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
+                p = Geom::Point (rg->cx.computed + rg->r.computed, rg->cy.computed);
                 break;
             case POINT_RG_R2:
-                p = NR::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
+                p = Geom::Point (rg->cx.computed, rg->cy.computed - rg->r.computed);
                 break;
             case POINT_RG_MID1:
                 {
                     gdouble offset = rg->vector.stops.at(point_i).offset;
-                    p = (1-offset) * NR::Point (rg->cx.computed, rg->cy.computed) + offset * NR::Point(rg->cx.computed + rg->r.computed, rg->cy.computed);
-                }        
+                    p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed + rg->r.computed, rg->cy.computed);
+                }
                 break;
             case POINT_RG_MID2:
                 {
                     gdouble offset = rg->vector.stops.at(point_i).offset;
-                    p = (1-offset) * NR::Point (rg->cx.computed, rg->cy.computed) + offset * NR::Point(rg->cx.computed, rg->cy.computed - rg->r.computed);
-                }        
+                    p = (1-offset) * Geom::Point (rg->cx.computed, rg->cy.computed) + offset * Geom::Point(rg->cx.computed, rg->cy.computed - rg->r.computed);
+                }
                 break;
         }
     }
 
-    if (SP_GRADIENT(gradient)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
-        sp_document_ensure_up_to_date(SP_OBJECT_DOCUMENT(item));
-        NR::Maybe<NR::Rect> bbox = item->getBounds(NR::identity()); // we need "true" bbox without item_i2d_affine
+    if (SP_GRADIENT(gradient)->getUnits() == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
+        SP_OBJECT_DOCUMENT(item)->ensureUpToDate();
+        Geom::OptRect bbox = item->getBounds(Geom::identity()); // we need "true" bbox without item_i2d_affine
         if (bbox) {
-            p *= NR::Matrix(bbox->dimensions()[NR::X], 0,
-                            0, bbox->dimensions()[NR::Y],
-                            bbox->min()[NR::X], bbox->min()[NR::Y]);
+            p *= Geom::Matrix(bbox->dimensions()[Geom::X], 0,
+                            0, bbox->dimensions()[Geom::Y],
+                            bbox->min()[Geom::X], bbox->min()[Geom::Y]);
         }
     }
-    p *= NR::Matrix(gradient->gradientTransform) * sp_item_i2d_affine(item);
-    return p;
+    p *= Geom::Matrix(gradient->gradientTransform) * (Geom::Matrix)item->i2d_affine();
+    return from_2geom(p);
 }
 
 
@@ -1055,9 +1083,11 @@ sp_item_gradient_get_coords (SPItem *item, guint point_type, guint point_i, bool
  * gr has to be a normalized vector.
  */
 
-SPGradient *
-sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, bool is_fill)
+SPGradient *sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, bool is_fill)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_item_set_gradient(%p, %p, %d, %d)", item, gr, type, is_fill);
+#endif
     g_return_val_if_fail(item != NULL, NULL);
     g_return_val_if_fail(SP_IS_ITEM(item), NULL);
     g_return_val_if_fail(gr != NULL, NULL);
@@ -1079,15 +1109,16 @@ sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, bool is_
         /* Current fill style is the gradient of the required type */
         SPGradient *current = SP_GRADIENT(ps);
 
-        //g_print("hrefcount %d   count %d\n", SP_OBJECT_HREFCOUNT(ig), count_gradient_hrefs(SP_OBJECT(item), ig));
+        //g_message("hrefcount %d   count %d\n", current->hrefcount, count_gradient_hrefs(SP_OBJECT(item), current));
 
-        if (SP_OBJECT_HREFCOUNT(current) == 1 ||
-            SP_OBJECT_HREFCOUNT(current) == count_gradient_hrefs(SP_OBJECT(item), current)) {
+        if (!current->isSwatch()
+            && (current->hrefcount == 1 ||
+            current->hrefcount == count_gradient_hrefs(SP_OBJECT(item), current))) {
 
             // current is private and it's either used once, or all its uses are by children of item;
             // so just change its href to vector
 
-            if ( current != gr && sp_gradient_get_vector(current, false) != gr ) {
+            if ( current != gr && current->getVector() != gr ) {
                 /* href is not the vector */
                 sp_gradient_repr_set_link(SP_OBJECT_REPR(current), gr);
             }
@@ -1123,80 +1154,73 @@ sp_item_set_gradient(SPItem *item, SPGradient *gr, SPGradientType type, bool is_
     }
 }
 
-static void
-sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *link)
+static void sp_gradient_repr_set_link(Inkscape::XML::Node *repr, SPGradient *link)
 {
+#ifdef SP_GR_VERBOSE
+    g_message("sp_gradient_repr_set_link(%p, %p)", repr, link);
+#endif
     g_return_if_fail(repr != NULL);
-    g_return_if_fail(link != NULL);
-    g_return_if_fail(SP_IS_GRADIENT(link));
+    if (link) {
+        g_return_if_fail(SP_IS_GRADIENT(link));
+    }
 
-    gchar *ref;
     if (link) {
-        gchar const *id = SP_OBJECT_ID(link);
-        size_t const len = strlen(id);
-        ref = (gchar*) alloca(len + 2);
-        *ref = '#';
-        memcpy(ref + 1, id, len + 1);
+        Glib::ustring ref("#");
+        ref += link->getId();
+        repr->setAttribute("xlink:href", ref.c_str());
     } else {
-        ref = NULL;
+        repr->setAttribute("xlink:href", 0);
     }
-
-    repr->setAttribute("xlink:href", ref);
 }
 
-/*
- * Get default normalized gradient vector of document, create if there is none
- */
 
-SPGradient *
-sp_document_default_gradient_vector(SPDocument *document, guint32 color)
+static void addStop( Inkscape::XML::Node *parent, Glib::ustring const &color, gint opacity, gchar const *offset )
 {
-    SPDefs *defs = (SPDefs *) SP_DOCUMENT_DEFS(document);
-    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
-
-    Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient");
-
-    repr->setAttribute("inkscape:collect", "always");
-    // set here, but removed when it's edited in the gradient editor
-    // to further reduce clutter, we could
-    // (1) here, search gradients by color and return what is found without duplication
-    // (2) in fill & stroke, show only one copy of each gradient in list
-
-    Inkscape::XML::Node *stop = xml_doc->createElement("svg:stop");
-
-    gchar b[64];
-    sp_svg_write_color(b, 64, color);
-
+#ifdef SP_GR_VERBOSE
+    g_message("addStop(%p, %s, %d, %s)", parent, color.c_str(), opacity, offset);
+#endif
+    Inkscape::XML::Node *stop = parent->document()->createElement("svg:stop");
     {
-        gchar *t = g_strdup_printf("stop-color:%s;stop-opacity:1;", b);
-        stop->setAttribute("style", t);
-        g_free(t);
+        gchar *tmp = g_strdup_printf( "stop-color:%s;stop-opacity:%d;", color.c_str(), opacity );
+        stop->setAttribute( "style", tmp );
+        g_free(tmp);
     }
 
-    stop->setAttribute("offset", "0");
+    stop->setAttribute( "offset", offset );
 
-    repr->appendChild(stop);
+    parent->appendChild(stop);
     Inkscape::GC::release(stop);
+}
 
-    stop = xml_doc->createElement("svg:stop");
+/*
+ * Get default normalized gradient vector of document, create if there is none
+ */
+SPGradient *sp_document_default_gradient_vector( SPDocument *document, SPColor const &color, bool singleStop )
+{
+    SPDefs *defs = static_cast<SPDefs *>(SP_DOCUMENT_DEFS(document));
+    Inkscape::XML::Document *xml_doc = document->rdoc;
 
-    {
-        gchar *t = g_strdup_printf("stop-color:%s;stop-opacity:0;", b);
-        stop->setAttribute("style", t);
-        g_free(t);
-    }
+    Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient");
 
-    stop->setAttribute("offset", "1");
+    if ( !singleStop ) {
+        repr->setAttribute("inkscape:collect", "always");
+        // set here, but removed when it's edited in the gradient editor
+        // to further reduce clutter, we could
+        // (1) here, search gradients by color and return what is found without duplication
+        // (2) in fill & stroke, show only one copy of each gradient in list
+    }
 
-    repr->appendChild(stop);
-    Inkscape::GC::release(stop);
+    Glib::ustring colorStr = color.toString();
+    addStop( repr, colorStr, 1, "0" );
+    if ( !singleStop ) {
+        addStop( repr, colorStr, 0, "1" );
+    }
 
     SP_OBJECT_REPR(defs)->addChild(repr, NULL);
     Inkscape::GC::release(repr);
 
     /* fixme: This does not look like nice */
-    SPGradient *gr;
-    gr = (SPGradient *) document->getObjectByRepr(repr);
+    SPGradient *gr = static_cast<SPGradient *>(document->getObjectByRepr(repr));
     g_assert(gr != NULL);
     g_assert(SP_IS_GRADIENT(gr));
     /* fixme: Maybe add extra sanity check here */
@@ -1209,13 +1233,12 @@ sp_document_default_gradient_vector(SPDocument *document, guint32 color)
 Return the preferred vector for \a o, made from (in order of preference) its current vector,
 current fill or stroke color, or from desktop style if \a o is NULL or doesn't have style.
 */
-SPGradient *
-sp_gradient_vector_for_object(SPDocument *const doc, SPDesktop *const desktop,
-                              SPObject *const o, bool const is_fill)
+SPGradient *sp_gradient_vector_for_object( SPDocument *const doc, SPDesktop *const desktop,
+                                           SPObject *const o, bool const is_fill, bool singleStop )
 {
-    guint32 rgba = 0;
+    SPColor color;
     if (o == NULL || SP_OBJECT_STYLE(o) == NULL) {
-        rgba = sp_desktop_get_color(desktop, is_fill);
+        color = sp_desktop_get_color(desktop, is_fill);
     } else {
         // take the color of the object
         SPStyle const &style = *SP_OBJECT_STYLE(o);
@@ -1223,21 +1246,21 @@ sp_gradient_vector_for_object(SPDocument *const doc, SPDesktop *const desktop,
                                   ? style.fill
                                   : style.stroke );
         if (paint.isPaintserver()) {
-            SPObject *server = is_fill? SP_OBJECT_STYLE_FILL_SERVER(o) : SP_OBJECT_STYLE_STROKE_SERVER(o);
-            if (SP_IS_GRADIENT (server)) {
-                return sp_gradient_get_vector(SP_GRADIENT (server), TRUE);
+            SPObject *server = is_fill? o->style->getFillPaintServer() : o->style->getStrokePaintServer();
+            if ( SP_IS_GRADIENT(server) ) {
+                return SP_GRADIENT(server)->getVector(true);
             } else {
-                rgba = sp_desktop_get_color(desktop, is_fill);
+                color = sp_desktop_get_color(desktop, is_fill);
             }
         } else if (paint.isColor()) {
-            rgba = sp_color_get_rgba32_ualpha(&paint.value.color, 0xff);
+            color = paint.value.color;
         } else {
             // if o doesn't use flat color, then take current color of the desktop.
-            rgba = sp_desktop_get_color(desktop, is_fill);
+            color = sp_desktop_get_color(desktop, is_fill);
         }
     }
 
-    return sp_document_default_gradient_vector(doc, rgba);
+    return sp_document_default_gradient_vector( doc, color, singleStop );
 }
 
 
@@ -1250,4 +1273,4 @@ sp_gradient_vector_for_object(SPDocument *const doc, SPDesktop *const desktop,
   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 :