Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / extension / internal / cairo-renderer.cpp
index 5d6a3e2f81ecb62ad14a91e26352c582e462074d..67f9354d8cac97085e57fc87b6f18d90cbc29df8 100644 (file)
@@ -1,11 +1,11 @@
-#define __SP_CAIRO_RENDERER_C__
-
 /** \file
  * Rendering with Cairo.
  */
 /*
  * Author:
  *   Miklos Erdelyi <erdelyim@gmail.com>
+ *   Jon A. Cruz <jon@joncruz.org>
+ *   Abhishek Sharma
  *
  * Copyright (C) 2006 Miklos Erdelyi
  *
 #include <signal.h>
 #include <errno.h>
 
-#include <libnr/n-art-bpath.h>
-#include <libnr/nr-matrix-ops.h>
-#include <libnr/nr-matrix-fns.h>
-#include <libnr/nr-matrix-translate-ops.h>
-#include <libnr/nr-scale-matrix-ops.h>
-
-#include "libnr/nr-matrix-rotate-ops.h"
-#include "libnr/nr-matrix-translate-ops.h"
-#include "libnr/nr-rotate-fns.h"
-#include "libnr/nr-scale-ops.h"
-#include "libnr/nr-scale-translate-ops.h"
-#include "libnr/nr-translate-matrix-ops.h"
-#include "libnr/nr-translate-scale-ops.h"
-#include "libnr/nr-convert2geom.h"
+#include "libnr/nr-rect.h"
+#include "libnrtype/Layout-TNG.h"
 #include <2geom/transforms.h>
 #include <2geom/pathvector.h>
 
@@ -92,6 +80,8 @@
 
 //#define TRACE(_args) g_printf _args
 #define TRACE(_args)
+//#define TEST(_args) _args
+#define TEST(_args)
 
 // FIXME: expose these from sp-clippath/mask.cpp
 struct SPClipPathView {
@@ -113,6 +103,7 @@ namespace Extension {
 namespace Internal {
 
 CairoRenderer::CairoRenderer(void)
+  : _omitText(false)
 {}
 
 CairoRenderer::~CairoRenderer(void)
@@ -136,7 +127,7 @@ CairoRenderer::createContext(void)
 
     // create initial render state
     CairoRenderState *state = new_context->_createState();
-    state->transform.set_identity();
+    state->transform = Geom::identity();
     new_context->_state_stack = g_slist_prepend(new_context->_state_stack, state);
     new_context->_state = state;
 
@@ -166,7 +157,27 @@ static void sp_image_render(SPItem *item, CairoRenderContext *ctx);
 static void sp_symbol_render(SPItem *item, CairoRenderContext *ctx);
 static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx);
 
-/* TODO FIXME: this does not render painting-marker-01-f.svg of SVG1.1 Test suite correctly. (orientation of one of the markers middle left ) */
+static void sp_shape_render_invoke_marker_rendering(SPMarker* marker, Geom::Matrix tr, SPStyle* style, CairoRenderContext *ctx)
+{
+    bool render = true;
+    if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
+        if (style->stroke_width.computed > 1e-9) {
+            tr = Geom::Scale(style->stroke_width.computed) * tr;
+        } else {
+            render = false; // stroke width zero and marker is thus scaled down to zero, skip
+        }
+    }
+
+    if (render) {
+        SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (marker));
+        tr = (Geom::Matrix)marker_item->transform * (Geom::Matrix)marker->c2p * tr;
+        Geom::Matrix old_tr = marker_item->transform;
+        marker_item->transform = tr;
+        ctx->getRenderer()->renderItem (ctx, marker_item);
+        marker_item->transform = old_tr;
+    }
+}
+
 static void sp_shape_render (SPItem *item, CairoRenderContext *ctx)
 {
     NRRect pbox;
@@ -175,91 +186,102 @@ static void sp_shape_render (SPItem *item, CairoRenderContext *ctx)
 
     if (!shape->curve) return;
 
-    /* fixme: Think (Lauris) */
-    sp_item_invoke_bbox(item, &pbox, NR::identity(), TRUE);
+    item->invoke_bbox( &pbox, Geom::identity(), TRUE);
 
     SPStyle* style = SP_OBJECT_STYLE (item);
-    CairoRenderer *renderer = ctx->getRenderer();
-
-    const_NRBPath bp;
-    bp.path = SP_CURVE_BPATH(shape->curve);
 
-    ctx->renderPath(&bp, style, &pbox);
-
-    /* TODO: make code prettier: lots of variables can be taken out of the loop! */
     Geom::PathVector const & pathv = shape->curve->get_pathvector();
-    for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
-        if ( shape->marker[SP_MARKER_LOC_START] ) {
-            SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_START]);
-            SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_START]));
+    if (pathv.empty()) return;
 
-            Geom::Point p = path_it->front().pointAt(0);
-            Geom::Point tang = path_it->front().unitTangentAt(0);
-            NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
+    ctx->renderPathVector(pathv, style, &pbox);
 
-            if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
-                tr = NR::scale(style->stroke_width.computed) * tr;
+    // START marker
+    for (int i = 0; i < 2; i++) {  // SP_MARKER_LOC and SP_MARKER_LOC_START
+        if ( shape->marker[i] ) {
+            SPMarker* marker = SP_MARKER (shape->marker[i]);
+            Geom::Matrix tr;
+            if (marker->orient_auto) {
+                tr = sp_shape_marker_get_transform_at_start(pathv.begin()->front());
+            } else {
+                tr = Geom::Rotate::from_degrees(marker->orient) * Geom::Translate(pathv.begin()->front().pointAt(0));
             }
-
-            tr = marker_item->transform * marker->c2p * tr;
-
-            NR::Matrix old_tr = marker_item->transform;
-            marker_item->transform = tr;
-            renderer->renderItem (ctx, marker_item);
-            marker_item->transform = old_tr;
+            sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx);
         }
-
-        if ( shape->marker[SP_MARKER_LOC_MID] ) {
-            Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
-            Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
-            while (curve_it2 != path_it->end_default())
+    }
+    // MID marker
+    for (int i = 0; i < 3; i += 2) {  // SP_MARKER_LOC and SP_MARKER_LOC_MID
+        if ( !shape->marker[i] ) continue;
+        SPMarker* marker = SP_MARKER (shape->marker[i]);
+        for(Geom::PathVector::const_iterator path_it = pathv.begin(); path_it != pathv.end(); ++path_it) {
+            // START position
+            if ( path_it != pathv.begin() 
+                 && ! ((path_it == (pathv.end()-1)) && (path_it->size_default() == 0)) ) // if this is the last path and it is a moveto-only, there is no mid marker there
             {
-                /* Put marker between curve_it1 and curve_it2.
-                 * Loop to end_default (so including closing segment), because when a path is closed,
-                 * there should be a midpoint marker between last segment and closing straight line segment */
-
-                SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_MID]);
-                SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_MID]));
-
-                Geom::Point p = curve_it1->pointAt(1);
-                Geom::Point tang1 = curve_it1->unitTangentAt(1);
-                Geom::Point tang2 = curve_it2->unitTangentAt(0);
-                NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang1, tang2)));
-
-                if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
-                    tr = NR::scale(style->stroke_width.computed) * tr;
+                Geom::Matrix tr;
+                if (marker->orient_auto) {
+                    tr = sp_shape_marker_get_transform_at_start(path_it->front());
+                } else {
+                    tr = Geom::Rotate::from_degrees(marker->orient) * Geom::Translate(path_it->front().pointAt(0));
                 }
-
-                tr = marker_item->transform * marker->c2p * tr;
-
-                NR::Matrix old_tr = marker_item->transform;
-                marker_item->transform = tr;
-                renderer->renderItem (ctx, marker_item);
-                marker_item->transform = old_tr;
-
-                ++curve_it1;
-                ++curve_it2;
+                sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx);
+            }
+            // MID position
+            if (path_it->size_default() > 1) {
+                Geom::Path::const_iterator curve_it1 = path_it->begin();      // incoming curve
+                Geom::Path::const_iterator curve_it2 = ++(path_it->begin());  // outgoing curve
+                while (curve_it2 != path_it->end_default())
+                {
+                    /* Put marker between curve_it1 and curve_it2.
+                     * Loop to end_default (so including closing segment), because when a path is closed,
+                     * there should be a midpoint marker between last segment and closing straight line segment */
+                    Geom::Matrix tr;
+                    if (marker->orient_auto) {
+                        tr = sp_shape_marker_get_transform(*curve_it1, *curve_it2);
+                    } else {
+                        tr = Geom::Rotate::from_degrees(marker->orient) * Geom::Translate(curve_it1->pointAt(1));
+                    }
+
+                    sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx);
+
+                    ++curve_it1;
+                    ++curve_it2;
+                }
+            }
+            // END position
+            if ( path_it != (pathv.end()-1) && !path_it->empty()) {
+                Geom::Curve const &lastcurve = path_it->back_default();
+                Geom::Matrix tr;
+                if (marker->orient_auto) {
+                    tr = sp_shape_marker_get_transform_at_end(lastcurve);
+                } else {
+                    tr = Geom::Rotate::from_degrees(marker->orient) * Geom::Translate(lastcurve.pointAt(1));
+                }
+                sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx);
             }
         }
-
-        if ( shape->marker[SP_MARKER_LOC_END] ) {
-            SPMarker* marker = SP_MARKER (shape->marker[SP_MARKER_LOC_END]);
-            SPItem* marker_item = sp_item_first_item_child (SP_OBJECT (shape->marker[SP_MARKER_LOC_END]));
-
-            Geom::Point p = path_it->back_default().pointAt(1);
-            Geom::Point tang = path_it->back_default().unitTangentAt(1);
-            NR::Matrix tr(from_2geom(sp_shape_marker_get_transform(p, tang, tang)));
-
-            if (marker->markerUnits == SP_MARKER_UNITS_STROKEWIDTH) {
-                tr = NR::scale(style->stroke_width.computed) * tr;
+    }
+    // END marker
+    for (int i = 0; i < 4; i += 3) {  // SP_MARKER_LOC and SP_MARKER_LOC_END
+        if ( shape->marker[i] ) {
+            SPMarker* marker = SP_MARKER (shape->marker[i]);
+
+            /* Get reference to last curve in the path.
+             * For moveto-only path, this returns the "closing line segment". */
+            Geom::Path const &path_last = pathv.back();
+            unsigned int index = path_last.size_default();
+            if (index > 0) {
+                index--;
             }
+            Geom::Curve const &lastcurve = path_last[index];
 
-            tr = marker_item->transform * marker->c2p * tr;
+            Geom::Matrix tr;
+            if (marker->orient_auto) {
+                tr = sp_shape_marker_get_transform_at_end(lastcurve);
+            } else {
+                tr = Geom::Rotate::from_degrees(marker->orient) * Geom::Translate(lastcurve.pointAt(1));
+            }
 
-            NR::Matrix old_tr = marker_item->transform;
-            marker_item->transform = tr;
-            renderer->renderItem (ctx, marker_item);
-            marker_item->transform = old_tr;
+            sp_shape_render_invoke_marker_rendering(marker, tr, style, ctx);
         }
     }
 }
@@ -268,7 +290,7 @@ static void sp_group_render(SPItem *item, CairoRenderContext *ctx)
 {
     SPGroup *group = SP_GROUP(item);
     CairoRenderer *renderer = ctx->getRenderer();
-    TRACE(("group op: %f\n", SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value)));
+    TRACE(("sp_group_render opacity: %f\n", SP_SCALE24_TO_FLOAT(SP_OBJECT_STYLE(item)->opacity.value)));
 
     GSList *l = g_slist_reverse(group->childList(false));
     while (l) {
@@ -287,7 +309,7 @@ static void sp_use_render(SPItem *item, CairoRenderContext *ctx)
     CairoRenderer *renderer = ctx->getRenderer();
 
     if ((use->x._set && use->x.computed != 0) || (use->y._set && use->y.computed != 0)) {
-        NR::Matrix tp(NR::translate(use->x.computed, use->y.computed));
+        Geom::Matrix tp(Geom::Translate(use->x.computed, use->y.computed));
         ctx->pushState();
         ctx->transform(&tp);
         translated = true;
@@ -344,9 +366,9 @@ static void sp_image_render(SPItem *item, CairoRenderContext *ctx)
         ctx->addClippingRect(image->x.computed, image->y.computed, image->width.computed, image->height.computed);
     }
 
-    NR::translate tp(x, y);
-    NR::scale s(width / (double)w, height / (double)h);
-    NR::Matrix t(s * tp);
+    Geom::Translate tp(x, y);
+    Geom::Scale s(width / (double)w, height / (double)h);
+    Geom::Matrix t(s * tp);
 
     ctx->renderImage (px, w, h, rs, &t, SP_OBJECT_STYLE (item));
 }
@@ -363,7 +385,7 @@ static void sp_symbol_render(SPItem *item, CairoRenderContext *ctx)
 
     // apply viewbox if set
     if (0 /*symbol->viewBox_set*/) {
-        NR::Matrix vb2user;
+        Geom::Matrix vb2user;
         double x, y, width, height;
         double view_width, view_height;
         x = 0.0;
@@ -378,7 +400,7 @@ static void sp_symbol_render(SPItem *item, CairoRenderContext *ctx)
                                      &x, &y,&width, &height);
 
         // [itemTransform *] translate(x, y) * scale(w/vw, h/vh) * translate(-vx, -vy);
-        vb2user.set_identity();
+        vb2user = Geom::identity();
         vb2user[0] = width / view_width;
         vb2user[3] = height / view_height;
         vb2user[4] = x - symbol->viewBox.x0 * vb2user[0];
@@ -401,143 +423,89 @@ static void sp_root_render(SPItem *item, CairoRenderContext *ctx)
 
     ctx->pushState();
     renderer->setStateForItem(ctx, item);
-    ctx->transform(&root->c2p);
+    Geom::Matrix tempmat (root->c2p);
+    ctx->transform(&tempmat);
     sp_group_render(item, ctx);
     ctx->popState();
 }
 
 /**
-    this function convert the item to a raster image and include the raster into the cairo renderer
+    This function converts the item to a raster image and includes the image into the cairo renderer.
+    It is only used for filters and then only when rendering filters as bitmaps is requested.
 */
 static void sp_asbitmap_render(SPItem *item, CairoRenderContext *ctx)
 {
-    g_warning("render as bitmap");
-
-    //the code now was copied from sp_selection_create_bitmap_copy
-
-    SPDocument *document = SP_OBJECT(item)->document;
-    Inkscape::XML::Document *xml_doc = sp_document_repr_doc(document);
 
-    // Get the bounding box of the selection
-    //NR::Maybe<NR::Rect> _bbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
-    // NRRect bbox = item->getBounds(from_2geom(sp_item_i2d_affine(item)));
-    NRRect bbox(item->getBounds(from_2geom(sp_item_i2d_affine(item))));
-
-
-    // List of the items to show; all others will be hidden
-    GSList *items = NULL; //g_slist_copy ((GSList *) selection->itemList());
-    items = g_slist_append(items, item);
-
-    // Remember parent and z-order of the topmost one
-    gint pos = SP_OBJECT_REPR(g_slist_last(items)->data)->position();
-    SPObject *parent_object = SP_OBJECT_PARENT(g_slist_last(items)->data);
-    Inkscape::XML::Node *parent = SP_OBJECT_REPR(parent_object);
+    // The code was adapted from sp_selection_create_bitmap_copy in selection-chemistry.cpp
 
     // Calculate resolution
     double res;
-    /** @TODO reimplement the resolution stuff
+    /** @TODO reimplement the resolution stuff   (WHY?)
     */
     res = ctx->getBitmapResolution();
     if(res == 0) {
         res = PX_PER_IN;
     }
+    TRACE(("sp_asbitmap_render: resolution: %f\n", res ));
+
+    // Get the bounding box of the selection in document coordinates.
+    Geom::OptRect bbox = 
+           item->getBounds(item->i2d_affine(), SPItem::RENDERING_BBOX);
 
+    if (!bbox) // no bbox, e.g. empty group
+        return;
 
     // The width and height of the bitmap in pixels
-    unsigned width = (unsigned) floor ((bbox.x1 - bbox.x0) * res / PX_PER_IN);
-    unsigned height =(unsigned) floor ((bbox.y1 - bbox.y0) * res / PX_PER_IN);
-
-    // Find out if we have to run a filter
-    gchar const *run = NULL;
-    gchar const *filter = NULL;
-    /** @TODO reimplement the filter stuff
-    //gchar const *filter = prefs_get_string_attribute ("options.createbitmap", "filter");
-    if (filter) {
-        // filter command is given;
-        // see if we have a parameter to pass to it
-        gchar const *param1 = prefs_get_string_attribute ("options.createbitmap", "filter_param1");
-        if (param1) {
-            if (param1[strlen(param1) - 1] == '%') {
-                // if the param string ends with %, interpret it as a percentage of the image's max dimension
-                gchar p1[256];
-                g_ascii_dtostr (p1, 256, ceil (g_ascii_strtod (param1, NULL) * MAX(width, height) / 100));
-                // the first param is always the image filename, the second is param1
-                run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, p1);
-            } else {
-                // otherwise pass the param1 unchanged
-                run = g_strdup_printf ("%s \"%s\" %s", filter, filepath, param1);
-            }
-        } else {
-            // run without extra parameter
-            run = g_strdup_printf ("%s \"%s\"", filter, filepath);
-        }
+    unsigned width = (unsigned) floor ((bbox->max()[Geom::X] - bbox->min()[Geom::X]) * (res / PX_PER_IN));
+    unsigned height =(unsigned) floor ((bbox->max()[Geom::Y] - bbox->min()[Geom::Y]) * (res / PX_PER_IN));
+    
+    // Scale to exactly fit integer bitmap inside bounding box
+    double scale_x = (bbox->max()[Geom::X] - bbox->min()[Geom::X]) / width;
+    double scale_y = (bbox->max()[Geom::Y] - bbox->min()[Geom::Y]) / height;
+
+    // Location of bounding box in document coordinates.
+    double shift_x = bbox->min()[Geom::X];
+    double shift_y = bbox->max()[Geom::Y];
+
+    // For default 90 dpi, snap bitmap to pixel grid
+    if (res == PX_PER_IN) { 
+        shift_x = round (shift_x);
+        shift_y = -round (-shift_y); // Correct rounding despite coordinate inversion.
+                                     // Remove the negations when the inversion is gone.
     }
-    */
+
     // Calculate the matrix that will be applied to the image so that it exactly overlaps the source objects
-    NR::Matrix eek = from_2geom(sp_item_i2d_affine (SP_ITEM(parent_object)));
-    NR::Matrix t;
 
-    double shift_x = bbox.x0;
-    double shift_y = bbox.y1;
-    if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
-        shift_x = round (shift_x);
-        shift_y = -round (-shift_y); // this gets correct rounding despite coordinate inversion, remove the negations when the inversion is gone
-    }
-    t = (NR::Matrix)(NR::scale(1, -1) * (NR::Matrix)(NR::translate (shift_x, shift_y)* eek.inverse()));
+    // Matix to put bitmap in correct place on document
+    Geom::Matrix t_on_document = (Geom::Matrix)(Geom::Scale (scale_x, -scale_y)) *
+                                 (Geom::Matrix)(Geom::Translate (shift_x, shift_y));
 
-    //t = t * ((NR::Matrix)ctx->getCurrentState()->transform).inverse();
+    // ctx matrix already includes item transformation. We must substract.
+    Geom::Matrix t_item =  item->i2d_affine ();
+    Geom::Matrix t = t_on_document * t_item.inverse();
 
     // Do the export
+    SPDocument *document = SP_OBJECT(item)->document;
+    GSList *items = NULL;
+    items = g_slist_append(items, item);
+
     GdkPixbuf *pb = sp_generate_internal_bitmap(document, NULL,
-        bbox.x0, bbox.y0, bbox.x1, bbox.y1, width, height, res, res, (guint32) 0xffffff00, items );
+        bbox->min()[Geom::X], bbox->min()[Geom::Y], bbox->max()[Geom::X], bbox->max()[Geom::Y], 
+        width, height, res, res, (guint32) 0xffffff00, items );
 
-    // Run filter, if any
-    /*
-    if (run) {
-        g_print ("Running external filter: %s\n", run);
-        system (run);
-    }
-    */
     if (pb) {
+        TEST(gdk_pixbuf_save( pb, "bitmap.png", "png", NULL, NULL ));
         unsigned char *px = gdk_pixbuf_get_pixels (pb);
         unsigned int w = gdk_pixbuf_get_width(pb);
         unsigned int h = gdk_pixbuf_get_height(pb);
         unsigned int rs = gdk_pixbuf_get_rowstride(pb);
-        NR::Matrix matrix;
-        matrix = t;
-        //matrix = ((NR::Matrix)ctx->getCurrentState()->transform).inverse();
-        //matrix.set_identity();
-
-        ctx->renderImage (px, w, h, rs, &matrix, SP_OBJECT_STYLE (item));
-    /*
-        // Create the repr for the image
-        Inkscape::XML::Node * repr = xml_doc->createElement("svg:image");
-        repr->setAttribute("xlink:href", filename);
-        repr->setAttribute("sodipodi:absref", filepath);
-        if (res == PX_PER_IN) { // for default 90 dpi, snap it to pixel grid
-            sp_repr_set_svg_double(repr, "width", width);
-            sp_repr_set_svg_double(repr, "height", height);
-        } else {
-            sp_repr_set_svg_double(repr, "width", (bbox.x1 - bbox.x0));
-            sp_repr_set_svg_double(repr, "height", (bbox.y1 - bbox.y0));
-        }
-
-        // Write transform
-        gchar *c=sp_svg_transform_write(t);
-        repr->setAttribute("transform", c);
-        g_free(c);
-
-        // add the new repr to the parent
-        parent->appendChild(repr);
-
-        // move to the saved position
-        repr->setPosition(pos > 0 ? pos + 1 : 1);
-    */
+        ctx->renderImage (px, w, h, rs, &t, SP_OBJECT_STYLE (item));
         gdk_pixbuf_unref (pb);
     }
     g_slist_free (items);
 }
 
+
 static void sp_item_invoke_render(SPItem *item, CairoRenderContext *ctx)
 {
     // Check item's visibility
@@ -587,6 +555,7 @@ CairoRenderer::setStateForItem(CairoRenderContext *ctx, SPItem const *item)
     CairoRenderState *state = ctx->getCurrentState();
     state->clip_path = item->clip_ref->getObject();
     state->mask = item->mask_ref->getObject();
+    state->item_transform = Geom::Matrix (item->transform);
 
     // If parent_has_userspace is true the parent state's transform
     // has to be used for the mask's/clippath's context.
@@ -595,23 +564,30 @@ CairoRenderer::setStateForItem(CairoRenderContext *ctx, SPItem const *item)
     // transformation before rendering the item.
     if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item) || SP_IS_IMAGE(item))
         state->parent_has_userspace = TRUE;
-    TRACE(("set op: %f\n", state->opacity));
+    TRACE(("setStateForItem opacity: %f\n", state->opacity));
 }
 
 void
 CairoRenderer::renderItem(CairoRenderContext *ctx, SPItem *item)
 {
+    if ( _omitText && (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) ) {
+        // skip text if _omitText is true
+        return;
+    }
+
     ctx->pushState();
     setStateForItem(ctx, item);
 
     CairoRenderState *state = ctx->getCurrentState();
     state->need_layer = ( state->mask || state->clip_path || state->opacity != 1.0 );
 
+    // Draw item on a temporary surface so a mask, clip path, or opacity can be applied to it.
     if (state->need_layer) {
         state->merge_opacity = FALSE;
         ctx->pushLayer();
     }
-    ctx->transform(&item->transform);
+    Geom::Matrix tempmat (item->transform);
+    ctx->transform(&tempmat);
     sp_item_invoke_render(item, ctx);
 
     if (state->need_layer)
@@ -621,43 +597,57 @@ CairoRenderer::renderItem(CairoRenderContext *ctx, SPItem *item)
 }
 
 bool
-CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc)
+CairoRenderer::setupDocument(CairoRenderContext *ctx, SPDocument *doc, bool pageBoundingBox, SPItem *base)
 {
+// PLEASE note when making changes to the boundingbox and transform calculation, corresponding changes should be made to PDFLaTeXRenderer::setupDocument !!!
+
     g_assert( ctx != NULL );
 
-    if (ctx->_vector_based_target) {
-        // width and height in pt
-        ctx->_width = sp_document_width(doc) * PT_PER_PX;
-        ctx->_height = sp_document_height(doc) * PT_PER_PX;
-    } else {
-        ctx->_width = sp_document_width(doc);
-        ctx->_height = sp_document_height(doc);
+    if (!base) {
+        base = SP_ITEM(doc->getRoot());
     }
 
     NRRect d;
-    bool pageBoundingBox = true;
     if (pageBoundingBox) {
         d.x0 = d.y0 = 0;
-        d.x1 = ceil(ctx->_width);
-        d.y1 = ceil(ctx->_height);
+        d.x1 = doc->getWidth();
+        d.y1 = doc->getHeight();
     } else {
-        SPItem* doc_item = SP_ITEM(sp_document_root(doc));
-        sp_item_invoke_bbox(doc_item, &d, from_2geom(sp_item_i2r_affine(doc_item)), TRUE);
-        if (ctx->_vector_based_target) {
-            // convert from px to pt
-            d.x0 *= PT_PER_PX;
-            d.x1 *= PT_PER_PX;
-            d.y0 *= PT_PER_PX;
-            d.y1 *= PT_PER_PX;
-        }
+        base->invoke_bbox( &d, base->i2d_affine(), TRUE, SPItem::RENDERING_BBOX);
+    }
+
+    if (ctx->_vector_based_target) {
+        // convert from px to pt
+        d.x0 *= PT_PER_PX;
+        d.x1 *= PT_PER_PX;
+        d.y0 *= PT_PER_PX;
+        d.y1 *= PT_PER_PX;
     }
-    TRACE(("%f x %f\n", ctx->_width, ctx->_height));
 
-    return ctx->setupSurface(d.x1-d.x0, d.y1-d.y0);
+    ctx->_width = d.x1-d.x0;
+    ctx->_height = d.y1-d.y0;
+
+    TRACE(("setupDocument: %f x %f\n", ctx->_width, ctx->_height));
+
+    bool ret = ctx->setupSurface(ctx->_width, ctx->_height);
+
+    if (ret && !pageBoundingBox)
+    {
+        double high = doc->getHeight();
+        if (ctx->_vector_based_target)
+            high *= PT_PER_PX;
+
+        Geom::Matrix tp(Geom::Translate(-d.x0 * (ctx->_vector_based_target ? PX_PER_PT : 1.0),
+                                    (d.y1 - high) * (ctx->_vector_based_target ? PX_PER_PT : 1.0)));
+        ctx->transform(&tp);
+    }
+    
+    return ret;
 }
 
 #include "macros.h" // SP_PRINT_*
 
+// Apply an SVG clip path
 void
 CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp)
 {
@@ -669,11 +659,11 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp)
     CairoRenderContext::CairoRenderMode saved_mode = ctx->getRenderMode();
     ctx->setRenderMode(CairoRenderContext::RENDER_MODE_CLIP);
 
-    NR::Matrix saved_ctm;
+    Geom::Matrix saved_ctm;
     if (cp->clipPathUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX) {
         //SP_PRINT_DRECT("clipd", cp->display->bbox);
         NRRect clip_bbox(cp->display->bbox);
-        NR::Matrix t(NR::scale(clip_bbox.x1 - clip_bbox.x0, clip_bbox.y1 - clip_bbox.y0));
+        Geom::Matrix t(Geom::Scale(clip_bbox.x1 - clip_bbox.x0, clip_bbox.y1 - clip_bbox.y0));
         t[4] = clip_bbox.x0;
         t[5] = clip_bbox.y0;
         t *= ctx->getCurrentState()->transform;
@@ -683,10 +673,20 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp)
 
     TRACE(("BEGIN clip\n"));
     SPObject *co = SP_OBJECT(cp);
-    for (SPObject *child = sp_object_first_child(co) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
+    for ( SPObject *child = co->firstChild() ; child; child = child->getNext() ) {
         if (SP_IS_ITEM(child)) {
             SPItem *item = SP_ITEM(child);
-            renderItem(ctx, item);
+
+            // combine transform of the item in clippath and the item using clippath:
+            Geom::Matrix tempmat (item->transform);
+            tempmat = tempmat * (ctx->getCurrentState()->item_transform);
+
+            // render this item in clippath
+            ctx->pushState();
+            ctx->transform(&tempmat);
+            setStateForItem(ctx, item);
+            sp_item_invoke_render(item, ctx);
+            ctx->popState();
         }
     }
     TRACE(("END clip\n"));
@@ -702,6 +702,7 @@ CairoRenderer::applyClipPath(CairoRenderContext *ctx, SPClipPath const *cp)
     ctx->setRenderMode(saved_mode);
 }
 
+// Apply an SVG mask
 void
 CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask)
 {
@@ -714,21 +715,23 @@ CairoRenderer::applyMask(CairoRenderContext *ctx, SPMask const *mask)
     NRRect mask_bbox(mask->display->bbox);
     // TODO: should the bbox be transformed if maskUnits != userSpaceOnUse ?
     if (mask->maskContentUnits == SP_CONTENT_UNITS_OBJECTBOUNDINGBOX) {
-        NR::Matrix t(NR::scale(mask_bbox.x1 - mask_bbox.x0, mask_bbox.y1 - mask_bbox.y0));
+        Geom::Matrix t(Geom::Scale(mask_bbox.x1 - mask_bbox.x0, mask_bbox.y1 - mask_bbox.y0));
         t[4] = mask_bbox.x0;
         t[5] = mask_bbox.y0;
         t *= ctx->getCurrentState()->transform;
         ctx->setTransform(&t);
     }
 
-    // clip mask contents
-    ctx->addClippingRect(mask_bbox.x0, mask_bbox.y0, mask_bbox.x1 - mask_bbox.x0, mask_bbox.y1 - mask_bbox.y0);
+    // Clip mask contents... but...
+    // The mask's bounding box is the "geometric bounding box" which doesn't allow for
+    // filters which extend outside the bounding box. So don't clip.
+    // ctx->addClippingRect(mask_bbox.x0, mask_bbox.y0, mask_bbox.x1 - mask_bbox.x0, mask_bbox.y1 - mask_bbox.y0);
 
     ctx->pushState();
 
     TRACE(("BEGIN mask\n"));
     SPObject *co = SP_OBJECT(mask);
-    for (SPObject *child = sp_object_first_child(co) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
+    for ( SPObject *child = co->firstChild() ; child; child = child->getNext() ) {
         if (SP_IS_ITEM(child)) {
             SPItem *item = SP_ITEM(child);
             renderItem(ctx, item);
@@ -811,4 +814,4 @@ calculatePreserveAspectRatio(unsigned int aspect_align, unsigned int aspect_clip
   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 :