CairoOutputDev.cc 110 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1
2
3
4
5
6
7
8
//========================================================================
//
// CairoOutputDev.cc
//
// Copyright 2003 Glyph & Cog, LLC
// Copyright 2004 Red Hat, Inc
//
//========================================================================
9
10
11
12
13

//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
14
15
16
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
17
18
// Copyright (C) 2005-2008 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
19
// Copyright (C) 2005, 2009, 2012, 2017-2021 Albert Astals Cid <aacid@kde.org>
20
// Copyright (C) 2005 Nickolay V. Shmyrev <nshmyrev@yandex.ru>
Albert Astals Cid's avatar
Albert Astals Cid committed
21
// Copyright (C) 2006-2011, 2013, 2014, 2017, 2018 Carlos Garcia Campos <carlosgc@gnome.org>
22
// Copyright (C) 2008 Carl Worth <cworth@cworth.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
23
// Copyright (C) 2008-2018 Adrian Johnson <ajohnson@redneon.com>
24
// Copyright (C) 2008 Michael Vrable <mvrable@cs.ucsd.edu>
Albert Astals Cid's avatar
Albert Astals Cid committed
25
// Copyright (C) 2008, 2009 Chris Wilson <chris@chris-wilson.co.uk>
26
// Copyright (C) 2008, 2012 Hib Eris <hib@hiberis.nl>
27
// Copyright (C) 2009, 2010 David Benjamin <davidben@mit.edu>
28
// Copyright (C) 2011-2014 Thomas Freitag <Thomas.Freitag@alfa.de>
Albert Astals Cid's avatar
Albert Astals Cid committed
29
// Copyright (C) 2012 Patrick Pfeifer <p2000@mailinator.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
30
// Copyright (C) 2012, 2015, 2016 Jason Crain <jason@aquaticape.us>
Albert Astals Cid's avatar
0.31.0    
Albert Astals Cid committed
31
// Copyright (C) 2015 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
32
// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by the LiMux project of the city of Munich
33
// Copyright (C) 2018, 2020 Adam Reichold <adam.reichold@t-online.de>
Albert Astals Cid's avatar
Albert Astals Cid committed
34
// Copyright (C) 2019, 2020 Marek Kasik <mkasik@redhat.com>
35
// Copyright (C) 2020 Michal <sudolskym@gmail.com>
36
// Copyright (C) 2020 Oliver Sander <oliver.sander@tu-dresden.de>
Albert Astals Cid's avatar
Albert Astals Cid committed
37
// Copyright (C) 2021 Uli Schlachter <psychon@znc.in>
38
39
40
41
42
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
Kristian Høgsberg's avatar
Kristian Høgsberg committed
43
44
45

#include <config.h>

46
#include <cstdint>
47
48
49
#include <cstring>
#include <cmath>
#include <cassert>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
50
51
52
53
54
55
#include <cairo.h>

#include "goo/gfile.h"
#include "GlobalParams.h"
#include "Error.h"
#include "Object.h"
56
#include "Gfx.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
57
58
#include "GfxState.h"
#include "GfxFont.h"
59
#include "Page.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
60
61
#include "Link.h"
#include "FontEncodingTables.h"
62
#include "PDFDocEncoding.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
63
64
65
66
#include <fofi/FoFiTrueType.h>
#include <splash/SplashBitmap.h>
#include "CairoOutputDev.h"
#include "CairoFontEngine.h"
67
#include "CairoRescaleBox.h"
68
#include "UnicodeMap.h"
69
#include "JBIG2Stream.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
70
71
//------------------------------------------------------------------------

72
// #define LOG_CAIRO
Kristian Høgsberg's avatar
Kristian Høgsberg committed
73

74
75
76
77
78
// To limit memory usage and improve performance when printing, limit
// cairo images to this size. 8192 is sufficient for an A2 sized
// 300ppi image.
#define MAX_PRINT_IMAGE_SIZE 8192

Kristian Høgsberg's avatar
Kristian Høgsberg committed
79
#ifdef LOG_CAIRO
Albert Astals Cid's avatar
Albert Astals Cid committed
80
#    define LOG(x) (x)
Kristian Høgsberg's avatar
Kristian Høgsberg committed
81
#else
Albert Astals Cid's avatar
Albert Astals Cid committed
82
#    define LOG(x)
Kristian Høgsberg's avatar
Kristian Høgsberg committed
83
84
#endif

Albert Astals Cid's avatar
Albert Astals Cid committed
85
86
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
Adrian Johnson's avatar
Adrian Johnson committed
87

Albert Astals Cid's avatar
Albert Astals Cid committed
88
89
90
91
//------------------------------------------------------------------------
// CairoImage
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
92
93
94
95
96
97
98
CairoImage::CairoImage(double x1A, double y1A, double x2A, double y2A)
{
    image = nullptr;
    x1 = x1A;
    y1 = y1A;
    x2 = x2A;
    y2 = y2A;
Albert Astals Cid's avatar
Albert Astals Cid committed
99
100
}

Albert Astals Cid's avatar
Albert Astals Cid committed
101
102
103
104
CairoImage::~CairoImage()
{
    if (image)
        cairo_surface_destroy(image);
Albert Astals Cid's avatar
Albert Astals Cid committed
105
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
106

Albert Astals Cid's avatar
Albert Astals Cid committed
107
108
109
110
111
void CairoImage::setImage(cairo_surface_t *i)
{
    if (image)
        cairo_surface_destroy(image);
    image = cairo_surface_reference(i);
112
113
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
114
115
116
117
//------------------------------------------------------------------------
// CairoOutputDev
//------------------------------------------------------------------------

118
119
120
121
122
123
124
// We cannot tie the lifetime of an FT_Library object to that of
// CairoOutputDev, since any FT_Faces created with it may end up with a
// reference by Cairo which can be held long after the CairoOutputDev is
// deleted.  The simplest way to avoid problems is to never tear down the
// FT_Library instance; to avoid leaks, just use a single global instance
// initialized the first time it is needed.
FT_Library CairoOutputDev::ft_lib;
125
std::once_flag CairoOutputDev::ft_lib_once_flag;
126

Albert Astals Cid's avatar
Albert Astals Cid committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
CairoOutputDev::CairoOutputDev()
{
    doc = nullptr;

    std::call_once(ft_lib_once_flag, FT_Init_FreeType, &ft_lib);

    fontEngine = nullptr;
    fontEngine_owner = false;
    glyphs = nullptr;
    fill_pattern = nullptr;
    fill_color.r = fill_color.g = fill_color.b = 0;
    stroke_pattern = nullptr;
    stroke_color.r = stroke_color.g = stroke_color.b = 0;
    stroke_opacity = 1.0;
    fill_opacity = 1.0;
    textClipPath = nullptr;
    strokePathClip = nullptr;
    cairo = nullptr;
    currentFont = nullptr;
146
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0)
Albert Astals Cid's avatar
Albert Astals Cid committed
147
    prescaleImages = false;
148
#else
Albert Astals Cid's avatar
Albert Astals Cid committed
149
    prescaleImages = true;
150
#endif
Albert Astals Cid's avatar
Albert Astals Cid committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    printing = true;
    use_show_text_glyphs = false;
    inUncoloredPattern = false;
    inType3Char = false;
    t3_glyph_has_bbox = false;
    text_matrix_valid = true;
    antialias = CAIRO_ANTIALIAS_DEFAULT;

    groupColorSpaceStack = nullptr;
    maskStack = nullptr;
    group = nullptr;
    mask = nullptr;
    shape = nullptr;
    cairo_shape = nullptr;
    knockoutCount = 0;

    textPage = nullptr;
    actualText = nullptr;

    // the SA parameter supposedly defaults to false, but Acrobat
    // apparently hardwires it to true
    stroke_adjust = true;
    align_stroke_coords = false;
    adjusted_stroke_width = false;
    xref = nullptr;
}

CairoOutputDev::~CairoOutputDev()
{
    if (fontEngine_owner && fontEngine) {
        delete fontEngine;
    }
183
184
185
186
    if (textClipPath) {
        cairo_path_destroy(textClipPath);
        textClipPath = nullptr;
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

    if (cairo)
        cairo_destroy(cairo);
    cairo_pattern_destroy(stroke_pattern);
    cairo_pattern_destroy(fill_pattern);
    if (group)
        cairo_pattern_destroy(group);
    if (mask)
        cairo_pattern_destroy(mask);
    if (shape)
        cairo_pattern_destroy(shape);
    if (textPage)
        textPage->decRefCnt();
    if (actualText)
        delete actualText;
202
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
203

204
void CairoOutputDev::setCairo(cairo_t *c)
205
{
Albert Astals Cid's avatar
Albert Astals Cid committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    if (cairo != nullptr) {
        cairo_status_t status = cairo_status(cairo);
        if (status) {
            error(errInternal, -1, "cairo context error: {0:s}\n", cairo_status_to_string(status));
        }
        cairo_destroy(cairo);
        assert(!cairo_shape);
    }
    if (c != nullptr) {
        cairo = cairo_reference(c);
        /* save the initial matrix so that we can use it for type3 fonts. */
        // XXX: is this sufficient? could we miss changes to the matrix somehow?
        cairo_get_matrix(cairo, &orig_matrix);
        setContextAntialias(cairo, antialias);
    } else {
        cairo = nullptr;
        cairo_shape = nullptr;
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
224
225
}

226
227
void CairoOutputDev::setTextPage(TextPage *text)
{
Albert Astals Cid's avatar
Albert Astals Cid committed
228
229
230
231
232
233
234
235
236
237
238
239
    if (textPage)
        textPage->decRefCnt();
    if (actualText)
        delete actualText;
    if (text) {
        textPage = text;
        textPage->incRefCnt();
        actualText = new ActualText(text);
    } else {
        textPage = nullptr;
        actualText = nullptr;
    }
240
241
}

242
void CairoOutputDev::setAntialias(cairo_antialias_t a)
243
{
Albert Astals Cid's avatar
Albert Astals Cid committed
244
245
246
247
248
    antialias = a;
    if (cairo)
        setContextAntialias(cairo, antialias);
    if (cairo_shape)
        setContextAntialias(cairo_shape, antialias);
249
250
}

251
void CairoOutputDev::setContextAntialias(cairo_t *cr, cairo_antialias_t antialias)
252
{
Albert Astals Cid's avatar
Albert Astals Cid committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    cairo_font_options_t *font_options;
    cairo_set_antialias(cr, antialias);
    font_options = cairo_font_options_create();
    cairo_get_font_options(cr, font_options);
    cairo_font_options_set_antialias(font_options, antialias);
    cairo_set_font_options(cr, font_options);
    cairo_font_options_destroy(font_options);
}

void CairoOutputDev::startDoc(PDFDoc *docA, CairoFontEngine *parentFontEngine)
{
    doc = docA;
    if (parentFontEngine) {
        fontEngine = parentFontEngine;
    } else {
        if (fontEngine) {
            delete fontEngine;
        }
        fontEngine = new CairoFontEngine(ft_lib);
        fontEngine_owner = true;
    }
    xref = doc->getXRef();
}

void CairoOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefA)
{
    /* set up some per page defaults */
280
    cairo_pattern_destroy(fill_pattern);
Albert Astals Cid's avatar
Albert Astals Cid committed
281
    cairo_pattern_destroy(stroke_pattern);
282

Albert Astals Cid's avatar
Albert Astals Cid committed
283
284
285
286
287
288
289
290
291
292
    fill_pattern = cairo_pattern_create_rgb(0., 0., 0.);
    fill_color.r = fill_color.g = fill_color.b = 0;
    stroke_pattern = cairo_pattern_reference(fill_pattern);
    stroke_color.r = stroke_color.g = stroke_color.b = 0;

    if (textPage)
        textPage->startPage(state);
    if (xrefA != nullptr) {
        xref = xrefA;
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
293
294
}

Albert Astals Cid's avatar
Albert Astals Cid committed
295
296
297
298
299
300
301
void CairoOutputDev::endPage()
{
    if (textPage) {
        textPage->endPage();
        textPage->coalesce(true, 0, false);
    }
}
302

Albert Astals Cid's avatar
Albert Astals Cid committed
303
304
305
306
307
308
void CairoOutputDev::saveState(GfxState *state)
{
    LOG(printf("save\n"));
    cairo_save(cairo);
    if (cairo_shape)
        cairo_save(cairo_shape);
309

Albert Astals Cid's avatar
Albert Astals Cid committed
310
311
312
313
314
    MaskStack *ms = new MaskStack;
    ms->mask = cairo_pattern_reference(mask);
    ms->mask_matrix = mask_matrix;
    ms->next = maskStack;
    maskStack = ms;
315

Albert Astals Cid's avatar
Albert Astals Cid committed
316
317
    if (strokePathClip)
        strokePathClip->ref_count++;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
318
319
}

Albert Astals Cid's avatar
Albert Astals Cid committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
void CairoOutputDev::restoreState(GfxState *state)
{
    LOG(printf("restore\n"));
    cairo_restore(cairo);
    if (cairo_shape)
        cairo_restore(cairo_shape);

    text_matrix_valid = true;

    /* These aren't restored by cairo_restore() since we keep them in
     * the output device. */
    updateFillColor(state);
    updateStrokeColor(state);
    updateFillOpacity(state);
    updateStrokeOpacity(state);
    updateBlendMode(state);

    MaskStack *ms = maskStack;
    if (ms) {
        if (mask)
            cairo_pattern_destroy(mask);
        mask = ms->mask;
        mask_matrix = ms->mask_matrix;
        maskStack = ms->next;
        delete ms;
    }
346

Albert Astals Cid's avatar
Albert Astals Cid committed
347
348
349
350
351
352
353
354
    if (strokePathClip && --strokePathClip->ref_count == 0) {
        delete strokePathClip->path;
        if (strokePathClip->dashes)
            gfree(strokePathClip->dashes);
        gfree(strokePathClip);
        strokePathClip = nullptr;
    }
}
355

Albert Astals Cid's avatar
Albert Astals Cid committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
void CairoOutputDev::updateAll(GfxState *state)
{
    updateLineDash(state);
    updateLineJoin(state);
    updateLineCap(state);
    updateLineWidth(state);
    updateFlatness(state);
    updateMiterLimit(state);
    updateFillColor(state);
    updateStrokeColor(state);
    updateFillOpacity(state);
    updateStrokeOpacity(state);
    updateBlendMode(state);
    needFontUpdate = true;
    if (textPage)
        textPage->updateFont(state);
}

void CairoOutputDev::setDefaultCTM(const double *ctm)
{
    cairo_matrix_t matrix;
    matrix.xx = ctm[0];
    matrix.yx = ctm[1];
    matrix.xy = ctm[2];
    matrix.yy = ctm[3];
    matrix.x0 = ctm[4];
    matrix.y0 = ctm[5];

    cairo_transform(cairo, &matrix);
    if (cairo_shape)
        cairo_transform(cairo_shape, &matrix);
387

Albert Astals Cid's avatar
Albert Astals Cid committed
388
    OutputDev::setDefaultCTM(ctm);
389
390
}

Albert Astals Cid's avatar
Albert Astals Cid committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
void CairoOutputDev::updateCTM(GfxState *state, double m11, double m12, double m21, double m22, double m31, double m32)
{
    cairo_matrix_t matrix, invert_matrix;
    matrix.xx = m11;
    matrix.yx = m12;
    matrix.xy = m21;
    matrix.yy = m22;
    matrix.x0 = m31;
    matrix.y0 = m32;

    /* Make sure the matrix is invertible before setting it.
     * cairo will blow up if we give it a matrix that's not
     * invertible, so we need to check before passing it
     * to cairo_transform. Ignoring it is likely to give better
     * results than not rendering anything at all. See #14398
     *
     * Ideally, we could do the cairo_transform
     * and then check if anything went wrong and fix it then
     * instead of having to invert the matrix. */
    invert_matrix = matrix;
    if (cairo_matrix_invert(&invert_matrix)) {
        error(errSyntaxWarning, -1, "matrix not invertible\n");
        return;
    }

    cairo_transform(cairo, &matrix);
    if (cairo_shape)
        cairo_transform(cairo_shape, &matrix);
    updateLineDash(state);
    updateLineJoin(state);
    updateLineCap(state);
    updateLineWidth(state);
}
424

Albert Astals Cid's avatar
Albert Astals Cid committed
425
426
427
428
429
void CairoOutputDev::updateLineDash(GfxState *state)
{
    double *dashPattern;
    int dashLength;
    double dashStart;
430

Albert Astals Cid's avatar
Albert Astals Cid committed
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
    state->getLineDash(&dashPattern, &dashLength, &dashStart);
    cairo_set_dash(cairo, dashPattern, dashLength, dashStart);
    if (cairo_shape)
        cairo_set_dash(cairo_shape, dashPattern, dashLength, dashStart);
}

void CairoOutputDev::updateFlatness(GfxState *state)
{
    // cairo_set_tolerance (cairo, state->getFlatness());
}

void CairoOutputDev::updateLineJoin(GfxState *state)
{
    switch (state->getLineJoin()) {
    case 0:
        cairo_set_line_join(cairo, CAIRO_LINE_JOIN_MITER);
        break;
    case 1:
        cairo_set_line_join(cairo, CAIRO_LINE_JOIN_ROUND);
        break;
    case 2:
        cairo_set_line_join(cairo, CAIRO_LINE_JOIN_BEVEL);
        break;
    }
    if (cairo_shape)
        cairo_set_line_join(cairo_shape, cairo_get_line_join(cairo));
}

void CairoOutputDev::updateLineCap(GfxState *state)
{
    switch (state->getLineCap()) {
    case 0:
        cairo_set_line_cap(cairo, CAIRO_LINE_CAP_BUTT);
        break;
    case 1:
        cairo_set_line_cap(cairo, CAIRO_LINE_CAP_ROUND);
        break;
    case 2:
        cairo_set_line_cap(cairo, CAIRO_LINE_CAP_SQUARE);
        break;
    }
    if (cairo_shape)
        cairo_set_line_cap(cairo_shape, cairo_get_line_cap(cairo));
}

void CairoOutputDev::updateMiterLimit(GfxState *state)
{
    cairo_set_miter_limit(cairo, state->getMiterLimit());
    if (cairo_shape)
        cairo_set_miter_limit(cairo_shape, state->getMiterLimit());
}

void CairoOutputDev::updateLineWidth(GfxState *state)
{
    LOG(printf("line width: %f\n", state->getLineWidth()));
    adjusted_stroke_width = false;
    double width = state->getLineWidth();
    if (stroke_adjust && !printing) {
        double x, y;
        x = y = width;

        /* find out line width in device units */
        cairo_user_to_device_distance(cairo, &x, &y);
        if (fabs(x) <= 1.0 && fabs(y) <= 1.0) {
            /* adjust width to at least one device pixel */
            x = y = 1.0;
            cairo_device_to_user_distance(cairo, &x, &y);
            width = MIN(fabs(x), fabs(y));
            adjusted_stroke_width = true;
        }
    } else if (width == 0.0) {
        /* Cairo does not support 0 line width == 1 device pixel. Find out
         * how big pixels (device unit) are in the x and y
         * directions. Choose the smaller of the two as our line width.
         */
        double x = 1.0, y = 1.0;
        if (printing) {
            // assume printer pixel size is 1/600 inch
            x = 72.0 / 600;
            y = 72.0 / 600;
        }
        cairo_device_to_user_distance(cairo, &x, &y);
        width = MIN(fabs(x), fabs(y));
    }
    cairo_set_line_width(cairo, width);
    if (cairo_shape)
        cairo_set_line_width(cairo_shape, cairo_get_line_width(cairo));
}

void CairoOutputDev::updateFillColor(GfxState *state)
{
    GfxRGB color = fill_color;

    if (inUncoloredPattern)
        return;

    state->getFillRGB(&fill_color);
    if (cairo_pattern_get_type(fill_pattern) != CAIRO_PATTERN_TYPE_SOLID || color.r != fill_color.r || color.g != fill_color.g || color.b != fill_color.b) {
        cairo_pattern_destroy(fill_pattern);
        fill_pattern = cairo_pattern_create_rgba(colToDbl(fill_color.r), colToDbl(fill_color.g), colToDbl(fill_color.b), fill_opacity);

        LOG(printf("fill color: %d %d %d\n", fill_color.r, fill_color.g, fill_color.b));
    }
}

void CairoOutputDev::updateStrokeColor(GfxState *state)
{
    GfxRGB color = stroke_color;

    if (inUncoloredPattern)
        return;

    state->getStrokeRGB(&stroke_color);
    if (cairo_pattern_get_type(fill_pattern) != CAIRO_PATTERN_TYPE_SOLID || color.r != stroke_color.r || color.g != stroke_color.g || color.b != stroke_color.b) {
        cairo_pattern_destroy(stroke_pattern);
        stroke_pattern = cairo_pattern_create_rgba(colToDbl(stroke_color.r), colToDbl(stroke_color.g), colToDbl(stroke_color.b), stroke_opacity);

        LOG(printf("stroke color: %d %d %d\n", stroke_color.r, stroke_color.g, stroke_color.b));
    }
}

void CairoOutputDev::updateFillOpacity(GfxState *state)
{
    double opacity = fill_opacity;

    if (inUncoloredPattern)
        return;

    fill_opacity = state->getFillOpacity();
    if (opacity != fill_opacity) {
        cairo_pattern_destroy(fill_pattern);
        fill_pattern = cairo_pattern_create_rgba(colToDbl(fill_color.r), colToDbl(fill_color.g), colToDbl(fill_color.b), fill_opacity);

        LOG(printf("fill opacity: %f\n", fill_opacity));
    }
}

void CairoOutputDev::updateStrokeOpacity(GfxState *state)
{
    double opacity = stroke_opacity;

    if (inUncoloredPattern)
        return;

    stroke_opacity = state->getStrokeOpacity();
    if (opacity != stroke_opacity) {
        cairo_pattern_destroy(stroke_pattern);
        stroke_pattern = cairo_pattern_create_rgba(colToDbl(stroke_color.r), colToDbl(stroke_color.g), colToDbl(stroke_color.b), stroke_opacity);

        LOG(printf("stroke opacity: %f\n", stroke_opacity));
    }
}

void CairoOutputDev::updateFillColorStop(GfxState *state, double offset)
{
    if (inUncoloredPattern)
        return;

    state->getFillRGB(&fill_color);

    // If stroke pattern is set then the current fill is clipped
    // to a stroke path.  In that case, the stroke opacity has to be used
    // rather than the fill opacity.
    // See https://gitlab.freedesktop.org/poppler/poppler/issues/178
    auto opacity = (state->getStrokePattern()) ? state->getStrokeOpacity() : state->getFillOpacity();

    cairo_pattern_add_color_stop_rgba(fill_pattern, offset, colToDbl(fill_color.r), colToDbl(fill_color.g), colToDbl(fill_color.b), opacity);
    LOG(printf("fill color stop: %f (%d, %d, %d, %d)\n", offset, fill_color.r, fill_color.g, fill_color.b, dblToCol(opacity)));
}

void CairoOutputDev::updateBlendMode(GfxState *state)
{
    switch (state->getBlendMode()) {
    default:
    case gfxBlendNormal:
        cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);
        break;
    case gfxBlendMultiply:
        cairo_set_operator(cairo, CAIRO_OPERATOR_MULTIPLY);
        break;
    case gfxBlendScreen:
        cairo_set_operator(cairo, CAIRO_OPERATOR_SCREEN);
        break;
    case gfxBlendOverlay:
        cairo_set_operator(cairo, CAIRO_OPERATOR_OVERLAY);
        break;
    case gfxBlendDarken:
        cairo_set_operator(cairo, CAIRO_OPERATOR_DARKEN);
        break;
    case gfxBlendLighten:
        cairo_set_operator(cairo, CAIRO_OPERATOR_LIGHTEN);
        break;
    case gfxBlendColorDodge:
        cairo_set_operator(cairo, CAIRO_OPERATOR_COLOR_DODGE);
        break;
    case gfxBlendColorBurn:
        cairo_set_operator(cairo, CAIRO_OPERATOR_COLOR_BURN);
        break;
    case gfxBlendHardLight:
        cairo_set_operator(cairo, CAIRO_OPERATOR_HARD_LIGHT);
        break;
    case gfxBlendSoftLight:
        cairo_set_operator(cairo, CAIRO_OPERATOR_SOFT_LIGHT);
        break;
    case gfxBlendDifference:
        cairo_set_operator(cairo, CAIRO_OPERATOR_DIFFERENCE);
        break;
    case gfxBlendExclusion:
        cairo_set_operator(cairo, CAIRO_OPERATOR_EXCLUSION);
        break;
    case gfxBlendHue:
        cairo_set_operator(cairo, CAIRO_OPERATOR_HSL_HUE);
        break;
    case gfxBlendSaturation:
        cairo_set_operator(cairo, CAIRO_OPERATOR_HSL_SATURATION);
        break;
    case gfxBlendColor:
        cairo_set_operator(cairo, CAIRO_OPERATOR_HSL_COLOR);
        break;
    case gfxBlendLuminosity:
        cairo_set_operator(cairo, CAIRO_OPERATOR_HSL_LUMINOSITY);
        break;
    }
    LOG(printf("blend mode: %d\n", (int)state->getBlendMode()));
}

void CairoOutputDev::updateFont(GfxState *state)
{
    cairo_font_face_t *font_face;
    cairo_matrix_t matrix, invert_matrix;

    LOG(printf("updateFont() font=%s\n", state->getFont()->getName()->c_str()));

    needFontUpdate = false;

    // FIXME: use cairo font engine?
    if (textPage)
        textPage->updateFont(state);

    currentFont = fontEngine->getFont(state->getFont(), doc, printing, xref);

    if (!currentFont)
        return;

    font_face = currentFont->getFontFace();
    cairo_set_font_face(cairo, font_face);

    use_show_text_glyphs = state->getFont()->hasToUnicodeCMap() && cairo_surface_has_show_text_glyphs(cairo_get_target(cairo));

    double fontSize = state->getFontSize();
    const double *m = state->getTextMat();
    /* NOTE: adjusting by a constant is hack. The correct solution
     * is probably to use user-fonts and compute the scale on a per
     * glyph basis instead of for the entire font */
    double w = currentFont->getSubstitutionCorrection(state->getFont());
    matrix.xx = m[0] * fontSize * state->getHorizScaling() * w;
    matrix.yx = m[1] * fontSize * state->getHorizScaling() * w;
    matrix.xy = -m[2] * fontSize;
    matrix.yy = -m[3] * fontSize;
    matrix.x0 = 0;
    matrix.y0 = 0;

    LOG(printf("font matrix: %f %f %f %f\n", matrix.xx, matrix.yx, matrix.xy, matrix.yy));

    /* Make sure the font matrix is invertible before setting it.  cairo
     * will blow up if we give it a matrix that's not invertible, so we
     * need to check before passing it to cairo_set_font_matrix. Ignoring it
     * is likely to give better results than not rendering anything at
     * all. See #18254.
     */
    invert_matrix = matrix;
    if (cairo_matrix_invert(&invert_matrix)) {
        error(errSyntaxWarning, -1, "font matrix not invertible");
        text_matrix_valid = false;
        return;
    }

    cairo_set_font_matrix(cairo, &matrix);
    text_matrix_valid = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
710
711
}

712
713
714
715
716
717
/* Tolerance in pixels for checking if strokes are horizontal or vertical
 * lines in device space */
#define STROKE_COORD_TOLERANCE 0.5

/* Align stroke coordinate i if the point is the start or end of a
 * horizontal or vertical line */
718
void CairoOutputDev::alignStrokeCoords(const GfxSubpath *subpath, int i, double *x, double *y)
719
{
Albert Astals Cid's avatar
Albert Astals Cid committed
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
    double x1, y1, x2, y2;
    bool align = false;

    x1 = subpath->getX(i);
    y1 = subpath->getY(i);
    cairo_user_to_device(cairo, &x1, &y1);

    // Does the current coord and prev coord form a horiz or vert line?
    if (i > 0 && !subpath->getCurve(i - 1)) {
        x2 = subpath->getX(i - 1);
        y2 = subpath->getY(i - 1);
        cairo_user_to_device(cairo, &x2, &y2);
        if (fabs(x2 - x1) < STROKE_COORD_TOLERANCE || fabs(y2 - y1) < STROKE_COORD_TOLERANCE)
            align = true;
    }

    // Does the current coord and next coord form a horiz or vert line?
    if (i < subpath->getNumPoints() - 1 && !subpath->getCurve(i + 1)) {
        x2 = subpath->getX(i + 1);
        y2 = subpath->getY(i + 1);
        cairo_user_to_device(cairo, &x2, &y2);
        if (fabs(x2 - x1) < STROKE_COORD_TOLERANCE || fabs(y2 - y1) < STROKE_COORD_TOLERANCE)
            align = true;
    }

    *x = subpath->getX(i);
    *y = subpath->getY(i);
    if (align) {
        /* see http://www.cairographics.org/FAQ/#sharp_lines */
        cairo_user_to_device(cairo, x, y);
        *x = floor(*x) + 0.5;
        *y = floor(*y) + 0.5;
        cairo_device_to_user(cairo, x, y);
    }
754
755
}

756
757
#undef STROKE_COORD_TOLERANCE

Albert Astals Cid's avatar
Albert Astals Cid committed
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
void CairoOutputDev::doPath(cairo_t *c, GfxState *state, const GfxPath *path)
{
    int i, j;
    double x, y;
    cairo_new_path(c);
    for (i = 0; i < path->getNumSubpaths(); ++i) {
        const GfxSubpath *subpath = path->getSubpath(i);
        if (subpath->getNumPoints() > 0) {
            if (align_stroke_coords) {
                alignStrokeCoords(subpath, 0, &x, &y);
            } else {
                x = subpath->getX(0);
                y = subpath->getY(0);
            }
            cairo_move_to(c, x, y);
            j = 1;
            while (j < subpath->getNumPoints()) {
                if (subpath->getCurve(j)) {
                    if (align_stroke_coords) {
                        alignStrokeCoords(subpath, j + 2, &x, &y);
                    } else {
                        x = subpath->getX(j + 2);
                        y = subpath->getY(j + 2);
                    }
                    cairo_curve_to(c, subpath->getX(j), subpath->getY(j), subpath->getX(j + 1), subpath->getY(j + 1), x, y);

                    j += 3;
                } else {
                    if (align_stroke_coords) {
                        alignStrokeCoords(subpath, j, &x, &y);
                    } else {
                        x = subpath->getX(j);
                        y = subpath->getY(j);
                    }
                    cairo_line_to(c, x, y);
                    ++j;
                }
            }
            if (subpath->isClosed()) {
                LOG(printf("close\n"));
                cairo_close_path(c);
            }
        }
    }
}

void CairoOutputDev::stroke(GfxState *state)
{
    if (inType3Char) {
        GfxGray gray;
        state->getFillGray(&gray);
        if (colToDbl(gray) > 0.5)
            return;
    }

    if (adjusted_stroke_width)
        align_stroke_coords = true;
    doPath(cairo, state, state->getPath());
    align_stroke_coords = false;
    cairo_set_source(cairo, stroke_pattern);
    LOG(printf("stroke\n"));
819
    if (strokePathClip) {
Albert Astals Cid's avatar
Albert Astals Cid committed
820
821
822
823
824
825
826
827
828
829
830
831
        cairo_push_group(cairo);
        cairo_stroke(cairo);
        cairo_pop_group_to_source(cairo);
        fillToStrokePathClip(state);
    } else {
        cairo_stroke(cairo);
    }
    if (cairo_shape) {
        doPath(cairo_shape, state, state->getPath());
        cairo_stroke(cairo_shape);
    }
}
832

Albert Astals Cid's avatar
Albert Astals Cid committed
833
834
835
836
837
838
839
840
void CairoOutputDev::fill(GfxState *state)
{
    if (inType3Char) {
        GfxGray gray;
        state->getFillGray(&gray);
        if (colToDbl(gray) > 0.5)
            return;
    }
841

Albert Astals Cid's avatar
Albert Astals Cid committed
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
    doPath(cairo, state, state->getPath());
    cairo_set_fill_rule(cairo, CAIRO_FILL_RULE_WINDING);
    cairo_set_source(cairo, fill_pattern);
    LOG(printf("fill\n"));
    // XXX: how do we get the path
    if (mask) {
        cairo_save(cairo);
        cairo_clip(cairo);
        if (strokePathClip) {
            cairo_push_group(cairo);
            fillToStrokePathClip(state);
            cairo_pop_group_to_source(cairo);
        }
        cairo_set_matrix(cairo, &mask_matrix);
        cairo_mask(cairo, mask);
        cairo_restore(cairo);
    } else if (strokePathClip) {
        fillToStrokePathClip(state);
    } else {
        cairo_fill(cairo);
    }
    if (cairo_shape) {
        cairo_set_fill_rule(cairo_shape, CAIRO_FILL_RULE_WINDING);
        doPath(cairo_shape, state, state->getPath());
        cairo_fill(cairo_shape);
    }
}
869

Albert Astals Cid's avatar
Albert Astals Cid committed
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
void CairoOutputDev::eoFill(GfxState *state)
{
    doPath(cairo, state, state->getPath());
    cairo_set_fill_rule(cairo, CAIRO_FILL_RULE_EVEN_ODD);
    cairo_set_source(cairo, fill_pattern);
    LOG(printf("fill-eo\n"));

    if (mask) {
        cairo_save(cairo);
        cairo_clip(cairo);
        cairo_set_matrix(cairo, &mask_matrix);
        cairo_mask(cairo, mask);
        cairo_restore(cairo);
    } else {
        cairo_fill(cairo);
    }
    if (cairo_shape) {
        cairo_set_fill_rule(cairo_shape, CAIRO_FILL_RULE_EVEN_ODD);
        doPath(cairo_shape, state, state->getPath());
        cairo_fill(cairo_shape);
    }
}
892

893
bool CairoOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *cat, GfxTilingPattern *tPat, const double *mat, int x0, int y0, int x1, int y1, double xStep, double yStep)
Albert Astals Cid's avatar
Albert Astals Cid committed
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
{
    PDFRectangle box;
    Gfx *gfx;
    cairo_pattern_t *pattern;
    cairo_surface_t *surface;
    cairo_matrix_t matrix;
    cairo_matrix_t pattern_matrix;
    cairo_t *old_cairo;
    double xMin, yMin, xMax, yMax;
    double width, height;
    double scaleX, scaleY;
    int surface_width, surface_height;
    StrokePathClip *strokePathTmp;
    bool adjusted_stroke_width_tmp;
    cairo_pattern_t *maskTmp;
909
910
911
912
913
    const double *bbox = tPat->getBBox();
    const double *pmat = tPat->getMatrix();
    const int paintType = tPat->getPaintType();
    Dict *resDict = tPat->getResDict();
    Object *str = tPat->getContentStream();
Albert Astals Cid's avatar
Albert Astals Cid committed
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
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
957
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

    width = bbox[2] - bbox[0];
    height = bbox[3] - bbox[1];

    if (xStep != width || yStep != height)
        return false;
    /* TODO: implement the other cases here too */

    // Find the width and height of the transformed pattern
    cairo_get_matrix(cairo, &matrix);
    cairo_matrix_init(&pattern_matrix, mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
    cairo_matrix_multiply(&matrix, &matrix, &pattern_matrix);

    double widthX = width, widthY = 0;
    cairo_matrix_transform_distance(&matrix, &widthX, &widthY);
    surface_width = ceil(sqrt(widthX * widthX + widthY * widthY));

    double heightX = 0, heightY = height;
    cairo_matrix_transform_distance(&matrix, &heightX, &heightY);
    surface_height = ceil(sqrt(heightX * heightX + heightY * heightY));
    scaleX = surface_width / width;
    scaleY = surface_height / height;

    surface = cairo_surface_create_similar(cairo_get_target(cairo), CAIRO_CONTENT_COLOR_ALPHA, surface_width, surface_height);
    if (cairo_surface_status(surface))
        return false;

    old_cairo = cairo;
    cairo = cairo_create(surface);
    cairo_surface_destroy(surface);
    setContextAntialias(cairo, antialias);

    box.x1 = bbox[0];
    box.y1 = bbox[1];
    box.x2 = bbox[2];
    box.y2 = bbox[3];
    cairo_scale(cairo, scaleX, scaleY);
    cairo_translate(cairo, -box.x1, -box.y1);

    strokePathTmp = strokePathClip;
    strokePathClip = nullptr;
    adjusted_stroke_width_tmp = adjusted_stroke_width;
    maskTmp = mask;
    mask = nullptr;
    gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA);
    if (paintType == 2)
        inUncoloredPattern = true;
    gfx->display(str);
    if (paintType == 2)
        inUncoloredPattern = false;
    delete gfx;
    strokePathClip = strokePathTmp;
    adjusted_stroke_width = adjusted_stroke_width_tmp;
    mask = maskTmp;

    pattern = cairo_pattern_create_for_surface(cairo_get_target(cairo));
    cairo_destroy(cairo);
    cairo = old_cairo;
    if (cairo_pattern_status(pattern))
        return false;

    // Cairo can fail if the pattern translation is too large. Fix by making the
    // translation smaller.
    const double det = pmat[0] * pmat[3] - pmat[1] * pmat[2];

    // Find the number of repetitions of pattern we need to shift by. Transform
    // the translation component of pmat (pmat[4] and pmat[5]) into the pattern's
    // coordinate system by multiplying by inverse of pmat, then divide by
    // pattern size (xStep and yStep).
    const double xoffset = round((pmat[3] * pmat[4] - pmat[2] * pmat[5]) / (xStep * det));
    const double yoffset = -round((pmat[1] * pmat[4] - pmat[0] * pmat[5]) / (yStep * det));

    if (!std::isfinite(xoffset) || !std::isfinite(yoffset)) {
        error(errSyntaxWarning, -1, "CairoOutputDev: Singular matrix in tilingPatternFill");
        return false;
    }
990

Albert Astals Cid's avatar
Albert Astals Cid committed
991
992
993
    // Shift pattern_matrix by multiples of the pattern size.
    pattern_matrix.x0 -= xoffset * pattern_matrix.xx * xStep + yoffset * pattern_matrix.xy * yStep;
    pattern_matrix.y0 -= xoffset * pattern_matrix.yx * xStep + yoffset * pattern_matrix.yy * yStep;
994

Albert Astals Cid's avatar
Albert Astals Cid committed
995
996
    state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
    cairo_rectangle(cairo, xMin, yMin, xMax - xMin, yMax - yMin);
997

Albert Astals Cid's avatar
Albert Astals Cid committed
998
999
1000
    cairo_matrix_init_scale(&matrix, scaleX, scaleY);
    cairo_matrix_translate(&matrix, -box.x1, -box.y1);
    cairo_pattern_set_matrix(pattern, &matrix);
For faster browsing, not all history is shown. View entire blame