rsvg-cairo-draw.c 36.5 KB
Newer Older
1 2
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set sw=4 sts=4 ts=4 expandtab: */
3
/*
Caleb Michael Moore's avatar
Caleb Michael Moore committed
4
   rsvg-shapes.c: Draw shapes with cairo
5

Caleb Michael Moore's avatar
Caleb Michael Moore committed
6 7
   Copyright (C) 2005 Dom Lachowicz <cinamod@hotmail.com>
   Copyright (C) 2005 Caleb Moore <c.moore@student.unsw.edu.au>
8
   Copyright (C) 2005 Red Hat, Inc.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this program; if not, write to the
   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.

25
   Authors: Dom Lachowicz <cinamod@hotmail.com>,
26
            Caleb Moore <c.moore@student.unsw.edu.au>
27
            Carl Worth <cworth@cworth.org>
28 29 30 31
*/

#include "rsvg-cairo-draw.h"
#include "rsvg-cairo-render.h"
Caleb Michael Moore's avatar
Caleb Michael Moore committed
32
#include "rsvg-cairo-clip.h"
33
#include "rsvg-styles.h"
34
#include "rsvg-path-builder.h"
35
#include "rsvg-filter.h"
36
#include "rsvg-structure.h"
37
#include "rsvg-image.h"
38 39

#include <math.h>
40
#include <string.h>
41

42
#include <pango/pangocairo.h>
43
#include <pango/pangofc-fontmap.h>
44
static gboolean
45
add_color_stop_to_gradient (RsvgNode *node, gpointer data)
46
{
47
    Gradient *gradient = data;
48 49 50 51 52 53 54 55
    RsvgGradientStop *stop;

    if (rsvg_node_type (node) != RSVG_NODE_TYPE_STOP)
        return TRUE; /* just ignore this node */

    stop = (RsvgGradientStop *) node;

    if (!stop->is_valid) {
56
        /* Don't add any more stops. */
57 58 59
        return FALSE;
    }

60
    gradient_add_color_stop (gradient, stop->offset, stop->rgba);
61 62 63 64

    return TRUE;
}

65 66
static void
add_color_stops_to_gradient (Gradient *gradient, RsvgNode *node)
67
{
68
    rsvg_node_foreach_child (node, add_color_stop_to_gradient, gradient);
69 70
}

71 72
static Gradient *
linear_gradient_to_rust (RsvgLinearGradient *linear)
73
{
74
    Gradient *gradient;
75

76 77 78 79 80 81 82 83
    gradient = gradient_linear_new (linear->hasx1 ? &linear->x1 : NULL,
                                    linear->hasy1 ? &linear->y1 : NULL,
                                    linear->hasx2 ? &linear->x2 : NULL,
                                    linear->hasy2 ? &linear->y2 : NULL,
                                    linear->hasbbox ? &linear->obj_bbox : NULL,
                                    linear->hastransform ? &linear->affine : NULL,
                                    linear->hasspread ? &linear->spread : NULL,
                                    linear->fallback);
84

85
    add_color_stops_to_gradient (gradient, (RsvgNode *) linear);
86

87
    return gradient;
88 89
}

90 91
static Gradient *
radial_gradient_to_rust (RsvgRadialGradient *radial)
92
{
93
    Gradient *gradient;
94

95 96 97 98 99 100 101 102 103
    gradient = gradient_radial_new (radial->hascx ? &radial->cx : NULL,
                                    radial->hascy ? &radial->cy : NULL,
                                    radial->hasr  ? &radial->r  : NULL,
                                    radial->hasfx ? &radial->fx : NULL,
                                    radial->hasfy ? &radial->fy : NULL,
                                    radial->hasbbox ? &radial->obj_bbox : NULL,
                                    radial->hastransform ? &radial->affine : NULL,
                                    radial->hasspread ? &radial->spread : NULL,
                                    radial->fallback);
104

105
    add_color_stops_to_gradient (gradient, (RsvgNode *) radial);
106

107
    return gradient;
108 109
}

110 111
Gradient *
rsvg_gradient_node_to_rust_gradient (RsvgNode *node)
112
{
113 114 115 116 117 118
    if (rsvg_node_type (node) == RSVG_NODE_TYPE_LINEAR_GRADIENT) {
        return linear_gradient_to_rust ((RsvgLinearGradient *) node);
    } else if (rsvg_node_type (node) == RSVG_NODE_TYPE_RADIAL_GRADIENT) {
        return radial_gradient_to_rust ((RsvgRadialGradient *) node);
    } else {
        return NULL;
119
    }
120
}
121

122 123 124 125 126 127
static void
_set_source_rsvg_linear_gradient (RsvgDrawingCtx *ctx,
                                  RsvgLinearGradient *linear,
                                  guint8 opacity, RsvgBbox bbox)
{
    Gradient *gradient;
128

129
    gradient = linear_gradient_to_rust (linear);
130

131
    gradient_resolve_fallbacks_and_set_pattern (gradient, ctx, opacity, bbox);
132

133
    gradient_destroy (gradient);
134 135
}

136
static void
137 138
_set_source_rsvg_radial_gradient (RsvgDrawingCtx * ctx,
                                  RsvgRadialGradient * radial,
139
                                  guint8 opacity, RsvgBbox bbox)
140
{
141
    Gradient *gradient;
142

143
    gradient = radial_gradient_to_rust (radial);
144

145
    gradient_resolve_fallbacks_and_set_pattern (gradient, ctx, opacity, bbox);
146

147
    gradient_destroy (gradient);
148 149 150
}

static void
151 152
_set_source_rsvg_solid_color (RsvgDrawingCtx * ctx,
                              RsvgSolidColor * color, guint8 opacity, guint32 current_color)
153
{
154 155
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
    cairo_t *cr = render->cr;
156
    guint32 argb = color->argb;
157
    double r, g, b, a;
158

159 160
    if (color->currentcolor)
        argb = current_color;
161

162 163 164 165
    r = ((argb >> 16) & 0xff) / 255.0;
    g = ((argb >>  8) & 0xff) / 255.0;
    b = ((argb >>  0) & 0xff) / 255.0;
    a =  (argb >> 24) / 255.0 * (opacity / 255.0);
166

167
    cairo_set_source_rgba (cr, r, g, b, a);
168 169
}

170
static gboolean
171
_set_source_rsvg_pattern (RsvgDrawingCtx * ctx,
172
                          RsvgPattern * rsvg_pattern, RsvgBbox bbox)
173
{
174
    Pattern *pattern;
175
    gboolean result;
176

177
    pattern = rsvg_pattern_node_to_rust_pattern ((RsvgNode *) rsvg_pattern);
178

179
    result = pattern_resolve_fallbacks_and_set_pattern (pattern, ctx, bbox);
180

181
    pattern_destroy (pattern);
182 183

    return result;
184 185
}

186
/* note: _set_source_rsvg_paint_server does not change cairo's CTM */
187
static gboolean
188 189 190
_set_source_rsvg_paint_server (RsvgDrawingCtx * ctx,
                               guint32 current_color_rgb,
                               RsvgPaintServer * ps,
191
                               guint8 opacity, RsvgBbox bbox, guint32 current_color)
192
{
193
    RsvgNode *node;
194 195 196
    gboolean had_paint_server;

    had_paint_server = FALSE;
197

198
    switch (ps->type) {
199
    case RSVG_PAINT_SERVER_IRI:
200
        node = rsvg_drawing_ctx_acquire_node (ctx, ps->core.iri->iri_str);
201 202
        if (node == NULL)
            break;
203
        else if (rsvg_node_type (node) == RSVG_NODE_TYPE_LINEAR_GRADIENT) {
204
            _set_source_rsvg_linear_gradient (ctx, (RsvgLinearGradient *) node, opacity, bbox);
205 206
            had_paint_server = TRUE;
        } else if (rsvg_node_type (node) == RSVG_NODE_TYPE_RADIAL_GRADIENT) {
207
            _set_source_rsvg_radial_gradient (ctx, (RsvgRadialGradient *) node, opacity, bbox);
208 209 210 211 212 213 214 215 216 217 218
            had_paint_server = TRUE;
        } else if (rsvg_node_type (node) == RSVG_NODE_TYPE_PATTERN) {
            if (_set_source_rsvg_pattern (ctx, (RsvgPattern *) node, bbox)) {
                had_paint_server = TRUE;
            } else {
                if (ps->core.iri->has_alternate) {
                    _set_source_rsvg_solid_color (ctx, &ps->core.iri->alternate, opacity, current_color);
                    had_paint_server = TRUE;
                }
            }
        }
219

220
        rsvg_drawing_ctx_release_node (ctx, node);
221 222
        break;
    case RSVG_PAINT_SERVER_SOLID:
223
        _set_source_rsvg_solid_color (ctx, ps->core.color, opacity, current_color);
224
        had_paint_server = TRUE;
225 226
        break;
    }
227 228

    return had_paint_server;
229 230
}

231
static void
232
_set_rsvg_affine (RsvgCairoRender * render, cairo_matrix_t *affine)
233
{
234
    cairo_t * cr = render->cr;
235
    cairo_matrix_t matrix;
236
    gboolean nest = cr != render->initial_cr;
237

238
    cairo_matrix_init (&matrix,
239 240 241 242
                       affine->xx, affine->yx,
                       affine->xy, affine->yy,
                       affine->x0 + (nest ? 0 : render->offset_x),
                       affine->y0 + (nest ? 0 : render->offset_y));
243
    cairo_set_matrix (cr, &matrix);
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258
static cairo_font_options_t *
get_font_options_for_testing (void)
{
    cairo_font_options_t *options;

    options = cairo_font_options_create ();
    cairo_font_options_set_antialias (options, CAIRO_ANTIALIAS_GRAY);
    cairo_font_options_set_hint_style (options, CAIRO_HINT_STYLE_FULL);
    cairo_font_options_set_hint_metrics (options, CAIRO_HINT_METRICS_ON);

    return options;
}

259 260 261 262 263 264 265 266 267 268
static void
set_font_options_for_testing (PangoContext *context)
{
    cairo_font_options_t *font_options;

    font_options = get_font_options_for_testing ();
    pango_cairo_context_set_font_options (context, font_options);
    cairo_font_options_destroy (font_options);
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
static void
create_font_config_for_testing (RsvgCairoRender *render)
{
    const char *font_path = SRCDIR "/tests/resources/LiberationSans-Regular.ttf";

    if (render->font_config_for_testing != NULL)
        return;

    render->font_config_for_testing = FcConfigCreate ();

    if (!FcConfigAppFontAddFile (render->font_config_for_testing, (const FcChar8 *) font_path)) {
        g_error ("Could not load font file \"%s\" for tests; aborting", font_path);
    }
}

static PangoFontMap *
get_font_map_for_testing (RsvgCairoRender *render)
{
    PangoFontMap *font_map;

    create_font_config_for_testing (render);

    font_map = pango_cairo_font_map_new_for_font_type (CAIRO_FONT_TYPE_FT);
    pango_fc_font_map_set_config (PANGO_FC_FONT_MAP (font_map), render->font_config_for_testing);

    return font_map;
}

297
PangoContext *
298
rsvg_cairo_create_pango_context (RsvgDrawingCtx * ctx)
299
{
300 301
    PangoFontMap *fontmap;
    PangoContext *context;
302
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
303
    double dpi_y;
304

305 306 307 308 309 310
    if (ctx->is_testing) {
        fontmap = get_font_map_for_testing (render);
    } else {
        fontmap = pango_cairo_font_map_get_default ();
    }

311
    context = pango_font_map_create_context (fontmap);
312
    pango_cairo_update_context (render->cr, context);
313 314 315 316

    rsvg_drawing_ctx_get_dpi (ctx, NULL, &dpi_y);
    pango_cairo_context_set_resolution (context, dpi_y);

317
    if (ctx->is_testing) {
318
        set_font_options_for_testing (context);
319 320
    }

321
    return context;
322 323
}

324 325 326
static void
setup_cr_for_stroke (cairo_t *cr, RsvgDrawingCtx *ctx, RsvgState *state)
{
327
    cairo_set_line_width (cr, rsvg_get_normalized_stroke_width (ctx));
328 329 330 331
    cairo_set_miter_limit (cr, state->miter_limit);
    cairo_set_line_cap (cr, (cairo_line_cap_t) state->cap);
    cairo_set_line_join (cr, (cairo_line_join_t) state->join);
    cairo_set_dash (cr, state->dash.dash, state->dash.n_dash,
332
                    rsvg_length_normalize (&state->dash.offset, ctx));
333 334
}

335
void
336
rsvg_cairo_render_pango_layout (RsvgDrawingCtx * ctx, PangoLayout * layout, double x, double y)
337
{
338
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
339
    RsvgState *state = rsvg_current_state (ctx);
340
    PangoRectangle ink;
341
    RsvgBbox bbox;
342 343
    PangoGravity gravity = pango_context_get_gravity (pango_layout_get_context (layout));
    double rotation;
344

345
    cairo_set_antialias (render->cr, state->text_rendering_type);
346

347
    _set_rsvg_affine (render, &state->affine);
348

349
    pango_layout_get_extents (layout, &ink, NULL);
350

351
    rsvg_bbox_init (&bbox, &state->affine);
352 353 354 355 356 357 358 359 360 361 362
    if (PANGO_GRAVITY_IS_VERTICAL (gravity)) {
        bbox.rect.x = x + (ink.x - ink.height) / (double)PANGO_SCALE;
        bbox.rect.y = y + ink.y / (double)PANGO_SCALE;
        bbox.rect.width = ink.height / (double)PANGO_SCALE;
        bbox.rect.height = ink.width / (double)PANGO_SCALE;
    } else {
        bbox.rect.x = x + ink.x / (double)PANGO_SCALE;
        bbox.rect.y = y + ink.y / (double)PANGO_SCALE;
        bbox.rect.width = ink.width / (double)PANGO_SCALE;
        bbox.rect.height = ink.height / (double)PANGO_SCALE;
    }
363 364
    bbox.virgin = 0;

365
    rotation = pango_gravity_to_rotation (gravity);
366
    if (state->fill) {
367
        cairo_save (render->cr);
Hiroyuki Ikezoe's avatar
Hiroyuki Ikezoe committed
368 369
        cairo_move_to (render->cr, x, y);
        rsvg_bbox_insert (&render->bbox, &bbox);
370 371 372 373 374 375 376 377 378 379 380

        if (_set_source_rsvg_paint_server (ctx,
                                           state->current_color,
                                           state->fill,
                                           state->fill_opacity,
                                           bbox, rsvg_current_state (ctx)->current_color)) {
            if (rotation != 0.)
                cairo_rotate (render->cr, -rotation);
            pango_cairo_show_layout (render->cr, layout);
        }

381
        cairo_restore (render->cr);
382 383 384
    }

    if (state->stroke) {
385
        cairo_save (render->cr);
386 387
        cairo_move_to (render->cr, x, y);
        rsvg_bbox_insert (&render->bbox, &bbox);
388

389 390 391 392 393 394 395 396
        if (_set_source_rsvg_paint_server (ctx,
                                           state->current_color,
                                           state->stroke,
                                           state->stroke_opacity,
                                           bbox, rsvg_current_state (ctx)->current_color)) {
            if (rotation != 0.)
                cairo_rotate (render->cr, -rotation);
            pango_cairo_layout_path (render->cr, layout);
397

398
            setup_cr_for_stroke (render->cr, ctx, state);
399

400 401
            cairo_stroke (render->cr);
        }
402

403
        cairo_restore (render->cr);
404
    }
405 406
}

407 408


409
void
410
rsvg_cairo_render_path_builder (RsvgDrawingCtx * ctx, RsvgPathBuilder *builder)
411
{
412
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
413
    RsvgState *state = rsvg_current_state (ctx);
414 415
    cairo_t *cr;
    RsvgBbox bbox;
416
    double backup_tolerance;
417

418
    rsvg_cairo_push_discrete_layer (ctx);
419 420 421

    cr = render->cr;

422
    cairo_set_antialias (cr, state->shape_rendering_type);
423

424
    _set_rsvg_affine (render, &state->affine);
425

426
    setup_cr_for_stroke (cr, ctx, state);
427

428
    rsvg_path_builder_add_to_cairo_context (builder, cr);
429

430
    rsvg_bbox_init (&bbox, &state->affine);
431

432 433 434 435 436 437
    backup_tolerance = cairo_get_tolerance (cr);
    cairo_set_tolerance (cr, 1.0);
    /* dropping the precision of cairo's bezier subdivision, yielding 2x
       _rendering_ time speedups, are these rather expensive operations
       really needed here? */

438 439 440 441 442 443 444 445 446
    /* Bounding box for fill
     *
     * Unlike the case for stroke, for fills we always compute the bounding box.
     * In GNOME we have SVGs for symbolic icons where each icon has a bounding
     * rectangle with no fill and no stroke, and inside it there are the actual
     * paths for the icon's shape.  We need to be able to compute the bounding
     * rectangle's extents, even when it has no fill nor stroke.
     */
    {
447
        RsvgBbox fb;
448
        rsvg_bbox_init (&fb, &state->affine);
449 450 451
        cairo_fill_extents (cr, &fb.rect.x, &fb.rect.y, &fb.rect.width, &fb.rect.height);
        fb.rect.width -= fb.rect.x;
        fb.rect.height -= fb.rect.y;
452 453 454
        fb.virgin = 0;
        rsvg_bbox_insert (&bbox, &fb);
    }
455 456

    /* Bounding box for stroke */
457 458
    if (state->stroke != NULL) {
        RsvgBbox sb;
459
        rsvg_bbox_init (&sb, &state->affine);
460 461 462
        cairo_stroke_extents (cr, &sb.rect.x, &sb.rect.y, &sb.rect.width, &sb.rect.height);
        sb.rect.width -= sb.rect.x;
        sb.rect.height -= sb.rect.y;
463 464 465 466
        sb.virgin = 0;
        rsvg_bbox_insert (&bbox, &sb);
    }

467 468
    cairo_set_tolerance (cr, backup_tolerance);

469 470 471 472
    rsvg_bbox_insert (&render->bbox, &bbox);

    if (state->fill != NULL) {
        int opacity;
473 474

        cairo_set_fill_rule (cr, state->fill_rule);
475

476
        opacity = state->fill_opacity;
477

478 479 480 481 482 483 484 485 486
        if (_set_source_rsvg_paint_server (ctx,
                                           state->current_color,
                                           state->fill,
                                           opacity, bbox, rsvg_current_state (ctx)->current_color)) {
            if (state->stroke != NULL)
                cairo_fill_preserve (cr);
            else
                cairo_fill (cr);
        }
487 488 489 490
    }

    if (state->stroke != NULL) {
        int opacity;
491
        opacity = state->stroke_opacity;
492

493 494 495 496 497 498
        if (_set_source_rsvg_paint_server (ctx,
                                           state->current_color,
                                           state->stroke,
                                           opacity, bbox, rsvg_current_state (ctx)->current_color)) {
            cairo_stroke (cr);
        }
499 500
    }

501 502
    cairo_new_path (cr); /* clear the path in case stroke == fill == NULL; otherwise we leave it around from computing the bounding box */

503
    rsvg_cairo_pop_discrete_layer (ctx);
504 505
}

506
void
507
rsvg_cairo_render_surface (RsvgDrawingCtx *ctx,
508
                           cairo_surface_t *surface,
509 510 511
                           double src_x,
                           double src_y,
                           double w,
512
                           double h)
513
{
514
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
515
    RsvgState *state = rsvg_current_state (ctx);
516

517 518
    int width, height;
    double dwidth, dheight;
519 520
    RsvgBbox bbox;

521
    if (surface == NULL)
522 523
        return;

524
    g_return_if_fail (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_IMAGE);
525

526 527 528
    dwidth = width = cairo_image_surface_get_width (surface);
    dheight = height = cairo_image_surface_get_height (surface);
    if (width == 0 || height == 0)
529 530
        return;

531
    rsvg_bbox_init (&bbox, &state->affine);
532 533
    bbox.rect.x = src_x;
    bbox.rect.y = src_y;
534 535
    bbox.rect.width = w;
    bbox.rect.height = h;
536
    bbox.virgin = 0;
Caleb Michael Moore's avatar
Caleb Michael Moore committed
537

538
    _set_rsvg_affine (render, &state->affine);
539
    cairo_scale (render->cr, w / dwidth, h / dheight);
540 541
    src_x *= dwidth / w;
    src_y *= dheight / h;
542

543
    cairo_set_operator (render->cr, state->comp_op);
544

545
#if 1
546
    cairo_set_source_surface (render->cr, surface, src_x, src_y);
547
#else
548 549 550
    {
        cairo_pattern_t *pattern;
        cairo_matrix_t matrix;
551

552 553
        pattern = cairo_pattern_create_for_surface (surface);
        cairo_pattern_set_extend (pattern, CAIRO_EXTEND_PAD);
554

555
        cairo_matrix_init_translate (&matrix, -src_x, -src_y);
556
        cairo_pattern_set_matrix (pattern, &matrix);
557

558 559 560
        cairo_set_source (render->cr, pattern);
        cairo_pattern_destroy (pattern);
    }
561 562
#endif

563
    cairo_paint (render->cr);
564

565
    rsvg_bbox_insert (&render->bbox, &bbox);
566
}
567

568 569 570 571 572 573 574 575
cairo_t *
rsvg_cairo_get_cairo_context (RsvgDrawingCtx *ctx)
{
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);

    return render->cr;
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
/* FIXME: Usage of this function is more less a hack.  Some code does this:
 *
 *   save_cr = rsvg_cairo_get_cairo_context (ctx);
 *
 *   some_surface = create_surface ();
 *
 *   cr = cairo_create (some_surface);
 *
 *   rsvg_cairo_set_cairo_context (ctx, cr);
 *
 *   ... draw with ctx but to that temporary surface
 *
 *   rsvg_cairo_set_cairo_context (ctx, save_cr);
 *
 * It would be better to have an explicit push/pop for the cairo_t, or
 * pushing a temporary surface, or something that does not involve
 * monkeypatching the cr directly.
 */
void
rsvg_cairo_set_cairo_context (RsvgDrawingCtx *ctx, cairo_t *cr)
{
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);

    render->cr = cr;
}

Dom Lachowicz's avatar
Dom Lachowicz committed
602
static void
603
rsvg_cairo_generate_mask (cairo_t * cr, RsvgMask * self, RsvgDrawingCtx * ctx, RsvgBbox * bbox)
Caleb Michael Moore's avatar
Caleb Michael Moore committed
604
{
605
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
606 607
    cairo_surface_t *surface;
    cairo_t *mask_cr, *save_cr;
608
    RsvgState *state = rsvg_current_state (ctx);
609 610 611
    guint8 *pixels;
    guint32 width = render->width, height = render->height;
    guint32 rowstride = width * 4, row, i;
612
    cairo_matrix_t affinesave;
613
    double sx, sy, sw, sh;
614
    gboolean nest = cr != render->initial_cr;
615

616 617 618 619 620 621 622 623
    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
    if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
        cairo_surface_destroy (surface);
        return;
    }

    pixels = cairo_image_surface_get_data (surface);
    rowstride = cairo_image_surface_get_stride (surface);
624

625
    if (self->maskunits == objectBoundingBox)
626
        rsvg_drawing_ctx_push_view_box (ctx, 1, 1);
627

628 629 630 631
    sx = rsvg_length_normalize (&self->x, ctx);
    sy = rsvg_length_normalize (&self->y, ctx);
    sw = rsvg_length_normalize (&self->width, ctx);
    sh = rsvg_length_normalize (&self->height, ctx);
632 633

    if (self->maskunits == objectBoundingBox)
634
        rsvg_drawing_ctx_pop_view_box (ctx);
635 636 637 638 639 640 641

    mask_cr = cairo_create (surface);
    save_cr = render->cr;
    render->cr = mask_cr;

    if (self->maskunits == objectBoundingBox)
        rsvg_cairo_add_clipping_rect (ctx,
642 643 644 645
                                      sx * bbox->rect.width + bbox->rect.x,
                                      sy * bbox->rect.height + bbox->rect.y,
                                      sw * bbox->rect.width,
                                      sh * bbox->rect.height);
646 647 648 649 650
    else
        rsvg_cairo_add_clipping_rect (ctx, sx, sy, sw, sh);

    /* Horribly dirty hack to have the bbox premultiplied to everything */
    if (self->contentunits == objectBoundingBox) {
651 652 653 654 655 656 657 658 659 660
        cairo_matrix_t bbtransform;
        cairo_matrix_init (&bbtransform,
                           bbox->rect.width,
                           0,
                           0,
                           bbox->rect.height,
                           bbox->rect.x,
                           bbox->rect.y);
        affinesave = self->super.state->affine;
        cairo_matrix_multiply (&self->super.state->affine, &bbtransform, &self->super.state->affine);
661
        rsvg_drawing_ctx_push_view_box (ctx, 1, 1);
662 663 664 665 666 667 668
    }

    rsvg_state_push (ctx);
    _rsvg_node_draw_children (&self->super, ctx, 0);
    rsvg_state_pop (ctx);

    if (self->contentunits == objectBoundingBox) {
669
        rsvg_drawing_ctx_pop_view_box (ctx);
670
        self->super.state->affine = affinesave;
671 672 673 674 675 676 677 678
    }

    render->cr = save_cr;

    for (row = 0; row < height; row++) {
        guint8 *row_data = (pixels + (row * rowstride));
        for (i = 0; i < width; i++) {
            guint32 *pixel = (guint32 *) row_data + i;
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
            /*
             *  Assuming, the pixel is linear RGB (not sRGB)
             *  y = luminance
             *  Y = 0.2126 R + 0.7152 G + 0.0722 B
             *  1.0 opacity = 255
             *
             *  When Y = 1.0, pixel for mask should be 0xFFFFFFFF
             *  	(you get 1.0 luminance from 255 from R, G and B)
             *
             *	r_mult = 0xFFFFFFFF / (255.0 * 255.0) * .2126 = 14042.45  ~= 14042
             *	g_mult = 0xFFFFFFFF / (255.0 * 255.0) * .7152 = 47239.69  ~= 47240
             *	b_mult = 0xFFFFFFFF / (255.0 * 255.0) * .0722 =  4768.88  ~= 4769
             *
             * 	This allows for the following expected behaviour:
             *  (we only care about the most sig byte)
             *	if pixel = 0x00FFFFFF, pixel' = 0xFF......
             *	if pixel = 0x00020202, pixel' = 0x02......
             *	if pixel = 0x00000000, pixel' = 0x00......
             */
            *pixel = ((((*pixel & 0x00ff0000) >> 16) * 14042 +
                       ((*pixel & 0x0000ff00) >>  8) * 47240 +
                       ((*pixel & 0x000000ff)      ) * 4769    ) * state->opacity);
701 702 703 704 705
        }
    }

    cairo_destroy (mask_cr);

706 707 708 709
    cairo_identity_matrix (cr);
    cairo_mask_surface (cr, surface,
                        nest ? 0 : render->offset_x,
                        nest ? 0 : render->offset_y);
710
    cairo_surface_destroy (surface);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
711 712 713
}

static void
714
rsvg_cairo_push_render_stack (RsvgDrawingCtx * ctx)
715
{
716
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
717 718 719
    cairo_surface_t *surface;
    cairo_t *child_cr;
    RsvgBbox *bbox;
720
    RsvgState *state = rsvg_current_state (ctx);
721 722
    gboolean lateclip = FALSE;

723 724
    if (rsvg_current_state (ctx)->clip_path) {
        RsvgNode *node;
725
        node = rsvg_drawing_ctx_acquire_node_of_type (ctx, rsvg_current_state (ctx)->clip_path, RSVG_NODE_TYPE_CLIP_PATH);
726
        if (node) {
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
            RsvgClipPath *clip_path = (RsvgClipPath *) node;

            switch (clip_path->units) {
            case userSpaceOnUse:
                rsvg_cairo_clip (ctx, clip_path, NULL);
                break;
            case objectBoundingBox:
                lateclip = TRUE;
                break;

            default:
                g_assert_not_reached ();
                break;
            }

742
            rsvg_drawing_ctx_release_node (ctx, node);
743 744
        }
    }
745 746

    if (state->opacity == 0xFF
747
        && !state->filter && !state->mask && !lateclip && (state->comp_op == CAIRO_OPERATOR_OVER)
748 749
        && (state->enable_background == RSVG_ENABLE_BACKGROUND_ACCUMULATE))
        return;
750 751

    if (!state->filter) {
752 753 754
        surface = cairo_surface_create_similar (cairo_get_target (render->cr),
                                                CAIRO_CONTENT_COLOR_ALPHA,
                                                render->width, render->height);
755
    } else {
756
        surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
757 758 759 760 761 762 763 764 765 766
                                              render->width, render->height);

        /* The surface reference is owned by the child_cr created below and put on the cr_stack! */
        render->surfaces_stack = g_list_prepend (render->surfaces_stack, surface);
    }

#if 0
    if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
        cairo_surface_destroy (surface);
        return;
767
    }
768 769
#endif

770 771 772 773 774 775 776 777 778
    child_cr = cairo_create (surface);
    cairo_surface_destroy (surface);

    render->cr_stack = g_list_prepend (render->cr_stack, render->cr);
    render->cr = child_cr;

    bbox = g_new (RsvgBbox, 1);
    *bbox = render->bbox;
    render->bb_stack = g_list_prepend (render->bb_stack, bbox);
779
    rsvg_bbox_init (&render->bbox, &state->affine);
780 781 782
}

void
783
rsvg_cairo_push_discrete_layer (RsvgDrawingCtx * ctx)
Caleb Michael Moore's avatar
Caleb Michael Moore committed
784
{
785 786 787
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);

    cairo_save (render->cr);
788
    rsvg_cairo_push_render_stack (ctx);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
789 790 791
}

static void
792
rsvg_cairo_pop_render_stack (RsvgDrawingCtx * ctx)
793
{
794
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
795
    cairo_t *child_cr = render->cr;
796
    RsvgClipPath *lateclip = NULL;
797
    cairo_surface_t *surface = NULL;
798
    RsvgState *state = rsvg_current_state (ctx);
799
    gboolean nest, needs_destroy = FALSE;
800

801 802
    if (rsvg_current_state (ctx)->clip_path) {
        RsvgNode *node;
803
        node = rsvg_drawing_ctx_acquire_node_of_type (ctx, rsvg_current_state (ctx)->clip_path, RSVG_NODE_TYPE_CLIP_PATH);
804
        if (node && ((RsvgClipPath *) node)->units == objectBoundingBox)
805
            lateclip = (RsvgClipPath *) node;
806
        else
807
            rsvg_drawing_ctx_release_node (ctx, node);
808
    }
809 810

    if (state->opacity == 0xFF
811
        && !state->filter && !state->mask && !lateclip && (state->comp_op == CAIRO_OPERATOR_OVER)
812 813
        && (state->enable_background == RSVG_ENABLE_BACKGROUND_ACCUMULATE))
        return;
814

815 816
    surface = cairo_get_target (child_cr);

817
    if (state->filter) {
818
        RsvgNode *filter;
819
        cairo_surface_t *output;
820

821 822
        output = render->surfaces_stack->data;
        render->surfaces_stack = g_list_delete_link (render->surfaces_stack, render->surfaces_stack);
823

824
        filter = rsvg_drawing_ctx_acquire_node_of_type (ctx, state->filter, RSVG_NODE_TYPE_FILTER);
825
        if (filter) {
826
            needs_destroy = TRUE;
827
            surface = rsvg_filter_render ((RsvgFilter *) filter, output, ctx, &render->bbox, "2103");
828
            rsvg_drawing_ctx_release_node (ctx, filter);
829

830 831
            /* Don't destroy the output surface, it's owned by child_cr */
        }
832
    }
833 834

    render->cr = (cairo_t *) render->cr_stack->data;
835
    render->cr_stack = g_list_delete_link (render->cr_stack, render->cr_stack);
836

837 838 839 840 841
    nest = render->cr != render->initial_cr;
    cairo_identity_matrix (render->cr);
    cairo_set_source_surface (render->cr, surface,
                              nest ? 0 : render->offset_x,
                              nest ? 0 : render->offset_y);
842

843
    if (lateclip) {
844
        rsvg_cairo_clip (ctx, lateclip, &render->bbox);
845
        rsvg_drawing_ctx_release_node (ctx, (RsvgNode *) lateclip);
846
    }
847

848
    cairo_set_operator (render->cr, state->comp_op);
849

850
    if (state->mask) {
851 852
        RsvgNode *mask;

853
        mask = rsvg_drawing_ctx_acquire_node_of_type (ctx, state->mask, RSVG_NODE_TYPE_MASK);
854 855
        if (mask) {
            rsvg_cairo_generate_mask (render->cr, (RsvgMask *) mask, ctx, &render->bbox);
856
            rsvg_drawing_ctx_release_node (ctx, mask);
857
        }
858 859
    } else if (state->opacity != 0xFF)
        cairo_paint_with_alpha (render->cr, (double) state->opacity / 255.0);
860
    else
861
        cairo_paint (render->cr);
862

863
    cairo_destroy (child_cr);
864

865
    rsvg_bbox_insert ((RsvgBbox *) render->bb_stack->data, &render->bbox);
866

867
    render->bbox = *((RsvgBbox *) render->bb_stack->data);
868

869
    g_free (render->bb_stack->data);
870
    render->bb_stack = g_list_delete_link (render->bb_stack, render->bb_stack);
871

872
    if (needs_destroy) {
873
        cairo_surface_destroy (surface);
874
    }
875 876
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
877
void
878
rsvg_cairo_pop_discrete_layer (RsvgDrawingCtx * ctx)
Caleb Michael Moore's avatar
Caleb Michael Moore committed
879
{
880 881
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);

882
    rsvg_cairo_pop_render_stack (ctx);
883
    cairo_restore (render->cr);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
884 885
}

886 887
void
rsvg_cairo_add_clipping_rect (RsvgDrawingCtx * ctx, double x, double y, double w, double h)
888
{
889
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
890
    cairo_t *cr = render->cr;
Caleb Michael Moore's avatar
Caleb Michael Moore committed
891

892
    _set_rsvg_affine (render, &rsvg_current_state (ctx)->affine);
893

894 895
    cairo_rectangle (cr, x, y, w, h);
    cairo_clip (cr);
896 897
}

898 899
cairo_surface_t *
rsvg_cairo_get_surface_of_node (RsvgDrawingCtx *ctx,
900 901
                                RsvgNode *drawable,
                                double width,
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
                                double height)
{
    cairo_surface_t *surface;
    cairo_t *cr;

    RsvgCairoRender *save_render = (RsvgCairoRender *) ctx->render;
    RsvgCairoRender *render;

    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
    if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
        cairo_surface_destroy (surface);
        return NULL;
    }

    cr = cairo_create (surface);

    render = rsvg_cairo_render_new (cr, width, height);
    ctx->render = (RsvgRender *) render;

    rsvg_node_draw (drawable, ctx, 0);

    cairo_destroy (cr);

    rsvg_render_free (ctx->render);
    ctx->render = (RsvgRender *) save_render;

    return surface;
}

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
cairo_surface_t *
rsvg_cairo_surface_from_pixbuf (const GdkPixbuf *pixbuf)
{
    gint width, height, gdk_rowstride, n_channels, cairo_rowstride;
    guchar *gdk_pixels, *cairo_pixels;
    cairo_format_t format;
    cairo_surface_t *surface;
    int j;

    if (pixbuf == NULL)
        return NULL;

    width = gdk_pixbuf_get_width (pixbuf);
    height = gdk_pixbuf_get_height (pixbuf);
    gdk_pixels = gdk_pixbuf_get_pixels (pixbuf);
    gdk_rowstride = gdk_pixbuf_get_rowstride (pixbuf);
    n_channels = gdk_pixbuf_get_n_channels (pixbuf);

    if (n_channels == 3)
        format = CAIRO_FORMAT_RGB24;
    else
        format = CAIRO_FORMAT_ARGB32;

    surface = cairo_image_surface_create (format, width, height);
    if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
        cairo_surface_destroy (surface);
957
        return NULL;
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    }

    cairo_pixels = cairo_image_surface_get_data (surface);
    cairo_rowstride = cairo_image_surface_get_stride (surface);

    if (n_channels == 3) {
        for (j = height; j; j--) {
            guchar *p = gdk_pixels;
            guchar *q = cairo_pixels;
            guchar *end = p + 3 * width;

            while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
                q[0] = p[2];
                q[1] = p[1];
                q[2] = p[0];
#else
                q[1] = p[0];
                q[2] = p[1];
                q[3] = p[2];
#endif
                p += 3;
                q += 4;
            }

            gdk_pixels += gdk_rowstride;
            cairo_pixels += cairo_rowstride;
        }
    } else {
        for (j = height; j; j--) {
            guchar *p = gdk_pixels;
            guchar *q = cairo_pixels;
            guchar *end = p + 4 * width;
            guint t1, t2, t3;

#define MULT(d,c,a,t) G_STMT_START { t = c * a + 0x7f; d = ((t >> 8) + t) >> 8; } G_STMT_END

            while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
                MULT (q[0], p[2], p[3], t1);
                MULT (q[1], p[1], p[3], t2);
                MULT (q[2], p[0], p[3], t3);
                q[3] = p[3];
#else
                q[0] = p[3];
                MULT (q[1], p[0], p[3], t1);
                MULT (q[2], p[1], p[3], t2);
                MULT (q[3], p[2], p[3], t3);
#endif

                p += 4;
                q += 4;
            }

#undef MULT
            gdk_pixels += gdk_rowstride;
            cairo_pixels += cairo_rowstride;
        }
    }

    cairo_surface_mark_dirty (surface);
    return surface;
}
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

/* Copied from gtk+/gdk/gdkpixbuf-drawable.c, LGPL 2+.
 *
 * Copyright (C) 1999 Michael Zucchi
 *
 * Authors: Michael Zucchi <zucchi@zedzone.mmc.com.au>
 *          Cody Russell <bratsche@dfw.net>
 *          Federico Mena-Quintero <federico@gimp.org>
 */

static void
convert_alpha (guchar *dest_data,
               int     dest_stride,
               guchar *src_data,
               int     src_stride,
               int     src_x,
               int     src_y,
               int     width,
               int     height)
{
    int x, y;

    src_data += src_stride * src_y + src_x * 4;

    for (y = 0; y < height; y++) {
        guint32 *src = (guint32 *) src_data;

        for (x = 0; x < width; x++) {
          guint alpha = src[x] >> 24;

          if (alpha == 0) {
              dest_data[x * 4 + 0] = 0;
              dest_data[x * 4 + 1] = 0;
              dest_data[x * 4 + 2] = 0;
          } else {
              dest_data[x * 4 + 0] = (((src[x] & 0xff0000) >> 16) * 255 + alpha / 2) / alpha;
              dest_data[x * 4 + 1] = (((src[x] & 0x00ff00) >>  8) * 255 + alpha / 2) / alpha;
              dest_data[x * 4 + 2] = (((src[x] & 0x0000ff) >>  0) * 255 + alpha / 2) / alpha;
          }
          dest_data[x * 4 + 3] = alpha;
      }

      src_data += src_stride;
      dest_data += dest_stride;
    }
}

static void
convert_no_alpha (guchar *dest_data,
                  int     dest_stride,
                  guchar *src_data,
                  int     src_stride,
                  int     src_x,
                  int     src_y,
                  int     width,
                  int     height)
{
    int x, y;

    src_data += src_stride * src_y + src_x * 4;

    for (y = 0; y < height; y++) {
        guint32 *src = (guint32 *) src_data;

        for (x = 0; x < width; x++) {
            dest_data[x * 3 + 0] = src[x] >> 16;
            dest_data[x * 3 + 1] = src[x] >>  8;
            dest_data[x * 3 + 2] = src[x];
        }

        src_data += src_stride;
        dest_data += dest_stride;
    }
}

GdkPixbuf *
rsvg_cairo_surface_to_pixbuf (cairo_surface_t *surface)
{
    cairo_content_t content;
    GdkPixbuf *dest;
    int width, height;

    /* General sanity checks */
    g_assert (cairo_surface_get_type (surface) == CAIRO_SURFACE_TYPE_IMAGE);

    width = cairo_image_surface_get_width (surface);
    height = cairo_image_surface_get_height (surface);
    if (width == 0 || height == 0)
        return NULL;

    content = cairo_surface_get_content (surface) | CAIRO_CONTENT_COLOR;
    dest = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
                          !!(content & CAIRO_CONTENT_ALPHA),
                          8,
                          width, height);

    if (gdk_pixbuf_get_has_alpha (dest))
      convert_alpha (gdk_pixbuf_get_pixels (dest),
                    gdk_pixbuf_get_rowstride (dest),
                    cairo_image_surface_get_data (surface),
                    cairo_image_surface_get_stride (surface),
                    0, 0,
                    width, height);
    else
      convert_no_alpha (gdk_pixbuf_get_pixels (dest),
                        gdk_pixbuf_get_rowstride (dest),
                        cairo_image_surface_get_data (surface),
                        cairo_image_surface_get_stride (surface),
                        0, 0,
                        width, height);

    return dest;
}
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

/* This is unused but still exists for ABI compat. See bug #666868. */
void rsvg_cairo_to_pixbuf (guint8 * pixels, int rowstride, int height);

void
rsvg_cairo_to_pixbuf (guint8 * pixels, int rowstride, int height)
{
    int row;
    /* un-premultiply data */
    for (row = 0; row < height; row++) {
        guint8 *row_data = (pixels + (row * rowstride));
        int i;

        for (i = 0; i < rowstride; i += 4) {
            guint8 *b = &row_data[i];
            guint32 pixel;
            guint8 alpha;

            memcpy (&pixel, b, sizeof (guint32));
            alpha = (pixel & 0xff000000) >> 24;
            if (alpha == 0) {
                b[0] = b[1] = b[2] = b[3] = 0;
            } else {
                b[0] = (((pixel & 0xff0000) >> 16) * 255 + alpha / 2) / alpha;
                b[1] = (((pixel & 0x00ff00) >> 8) * 255 + alpha / 2) / alpha;
                b[2] = (((pixel & 0x0000ff) >> 0) * 255 + alpha / 2) / alpha;
                b[3] = alpha;
            }
        }
    }
}