Code

- proper transformations handling
[inkscape.git] / src / extension / internal / cairo-render-context.cpp
index f308ce15753de2441e9e32106e5b085c3bd6332f..c33beab8a14870c53424c92be46d76a66568a08f 100644 (file)
@@ -116,7 +116,7 @@ CairoRenderContext::CairoRenderContext(CairoRenderer *parent) :
     _stream(NULL),
     _is_valid(FALSE),
     _vector_based_target(FALSE),
-    _cr(NULL),
+    _cr(NULL), // Cairo context
     _surface(NULL),
     _target(CAIRO_SURFACE_TYPE_IMAGE),
     _target_format(CAIRO_FORMAT_ARGB32),
@@ -125,14 +125,27 @@ CairoRenderContext::CairoRenderContext(CairoRenderer *parent) :
     _renderer(parent),
     _render_mode(RENDER_MODE_NORMAL),
     _clip_mode(CLIP_MODE_MASK)
-{}
+{
+    font_table = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, font_data_free);
+}
 
 CairoRenderContext::~CairoRenderContext(void)
 {
+    if(font_table != NULL) {
+        g_hash_table_remove_all(font_table);
+    }
+
     if (_cr) cairo_destroy(_cr);
     if (_surface) cairo_surface_destroy(_surface);
     if (_layout) g_object_unref(_layout);
 }
+void CairoRenderContext::font_data_free(gpointer data)
+{
+    cairo_font_face_t *font_face = (cairo_font_face_t *)data;
+    if (font_face) {
+        cairo_font_face_destroy(font_face);
+    }
+}
 
 CairoRenderer*
 CairoRenderContext::getRenderer(void) const
@@ -192,6 +205,8 @@ CairoRenderContext::cloneMe(double width, double height) const
                                                             (int)ceil(width), (int)ceil(height));
     new_context->_cr = cairo_create(surface);
     new_context->_surface = surface;
+    new_context->_width = width;
+    new_context->_height = height;
     new_context->_is_valid = TRUE;
 
     return new_context;
@@ -481,8 +496,8 @@ void
 CairoRenderContext::setClipMode(CairoClipMode mode)
 {
     switch (mode) {
-        case CLIP_MODE_PATH:
-        case CLIP_MODE_MASK:
+        case CLIP_MODE_PATH: // Clip is rendered as a path for vector output
+        case CLIP_MODE_MASK: // Clip is rendered as a bitmap for raster output.
             _clip_mode = mode;
             break;
         default:
@@ -538,9 +553,23 @@ CairoRenderContext::popLayer(void)
     g_assert( _is_valid );
 
     float opacity = _state->opacity;
-    TRACE(("--popLayer w/ %f\n", opacity));
+    TRACE(("--popLayer w/ opacity %f\n", opacity));
+
+    /*
+     At this point, the Cairo source is ready. A Cairo mask must be created if required.
+     Care must be taken of transformatons as Cairo, like PS and PDF, treats clip paths and
+     masks independently of the objects they effect while in SVG the clip paths and masks
+     are defined relative to the objects they are attached to.
+     Notes:
+     1. An SVG object may have both a clip path and a mask!
+     2. An SVG clip path can be composed of an object with a clip path. This is not handled properly.
+     3. An SVG clipped or masked object may be first drawn off the page and then translated onto
+        the page (document). This is also not handled properly.
+     4. The code converts all SVG masks to bitmaps. This shouldn't be necessary.
+     5. Cairo expects a mask to use only the alpha channel. SVG masks combine the RGB luminance with
+        alpha. This is handled here by doing a pixel by pixel conversion.
+    */
 
-    // apply clipPath or mask if present
     SPClipPath *clip_path = _state->clip_path;
     SPMask *mask = _state->mask;
     if (clip_path || mask) {
@@ -548,15 +577,17 @@ CairoRenderContext::popLayer(void)
         CairoRenderContext *clip_ctx = 0;
         cairo_surface_t *clip_mask = 0;
 
+        // Apply any clip path first
         if (clip_path) {
+            TRACE(("  Applying clip\n"));
             if (_render_mode == RENDER_MODE_CLIP)
                 mask = NULL;    // disable mask when performing nested clipping
 
             if (_vector_based_target) {
-                setClipMode(CLIP_MODE_PATH);
+                setClipMode(CLIP_MODE_PATH); // Vector
                 if (!mask) {
                     cairo_pop_group_to_source(_cr);
-                    _renderer->applyClipPath(this, clip_path);
+                    _renderer->applyClipPath(this, clip_path); // Uses cairo_clip()
                     if (opacity == 1.0)
                         cairo_paint(_cr);
                     else
@@ -570,7 +601,10 @@ CairoRenderContext::popLayer(void)
                 // setup a new rendering context
                 clip_ctx = _renderer->createContext();
                 clip_ctx->setImageTarget(CAIRO_FORMAT_A8);
-                clip_ctx->setClipMode(CLIP_MODE_MASK);
+                clip_ctx->setClipMode(CLIP_MODE_MASK);  // Raster
+                // This code ties the clipping to the document coordinates. It doesn't allow
+                // for a clipped object intially drawn off the page and then translated onto
+                // the page.
                 if (!clip_ctx->setupSurface(_width, _height)) {
                     TRACE(("clip: setupSurface failed\n"));
                     _renderer->destroyContext(clip_ctx);
@@ -583,7 +617,7 @@ CairoRenderContext::popLayer(void)
                 cairo_paint(clip_ctx->_cr);
                 cairo_restore(clip_ctx->_cr);
 
-                // if a mask won't be applied set opacity too
+                // If a mask won't be applied set opacity too. (The clip is represented by a solid Cairo mask.)
                 if (!mask)
                     cairo_set_source_rgba(clip_ctx->_cr, 1.0, 1.0, 1.0, opacity);
                 else
@@ -591,7 +625,7 @@ CairoRenderContext::popLayer(void)
 
                 // copy over the correct CTM
                 // It must be stored in item_transform of current state after pushState.
-                Geom::Matrix item_transform; 
+                Geom::Matrix item_transform;
                 if (_state->parent_has_userspace)
                     item_transform = getParentState()->transform * _state->item_transform;
                 else
@@ -614,7 +648,9 @@ CairoRenderContext::popLayer(void)
             }
         }
 
+        // Apply any mask second
         if (mask) {
+            TRACE(("  Applying mask\n"));
             // create rendering context for mask
             CairoRenderContext *mask_ctx = _renderer->createContext();
 
@@ -685,6 +721,7 @@ CairoRenderContext::popLayer(void)
             _renderer->destroyContext(mask_ctx);
         }
     } else {
+        // No clip path or mask
         cairo_pop_group_to_source(_cr);
         if (opacity == 1.0)
             cairo_paint(_cr);
@@ -727,7 +764,12 @@ CairoRenderContext::setupSurface(double width, double height)
     if (_vector_based_target && _stream == NULL)
         return false;
 
+    _width = width;
+    _height = height;
+
     cairo_surface_t *surface = NULL;
+    cairo_matrix_t ctm;
+    cairo_matrix_init_identity (&ctm);
     switch (_target) {
         case CAIRO_SURFACE_TYPE_IMAGE:
             surface = cairo_image_surface_create(_target_format, (int)ceil(width), (int)ceil(height));
@@ -740,10 +782,10 @@ CairoRenderContext::setupSurface(double width, double height)
 #ifdef CAIRO_HAS_PS_SURFACE
         case CAIRO_SURFACE_TYPE_PS:
             surface = cairo_ps_surface_create_for_stream(Inkscape::Extension::Internal::_write_callback, _stream, width, height);
-#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 5, 2))
             if(CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) {
                 return FALSE;
             }
+#if (CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 5, 2))
             cairo_ps_surface_restrict_to_level (surface, (cairo_ps_level_t)_ps_level);
             cairo_ps_surface_set_eps (surface, (cairo_bool_t) _eps);
 #endif
@@ -754,33 +796,38 @@ CairoRenderContext::setupSurface(double width, double height)
             break;
     }
 
-    return _finishSurfaceSetup (surface);
+    return _finishSurfaceSetup (surface, &ctm);
 }
 
 bool
-CairoRenderContext::setSurfaceTarget(cairo_surface_t *surface, bool is_vector)
+CairoRenderContext::setSurfaceTarget(cairo_surface_t *surface, bool is_vector, cairo_matrix_t *ctm)
 {
     if (_is_valid || !surface)
         return false;
 
     _vector_based_target = is_vector;
-    bool ret = _finishSurfaceSetup (surface);
+    bool ret = _finishSurfaceSetup (surface, ctm);
     if (ret)
         cairo_surface_reference (surface);
     return ret;
 }
 
 bool
-CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface)
+CairoRenderContext::_finishSurfaceSetup(cairo_surface_t *surface, cairo_matrix_t *ctm)
 {
     if(surface == NULL) {
-        return FALSE;
+        return false;
     }
     if(CAIRO_STATUS_SUCCESS != cairo_surface_status(surface)) {
-        return FALSE;
+        return false;
     }
 
     _cr = cairo_create(surface);
+    if(CAIRO_STATUS_SUCCESS != cairo_status(_cr)) {
+        return false;
+    }
+    if (ctm)
+        cairo_set_matrix(_cr, ctm);
     _surface = surface;
 
     if (_vector_based_target) {
@@ -981,7 +1028,7 @@ CairoRenderContext::_createPatternPainter(SPPaintServer const *const paintserver
 
     }
 
-    // Calculate the size of the surface which has to be created 
+    // Calculate the size of the surface which has to be created
 #define SUBPIX_SCALE 100
     // Cairo requires an integer pattern surface width/height.
     // Subtract 0.5 to prevent small rounding errors from increasing pattern size by one pixel.
@@ -1167,7 +1214,8 @@ CairoRenderContext::_createPatternForPaintServer(SPPaintServer const *const pain
 void
 CairoRenderContext::_setFillStyle(SPStyle const *const style, NRRect const *pbox)
 {
-    g_return_if_fail( style->fill.isColor()
+    g_return_if_fail( !style->fill.set
+                      || style->fill.isColor()
                       || style->fill.isPaintserver() );
 
     float alpha = SP_SCALE24_TO_FLOAT(style->fill_opacity.value);
@@ -1181,6 +1229,10 @@ CairoRenderContext::_setFillStyle(SPStyle const *const style, NRRect const *pbox
         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
 
         cairo_set_source_rgba(_cr, rgb[0], rgb[1], rgb[2], alpha);
+
+    } else if (!style->fill.set) { // unset fill is black
+        cairo_set_source_rgba(_cr, 0, 0, 0, alpha);
+
     } else {
         g_assert( style->fill.isPaintserver()
                   || SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style))
@@ -1283,7 +1335,11 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con
         return true;
     }
 
-    if (style->fill.isNone() && style->stroke.isNone())
+    bool no_fill = style->fill.isNone() || style->fill_opacity.value == 0;
+    bool no_stroke = style->stroke.isNone() || style->stroke_width.computed < 1e-9 ||
+                    style->stroke_opacity.value == 0;
+
+    if (no_fill && no_stroke)
         return true;
 
     bool need_layer = ( !_state->merge_opacity && !_state->need_layer &&
@@ -1294,7 +1350,7 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con
     else
         pushLayer();
 
-    if (!style->fill.isNone()) {
+    if (!no_fill) {
         _setFillStyle(style, pbox);
         setPathVector(pathv);
 
@@ -1304,15 +1360,15 @@ CairoRenderContext::renderPathVector(Geom::PathVector const & pathv, SPStyle con
             cairo_set_fill_rule(_cr, CAIRO_FILL_RULE_WINDING);
         }
 
-        if (style->stroke.isNone())
+        if (no_stroke)
             cairo_fill(_cr);
         else
             cairo_fill_preserve(_cr);
     }
 
-    if (!style->stroke.isNone()) {
+    if (!no_stroke) {
         _setStrokeStyle(style, pbox);
-        if (style->fill.isNone())
+        if (no_fill)
             setPathVector(pathv);
 
         cairo_stroke(_cr);
@@ -1407,7 +1463,7 @@ CairoRenderContext::renderImage(guchar *px, unsigned int w, unsigned int h, unsi
 #define GLYPH_ARRAY_SIZE 64
 
 unsigned int
-CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont *font, std::vector<CairoGlyphInfo> const &glyphtext, bool is_stroke)
+CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont *font, std::vector<CairoGlyphInfo> const &glyphtext, bool path)
 {
     cairo_glyph_t glyph_array[GLYPH_ARRAY_SIZE];
     cairo_glyph_t *glyphs = glyph_array;
@@ -1431,10 +1487,11 @@ CairoRenderContext::_showGlyphs(cairo_t *cr, PangoFont *font, std::vector<CairoG
         i++;
     }
 
-    if (is_stroke || _is_texttopath)
+    if (path) {
         cairo_glyph_path(cr, glyphs, num_glyphs - num_invalid_glyphs);
-    else
+    } else {
         cairo_show_glyphs(cr, glyphs, num_glyphs - num_invalid_glyphs);
+    }
 
     if (num_glyphs > GLYPH_ARRAY_SIZE)
         g_free(glyphs);
@@ -1448,10 +1505,11 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Matrix const *font_ma
 {
     // create a cairo_font_face from PangoFont
     double size = style->font_size.computed;
-    cairo_font_face_t *font_face = NULL;
+    gpointer fonthash = (gpointer)font;
+    cairo_font_face_t *font_face = (cairo_font_face_t *)g_hash_table_lookup(font_table, fonthash);
 
     FcPattern *fc_pattern = NULL;
-    
+
 #ifdef USE_PANGO_WIN32
 # ifdef CAIRO_HAS_WIN32_FONT
     LOGFONTA *lfa = pango_win32_font_logfont(font);
@@ -1460,17 +1518,23 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Matrix const *font_ma
     ZeroMemory(&lfw, sizeof(LOGFONTW));
     memcpy(&lfw, lfa, sizeof(LOGFONTA));
     MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, lfa->lfFaceName, LF_FACESIZE, lfw.lfFaceName, LF_FACESIZE);
-    
-    font_face = cairo_win32_font_face_create_for_logfontw(&lfw);
+
+    if(font_face == NULL) {
+        font_face = cairo_win32_font_face_create_for_logfontw(&lfw);
+        g_hash_table_insert(font_table, fonthash, font_face);
+    }
 # endif
 #else
 # ifdef CAIRO_HAS_FT_FONT
     PangoFcFont *fc_font = PANGO_FC_FONT(font);
     fc_pattern = fc_font->font_pattern;
-    font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
+    if(font_face == NULL) {
+        font_face = cairo_ft_font_face_create_for_pattern(fc_pattern);
+        g_hash_table_insert(font_table, fonthash, font_face);
+    }
 # endif
 #endif
-    
+
     cairo_save(_cr);
     cairo_set_font_face(_cr, font_face);
 
@@ -1495,28 +1559,36 @@ CairoRenderContext::renderGlyphtext(PangoFont *font, Geom::Matrix const *font_ma
             _showGlyphs(_cr, font, glyphtext, TRUE);
         }
     } else {
-
+        bool fill = false, stroke = false, have_path = false;
         if (style->fill.isColor() || style->fill.isPaintserver()) {
-            // set fill style
-            _setFillStyle(style, NULL);
-
-            _showGlyphs(_cr, font, glyphtext, FALSE);
+            fill = true;
         }
 
         if (style->stroke.isColor() || style->stroke.isPaintserver()) {
-            // set stroke style
+            stroke = true;
+        }
+        if (fill) {
+            _setFillStyle(style, NULL);
+            if (_is_texttopath) {
+                _showGlyphs(_cr, font, glyphtext, true);
+                have_path = true;
+                if (stroke) cairo_fill_preserve(_cr);
+                else cairo_fill(_cr);
+            } else {
+                _showGlyphs(_cr, font, glyphtext, false);
+            }
+        }
+        if (stroke) {
             _setStrokeStyle(style, NULL);
-
-            // paint stroke
-            _showGlyphs(_cr, font, glyphtext, TRUE);
+            if (!have_path) _showGlyphs(_cr, font, glyphtext, true);
             cairo_stroke(_cr);
         }
     }
 
     cairo_restore(_cr);
 
-    if (font_face)
-        cairo_font_face_destroy(font_face);
+//    if (font_face)
+//        cairo_font_face_destroy(font_face);
 
     return true;
 }