forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDrawTargetCairo.cpp
2014 lines (1685 loc) · 63.8 KB
/
DrawTargetCairo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
346
347
348
349
350
351
352
353
354
355
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
387
388
389
390
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
424
425
426
427
428
429
430
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
710
711
712
713
714
715
716
717
718
719
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
754
755
756
757
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
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
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
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "DrawTargetCairo.h"
#include "SourceSurfaceCairo.h"
#include "PathCairo.h"
#include "HelpersCairo.h"
#include "BorrowedContext.h"
#include "FilterNodeSoftware.h"
#include "mozilla/Scoped.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Vector.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_print.h"
#include "nsPrintfCString.h"
#include "cairo.h"
#include "cairo-tee.h"
#include <string.h>
#include "Blur.h"
#include "Logging.h"
#include "Tools.h"
#ifdef CAIRO_HAS_QUARTZ_SURFACE
# include "cairo-quartz.h"
# ifdef MOZ_WIDGET_COCOA
# include <ApplicationServices/ApplicationServices.h>
# endif
#endif
#ifdef CAIRO_HAS_XLIB_SURFACE
# include "cairo-xlib.h"
#endif
#ifdef CAIRO_HAS_WIN32_SURFACE
# include "cairo-win32.h"
#endif
#define PIXMAN_DONT_DEFINE_STDINT
#include "pixman.h"
#include <algorithm>
// 2^23
#define CAIRO_COORD_MAX (Float(0x7fffff))
namespace mozilla {
MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedCairoSurface, cairo_surface_t,
cairo_surface_destroy);
namespace gfx {
cairo_surface_t* DrawTargetCairo::mDummySurface;
namespace {
// An RAII class to prepare to draw a context and optional path. Saves and
// restores the context on construction/destruction.
class AutoPrepareForDrawing {
public:
AutoPrepareForDrawing(DrawTargetCairo* dt, cairo_t* ctx) : mCtx(ctx) {
dt->PrepareForDrawing(ctx);
cairo_save(mCtx);
MOZ_ASSERT(cairo_status(mCtx) ||
dt->GetTransform().FuzzyEquals(GetTransform()));
}
AutoPrepareForDrawing(DrawTargetCairo* dt, cairo_t* ctx, const Path* path)
: mCtx(ctx) {
dt->PrepareForDrawing(ctx, path);
cairo_save(mCtx);
MOZ_ASSERT(cairo_status(mCtx) ||
dt->GetTransform().FuzzyEquals(GetTransform()));
}
~AutoPrepareForDrawing() {
cairo_restore(mCtx);
cairo_status_t status = cairo_status(mCtx);
if (status) {
gfxWarning() << "DrawTargetCairo context in error state: "
<< cairo_status_to_string(status) << "(" << status << ")";
}
}
private:
#ifdef DEBUG
Matrix GetTransform() {
cairo_matrix_t mat;
cairo_get_matrix(mCtx, &mat);
return Matrix(mat.xx, mat.yx, mat.xy, mat.yy, mat.x0, mat.y0);
}
#endif
cairo_t* mCtx;
};
/* Clamp r to (0,0) (2^23,2^23)
* these are to be device coordinates.
*
* Returns false if the rectangle is completely out of bounds,
* true otherwise.
*
* This function assumes that it will be called with a rectangle being
* drawn into a surface with an identity transformation matrix; that
* is, anything above or to the left of (0,0) will be offscreen.
*
* First it checks if the rectangle is entirely beyond
* CAIRO_COORD_MAX; if so, it can't ever appear on the screen --
* false is returned.
*
* Then it shifts any rectangles with x/y < 0 so that x and y are = 0,
* and adjusts the width and height appropriately. For example, a
* rectangle from (0,-5) with dimensions (5,10) will become a
* rectangle from (0,0) with dimensions (5,5).
*
* If after negative x/y adjustment to 0, either the width or height
* is negative, then the rectangle is completely offscreen, and
* nothing is drawn -- false is returned.
*
* Finally, if x+width or y+height are greater than CAIRO_COORD_MAX,
* the width and height are clamped such x+width or y+height are equal
* to CAIRO_COORD_MAX, and true is returned.
*/
static bool ConditionRect(Rect& r) {
// if either x or y is way out of bounds;
// note that we don't handle negative w/h here
if (r.X() > CAIRO_COORD_MAX || r.Y() > CAIRO_COORD_MAX) return false;
if (r.X() < 0.f) {
r.SetWidth(r.XMost());
if (r.Width() < 0.f) return false;
r.MoveToX(0.f);
}
if (r.XMost() > CAIRO_COORD_MAX) {
r.SetRightEdge(CAIRO_COORD_MAX);
}
if (r.Y() < 0.f) {
r.SetHeight(r.YMost());
if (r.Height() < 0.f) return false;
r.MoveToY(0.f);
}
if (r.YMost() > CAIRO_COORD_MAX) {
r.SetBottomEdge(CAIRO_COORD_MAX);
}
return true;
}
} // end anonymous namespace
static bool SupportsSelfCopy(cairo_surface_t* surface) {
switch (cairo_surface_get_type(surface)) {
#ifdef CAIRO_HAS_QUARTZ_SURFACE
case CAIRO_SURFACE_TYPE_QUARTZ:
return true;
#endif
#ifdef CAIRO_HAS_WIN32_SURFACE
case CAIRO_SURFACE_TYPE_WIN32:
case CAIRO_SURFACE_TYPE_WIN32_PRINTING:
return true;
#endif
default:
return false;
}
}
static bool PatternIsCompatible(const Pattern& aPattern) {
switch (aPattern.GetType()) {
case PatternType::LINEAR_GRADIENT: {
const LinearGradientPattern& pattern =
static_cast<const LinearGradientPattern&>(aPattern);
return pattern.mStops->GetBackendType() == BackendType::CAIRO;
}
case PatternType::RADIAL_GRADIENT: {
const RadialGradientPattern& pattern =
static_cast<const RadialGradientPattern&>(aPattern);
return pattern.mStops->GetBackendType() == BackendType::CAIRO;
}
case PatternType::CONIC_GRADIENT: {
const ConicGradientPattern& pattern =
static_cast<const ConicGradientPattern&>(aPattern);
return pattern.mStops->GetBackendType() == BackendType::CAIRO;
}
default:
return true;
}
}
static cairo_user_data_key_t surfaceDataKey;
static void ReleaseData(void* aData) {
DataSourceSurface* data = static_cast<DataSourceSurface*>(aData);
data->Unmap();
data->Release();
}
static cairo_surface_t* CopyToImageSurface(unsigned char* aData,
const IntRect& aRect,
int32_t aStride,
SurfaceFormat aFormat) {
MOZ_ASSERT(aData);
auto aRectWidth = aRect.Width();
auto aRectHeight = aRect.Height();
cairo_surface_t* surf = cairo_image_surface_create(
GfxFormatToCairoFormat(aFormat), aRectWidth, aRectHeight);
// In certain scenarios, requesting larger than 8k image fails. Bug 803568
// covers the details of how to run into it, but the full detailed
// investigation hasn't been done to determine the underlying cause. We
// will just handle the failure to allocate the surface to avoid a crash.
if (cairo_surface_status(surf)) {
gfxWarning() << "Invalid surface DTC " << cairo_surface_status(surf);
return nullptr;
}
unsigned char* surfData = cairo_image_surface_get_data(surf);
int surfStride = cairo_image_surface_get_stride(surf);
int32_t pixelWidth = BytesPerPixel(aFormat);
unsigned char* source = aData + aRect.Y() * aStride + aRect.X() * pixelWidth;
MOZ_ASSERT(aStride >= aRectWidth * pixelWidth);
for (int32_t y = 0; y < aRectHeight; ++y) {
memcpy(surfData + y * surfStride, source + y * aStride,
aRectWidth * pixelWidth);
}
cairo_surface_mark_dirty(surf);
return surf;
}
/**
* If aSurface can be represented as a surface of type
* CAIRO_SURFACE_TYPE_IMAGE then returns that surface. Does
* not add a reference.
*/
static cairo_surface_t* GetAsImageSurface(cairo_surface_t* aSurface) {
if (cairo_surface_get_type(aSurface) == CAIRO_SURFACE_TYPE_IMAGE) {
return aSurface;
#ifdef CAIRO_HAS_WIN32_SURFACE
} else if (cairo_surface_get_type(aSurface) == CAIRO_SURFACE_TYPE_WIN32) {
return cairo_win32_surface_get_image(aSurface);
#endif
}
return nullptr;
}
static cairo_surface_t* CreateSubImageForData(unsigned char* aData,
const IntRect& aRect, int aStride,
SurfaceFormat aFormat) {
if (!aData) {
gfxWarning() << "DrawTargetCairo.CreateSubImageForData null aData";
return nullptr;
}
unsigned char* data =
aData + aRect.Y() * aStride + aRect.X() * BytesPerPixel(aFormat);
cairo_surface_t* image = cairo_image_surface_create_for_data(
data, GfxFormatToCairoFormat(aFormat), aRect.Width(), aRect.Height(),
aStride);
// Set the subimage's device offset so that in remains in the same place
// relative to the parent
cairo_surface_set_device_offset(image, -aRect.X(), -aRect.Y());
return image;
}
/**
* Returns a referenced cairo_surface_t representing the
* sub-image specified by aSubImage.
*/
static cairo_surface_t* ExtractSubImage(cairo_surface_t* aSurface,
const IntRect& aSubImage,
SurfaceFormat aFormat) {
// No need to worry about retaining a reference to the original
// surface since the only caller of this function guarantees
// that aSurface will stay alive as long as the result
cairo_surface_t* image = GetAsImageSurface(aSurface);
if (image) {
image =
CreateSubImageForData(cairo_image_surface_get_data(image), aSubImage,
cairo_image_surface_get_stride(image), aFormat);
return image;
}
cairo_surface_t* similar = cairo_surface_create_similar(
aSurface, cairo_surface_get_content(aSurface), aSubImage.Width(),
aSubImage.Height());
cairo_t* ctx = cairo_create(similar);
cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
cairo_set_source_surface(ctx, aSurface, -aSubImage.X(), -aSubImage.Y());
cairo_paint(ctx);
cairo_destroy(ctx);
cairo_surface_set_device_offset(similar, -aSubImage.X(), -aSubImage.Y());
return similar;
}
/**
* Returns cairo surface for the given SourceSurface.
* If possible, it will use the cairo_surface associated with aSurface,
* otherwise, it will create a new cairo_surface.
* In either case, the caller must call cairo_surface_destroy on the
* result when it is done with it.
*/
static cairo_surface_t* GetCairoSurfaceForSourceSurface(
SourceSurface* aSurface, bool aExistingOnly = false,
const IntRect& aSubImage = IntRect()) {
if (!aSurface) {
return nullptr;
}
IntRect subimage = IntRect(IntPoint(), aSurface->GetSize());
if (!aSubImage.IsEmpty()) {
MOZ_ASSERT(!aExistingOnly);
MOZ_ASSERT(subimage.Contains(aSubImage));
subimage = aSubImage;
}
if (aSurface->GetType() == SurfaceType::CAIRO) {
cairo_surface_t* surf =
static_cast<SourceSurfaceCairo*>(aSurface)->GetSurface();
if (aSubImage.IsEmpty()) {
cairo_surface_reference(surf);
} else {
surf = ExtractSubImage(surf, subimage, aSurface->GetFormat());
}
return surf;
}
if (aSurface->GetType() == SurfaceType::CAIRO_IMAGE) {
cairo_surface_t* surf =
static_cast<const DataSourceSurfaceCairo*>(aSurface)->GetSurface();
if (aSubImage.IsEmpty()) {
cairo_surface_reference(surf);
} else {
surf = ExtractSubImage(surf, subimage, aSurface->GetFormat());
}
return surf;
}
if (aExistingOnly) {
return nullptr;
}
RefPtr<DataSourceSurface> data = aSurface->GetDataSurface();
if (!data) {
return nullptr;
}
DataSourceSurface::MappedSurface map;
if (!data->Map(DataSourceSurface::READ, &map)) {
return nullptr;
}
cairo_surface_t* surf = CreateSubImageForData(map.mData, subimage,
map.mStride, data->GetFormat());
// In certain scenarios, requesting larger than 8k image fails. Bug 803568
// covers the details of how to run into it, but the full detailed
// investigation hasn't been done to determine the underlying cause. We
// will just handle the failure to allocate the surface to avoid a crash.
if (!surf || cairo_surface_status(surf)) {
if (surf && (cairo_surface_status(surf) == CAIRO_STATUS_INVALID_STRIDE)) {
// If we failed because of an invalid stride then copy into
// a new surface with a stride that cairo chooses. No need to
// set user data since we're not dependent on the original
// data.
cairo_surface_t* result = CopyToImageSurface(
map.mData, subimage, map.mStride, data->GetFormat());
data->Unmap();
return result;
}
data->Unmap();
return nullptr;
}
cairo_surface_set_user_data(surf, &surfaceDataKey, data.forget().take(),
ReleaseData);
return surf;
}
// An RAII class to temporarily clear any device offset set
// on a surface. Note that this does not take a reference to the
// surface.
class AutoClearDeviceOffset final {
public:
explicit AutoClearDeviceOffset(SourceSurface* aSurface)
: mSurface(nullptr), mX(0), mY(0) {
Init(aSurface);
}
explicit AutoClearDeviceOffset(const Pattern& aPattern)
: mSurface(nullptr), mX(0.0), mY(0.0) {
if (aPattern.GetType() == PatternType::SURFACE) {
const SurfacePattern& pattern =
static_cast<const SurfacePattern&>(aPattern);
Init(pattern.mSurface);
}
}
~AutoClearDeviceOffset() {
if (mSurface) {
cairo_surface_set_device_offset(mSurface, mX, mY);
}
}
private:
void Init(SourceSurface* aSurface) {
cairo_surface_t* surface = GetCairoSurfaceForSourceSurface(aSurface, true);
if (surface) {
Init(surface);
cairo_surface_destroy(surface);
}
}
void Init(cairo_surface_t* aSurface) {
mSurface = aSurface;
cairo_surface_get_device_offset(mSurface, &mX, &mY);
cairo_surface_set_device_offset(mSurface, 0, 0);
}
cairo_surface_t* mSurface;
double mX;
double mY;
};
static inline void CairoPatternAddGradientStop(cairo_pattern_t* aPattern,
const GradientStop& aStop,
Float aNudge = 0) {
cairo_pattern_add_color_stop_rgba(aPattern, aStop.offset + aNudge,
aStop.color.r, aStop.color.g, aStop.color.b,
aStop.color.a);
}
// Never returns nullptr. As such, you must always pass in Cairo-compatible
// patterns, most notably gradients with a GradientStopCairo.
// The pattern returned must have cairo_pattern_destroy() called on it by the
// caller.
// As the cairo_pattern_t returned may depend on the Pattern passed in, the
// lifetime of the cairo_pattern_t returned must not exceed the lifetime of the
// Pattern passed in.
static cairo_pattern_t* GfxPatternToCairoPattern(const Pattern& aPattern,
Float aAlpha,
const Matrix& aTransform) {
cairo_pattern_t* pat;
const Matrix* matrix = nullptr;
switch (aPattern.GetType()) {
case PatternType::COLOR: {
DeviceColor color = static_cast<const ColorPattern&>(aPattern).mColor;
pat = cairo_pattern_create_rgba(color.r, color.g, color.b,
color.a * aAlpha);
break;
}
case PatternType::SURFACE: {
const SurfacePattern& pattern =
static_cast<const SurfacePattern&>(aPattern);
cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(
pattern.mSurface, false, pattern.mSamplingRect);
if (!surf) return nullptr;
pat = cairo_pattern_create_for_surface(surf);
matrix = &pattern.mMatrix;
cairo_pattern_set_filter(
pat, GfxSamplingFilterToCairoFilter(pattern.mSamplingFilter));
cairo_pattern_set_extend(pat,
GfxExtendToCairoExtend(pattern.mExtendMode));
cairo_surface_destroy(surf);
break;
}
case PatternType::LINEAR_GRADIENT: {
const LinearGradientPattern& pattern =
static_cast<const LinearGradientPattern&>(aPattern);
pat = cairo_pattern_create_linear(pattern.mBegin.x, pattern.mBegin.y,
pattern.mEnd.x, pattern.mEnd.y);
MOZ_ASSERT(pattern.mStops->GetBackendType() == BackendType::CAIRO);
GradientStopsCairo* cairoStops =
static_cast<GradientStopsCairo*>(pattern.mStops.get());
cairo_pattern_set_extend(
pat, GfxExtendToCairoExtend(cairoStops->GetExtendMode()));
matrix = &pattern.mMatrix;
const std::vector<GradientStop>& stops = cairoStops->GetStops();
for (size_t i = 0; i < stops.size(); ++i) {
CairoPatternAddGradientStop(pat, stops[i]);
}
break;
}
case PatternType::RADIAL_GRADIENT: {
const RadialGradientPattern& pattern =
static_cast<const RadialGradientPattern&>(aPattern);
pat = cairo_pattern_create_radial(pattern.mCenter1.x, pattern.mCenter1.y,
pattern.mRadius1, pattern.mCenter2.x,
pattern.mCenter2.y, pattern.mRadius2);
MOZ_ASSERT(pattern.mStops->GetBackendType() == BackendType::CAIRO);
GradientStopsCairo* cairoStops =
static_cast<GradientStopsCairo*>(pattern.mStops.get());
cairo_pattern_set_extend(
pat, GfxExtendToCairoExtend(cairoStops->GetExtendMode()));
matrix = &pattern.mMatrix;
const std::vector<GradientStop>& stops = cairoStops->GetStops();
for (size_t i = 0; i < stops.size(); ++i) {
CairoPatternAddGradientStop(pat, stops[i]);
}
break;
}
case PatternType::CONIC_GRADIENT: {
// XXX(ntim): Bug 1617039 - Implement conic-gradient for Cairo
pat = cairo_pattern_create_rgba(0.0, 0.0, 0.0, 0.0);
break;
}
default: {
// We should support all pattern types!
MOZ_ASSERT(false);
}
}
// The pattern matrix is a matrix that transforms the pattern into user
// space. Cairo takes a matrix that converts from user space to pattern
// space. Cairo therefore needs the inverse.
if (matrix) {
cairo_matrix_t mat;
GfxMatrixToCairoMatrix(*matrix, mat);
cairo_matrix_invert(&mat);
cairo_pattern_set_matrix(pat, &mat);
}
return pat;
}
static bool NeedIntermediateSurface(const Pattern& aPattern,
const DrawOptions& aOptions) {
// We pre-multiply colours' alpha by the global alpha, so we don't need to
// use an intermediate surface for them.
if (aPattern.GetType() == PatternType::COLOR) return false;
if (aOptions.mAlpha == 1.0) return false;
return true;
}
DrawTargetCairo::DrawTargetCairo()
: mContext(nullptr),
mSurface(nullptr),
mTransformSingular(false),
mLockedBits(nullptr),
mFontOptions(nullptr) {}
DrawTargetCairo::~DrawTargetCairo() {
cairo_destroy(mContext);
if (mSurface) {
cairo_surface_destroy(mSurface);
mSurface = nullptr;
}
if (mFontOptions) {
cairo_font_options_destroy(mFontOptions);
mFontOptions = nullptr;
}
MOZ_ASSERT(!mLockedBits);
}
bool DrawTargetCairo::IsValid() const {
return mSurface && !cairo_surface_status(mSurface) && mContext &&
!cairo_surface_status(cairo_get_group_target(mContext));
}
DrawTargetType DrawTargetCairo::GetType() const {
if (mContext) {
cairo_surface_type_t type = cairo_surface_get_type(mSurface);
if (type == CAIRO_SURFACE_TYPE_TEE) {
type = cairo_surface_get_type(cairo_tee_surface_index(mSurface, 0));
MOZ_ASSERT(type != CAIRO_SURFACE_TYPE_TEE, "C'mon!");
MOZ_ASSERT(
type == cairo_surface_get_type(cairo_tee_surface_index(mSurface, 1)),
"What should we do here?");
}
switch (type) {
case CAIRO_SURFACE_TYPE_PDF:
case CAIRO_SURFACE_TYPE_PS:
case CAIRO_SURFACE_TYPE_SVG:
case CAIRO_SURFACE_TYPE_WIN32_PRINTING:
case CAIRO_SURFACE_TYPE_XML:
return DrawTargetType::VECTOR;
case CAIRO_SURFACE_TYPE_VG:
case CAIRO_SURFACE_TYPE_GL:
case CAIRO_SURFACE_TYPE_GLITZ:
case CAIRO_SURFACE_TYPE_QUARTZ:
case CAIRO_SURFACE_TYPE_DIRECTFB:
return DrawTargetType::HARDWARE_RASTER;
case CAIRO_SURFACE_TYPE_SKIA:
case CAIRO_SURFACE_TYPE_QT:
MOZ_FALLTHROUGH_ASSERT(
"Can't determine actual DrawTargetType for DrawTargetCairo - "
"assuming SOFTWARE_RASTER");
case CAIRO_SURFACE_TYPE_IMAGE:
case CAIRO_SURFACE_TYPE_XLIB:
case CAIRO_SURFACE_TYPE_XCB:
case CAIRO_SURFACE_TYPE_WIN32:
case CAIRO_SURFACE_TYPE_BEOS:
case CAIRO_SURFACE_TYPE_OS2:
case CAIRO_SURFACE_TYPE_QUARTZ_IMAGE:
case CAIRO_SURFACE_TYPE_SCRIPT:
case CAIRO_SURFACE_TYPE_RECORDING:
case CAIRO_SURFACE_TYPE_DRM:
case CAIRO_SURFACE_TYPE_SUBSURFACE:
case CAIRO_SURFACE_TYPE_TEE: // included to silence warning about
// unhandled enum value
return DrawTargetType::SOFTWARE_RASTER;
default:
MOZ_CRASH("GFX: Unsupported cairo surface type");
}
}
MOZ_ASSERT(false, "Could not determine DrawTargetType for DrawTargetCairo");
return DrawTargetType::SOFTWARE_RASTER;
}
IntSize DrawTargetCairo::GetSize() const { return mSize; }
SurfaceFormat GfxFormatForCairoSurface(cairo_surface_t* surface) {
cairo_surface_type_t type = cairo_surface_get_type(surface);
if (type == CAIRO_SURFACE_TYPE_IMAGE) {
return CairoFormatToGfxFormat(cairo_image_surface_get_format(surface));
}
#ifdef CAIRO_HAS_XLIB_SURFACE
// xlib is currently the only Cairo backend that creates 16bpp surfaces
if (type == CAIRO_SURFACE_TYPE_XLIB &&
cairo_xlib_surface_get_depth(surface) == 16) {
return SurfaceFormat::R5G6B5_UINT16;
}
#endif
return CairoContentToGfxFormat(cairo_surface_get_content(surface));
}
void DrawTargetCairo::Link(const char* aDestination, const Rect& aRect) {
if (!aDestination || !*aDestination) {
// No destination? Just bail out.
return;
}
// We need to \-escape any single-quotes in the destination string, in order
// to pass it via the attributes arg to cairo_tag_begin.
//
// We also need to escape any backslashes (bug 1748077), as per doc at
// https://www.cairographics.org/manual/cairo-Tags-and-Links.html#cairo-tag-begin
// The cairo-pdf-interchange backend (used on all platforms EXCEPT macOS)
// actually requires that we *doubly* escape the backslashes (this may be a
// cairo bug), while the quartz backend is fine with them singly-escaped.
//
// (Encoding of non-ASCII chars etc gets handled later by the PDF backend.)
nsAutoCString dest(aDestination);
for (size_t i = dest.Length(); i > 0;) {
--i;
if (dest[i] == '\'') {
dest.ReplaceLiteral(i, 1, "\\'");
} else if (dest[i] == '\\') {
#ifdef XP_MACOSX
dest.ReplaceLiteral(i, 1, "\\\\");
#else
dest.ReplaceLiteral(i, 1, "\\\\\\\\");
#endif
}
}
double x = aRect.x, y = aRect.y, w = aRect.width, h = aRect.height;
cairo_user_to_device(mContext, &x, &y);
cairo_user_to_device_distance(mContext, &w, &h);
nsPrintfCString attributes("rect=[%f %f %f %f] ", x, y, w, h);
if (dest[0] == '#') {
// The actual destination does not have a leading '#'.
attributes.AppendPrintf("dest='%s'", dest.get() + 1);
} else {
attributes.AppendPrintf("uri='%s'", dest.get());
}
// We generate a begin/end pair with no content in between, because we are
// using the rect attribute of the begin tag to specify the link region
// rather than depending on cairo to accumulate the painted area.
cairo_tag_begin(mContext, CAIRO_TAG_LINK, attributes.get());
cairo_tag_end(mContext, CAIRO_TAG_LINK);
}
void DrawTargetCairo::Destination(const char* aDestination,
const Point& aPoint) {
if (!aDestination || !*aDestination) {
// No destination? Just bail out.
return;
}
nsAutoCString dest(aDestination);
for (size_t i = dest.Length(); i > 0;) {
--i;
if (dest[i] == '\'') {
dest.ReplaceLiteral(i, 1, "\\'");
}
}
double x = aPoint.x, y = aPoint.y;
cairo_user_to_device(mContext, &x, &y);
nsPrintfCString attributes("name='%s' x=%f y=%f internal", dest.get(), x, y);
cairo_tag_begin(mContext, CAIRO_TAG_DEST, attributes.get());
cairo_tag_end(mContext, CAIRO_TAG_DEST);
}
already_AddRefed<SourceSurface> DrawTargetCairo::Snapshot() {
if (!IsValid()) {
gfxCriticalNote << "DrawTargetCairo::Snapshot with bad surface "
<< hexa(mSurface) << ", context " << hexa(mContext)
<< ", status "
<< (mSurface ? cairo_surface_status(mSurface) : -1);
return nullptr;
}
if (mSnapshot) {
RefPtr<SourceSurface> snapshot(mSnapshot);
return snapshot.forget();
}
IntSize size = GetSize();
mSnapshot = new SourceSurfaceCairo(mSurface, size,
GfxFormatForCairoSurface(mSurface), this);
RefPtr<SourceSurface> snapshot(mSnapshot);
return snapshot.forget();
}
bool DrawTargetCairo::LockBits(uint8_t** aData, IntSize* aSize,
int32_t* aStride, SurfaceFormat* aFormat,
IntPoint* aOrigin) {
cairo_surface_t* target = cairo_get_group_target(mContext);
cairo_surface_t* surf = target;
#ifdef CAIRO_HAS_WIN32_SURFACE
if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
if (imgsurf) {
surf = imgsurf;
}
}
#endif
if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_IMAGE &&
cairo_surface_status(surf) == CAIRO_STATUS_SUCCESS) {
PointDouble offset;
cairo_surface_get_device_offset(target, &offset.x.value, &offset.y.value);
// verify the device offset can be converted to integers suitable for a
// bounds rect
IntPoint origin(int32_t(-offset.x), int32_t(-offset.y));
if (-PointDouble(origin) != offset || (!aOrigin && origin != IntPoint())) {
return false;
}
WillChange();
Flush();
mLockedBits = cairo_image_surface_get_data(surf);
*aData = mLockedBits;
*aSize = IntSize(cairo_image_surface_get_width(surf),
cairo_image_surface_get_height(surf));
*aStride = cairo_image_surface_get_stride(surf);
*aFormat = CairoFormatToGfxFormat(cairo_image_surface_get_format(surf));
if (aOrigin) {
*aOrigin = origin;
}
return true;
}
return false;
}
void DrawTargetCairo::ReleaseBits(uint8_t* aData) {
MOZ_ASSERT(mLockedBits == aData);
mLockedBits = nullptr;
cairo_surface_t* surf = cairo_get_group_target(mContext);
#ifdef CAIRO_HAS_WIN32_SURFACE
if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
if (imgsurf) {
cairo_surface_mark_dirty(imgsurf);
}
}
#endif
cairo_surface_mark_dirty(surf);
}
void DrawTargetCairo::Flush() {
cairo_surface_t* surf = cairo_get_group_target(mContext);
cairo_surface_flush(surf);
}
void DrawTargetCairo::PrepareForDrawing(cairo_t* aContext,
const Path* aPath /* = nullptr */) {
WillChange(aPath);
}
cairo_surface_t* DrawTargetCairo::GetDummySurface() {
if (mDummySurface) {
return mDummySurface;
}
mDummySurface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
return mDummySurface;
}
static void PaintWithAlpha(cairo_t* aContext, const DrawOptions& aOptions) {
if (aOptions.mCompositionOp == CompositionOp::OP_SOURCE) {
// Cairo treats the source operator like a lerp when alpha is < 1.
// Approximate the desired operator by: out = 0; out += src*alpha;
if (aOptions.mAlpha == 1) {
cairo_set_operator(aContext, CAIRO_OPERATOR_SOURCE);
cairo_paint(aContext);
} else {
cairo_set_operator(aContext, CAIRO_OPERATOR_CLEAR);
cairo_paint(aContext);
cairo_set_operator(aContext, CAIRO_OPERATOR_ADD);
cairo_paint_with_alpha(aContext, aOptions.mAlpha);
}
} else {
cairo_set_operator(aContext, GfxOpToCairoOp(aOptions.mCompositionOp));
cairo_paint_with_alpha(aContext, aOptions.mAlpha);
}
}
void DrawTargetCairo::DrawSurface(SourceSurface* aSurface, const Rect& aDest,
const Rect& aSource,
const DrawSurfaceOptions& aSurfOptions,
const DrawOptions& aOptions) {
if (mTransformSingular || aDest.IsEmpty()) {
return;
}
if (!IsValid() || !aSurface) {
gfxCriticalNote << "DrawSurface with bad surface "
<< cairo_surface_status(cairo_get_group_target(mContext));
return;
}
AutoPrepareForDrawing prep(this, mContext);
AutoClearDeviceOffset clear(aSurface);
float sx = aSource.Width() / aDest.Width();
float sy = aSource.Height() / aDest.Height();
cairo_matrix_t src_mat;
cairo_matrix_init_translate(&src_mat, aSource.X() - aSurface->GetRect().x,
aSource.Y() - aSurface->GetRect().y);
cairo_matrix_scale(&src_mat, sx, sy);
cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(aSurface);
if (!surf) {
gfxWarning()
<< "Failed to create cairo surface for DrawTargetCairo::DrawSurface";
return;
}
cairo_pattern_t* pat = cairo_pattern_create_for_surface(surf);
cairo_surface_destroy(surf);
cairo_pattern_set_matrix(pat, &src_mat);
cairo_pattern_set_filter(
pat, GfxSamplingFilterToCairoFilter(aSurfOptions.mSamplingFilter));
// For PDF output, we avoid using EXTEND_PAD here because floating-point
// error accumulation may lead cairo_pdf_surface to conclude that padding
// is needed due to an apparent one- or two-pixel mismatch between source
// pattern and destination rect sizes when we're rendering a pdf.js page,
// and this forces undesirable fallback to the rasterization codepath
// instead of simply replaying the recording.
// (See bug 1777209.)
cairo_pattern_set_extend(
pat, cairo_surface_get_type(mSurface) == CAIRO_SURFACE_TYPE_PDF
? CAIRO_EXTEND_NONE
: CAIRO_EXTEND_PAD);
cairo_set_antialias(mContext,
GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
// If the destination rect covers the entire clipped area, then unbounded and
// bounded operations are identical, and we don't need to push a group.
bool needsGroup = !IsOperatorBoundByMask(aOptions.mCompositionOp) &&
!aDest.Contains(GetUserSpaceClip());
cairo_translate(mContext, aDest.X(), aDest.Y());
if (needsGroup) {
cairo_push_group(mContext);
cairo_new_path(mContext);
cairo_rectangle(mContext, 0, 0, aDest.Width(), aDest.Height());
cairo_set_source(mContext, pat);
cairo_fill(mContext);
cairo_pop_group_to_source(mContext);
} else {
cairo_new_path(mContext);
cairo_rectangle(mContext, 0, 0, aDest.Width(), aDest.Height());
cairo_clip(mContext);
cairo_set_source(mContext, pat);
}
PaintWithAlpha(mContext, aOptions);
cairo_pattern_destroy(pat);
}
void DrawTargetCairo::DrawFilter(FilterNode* aNode, const Rect& aSourceRect,
const Point& aDestPoint,
const DrawOptions& aOptions) {
FilterNodeSoftware* filter = static_cast<FilterNodeSoftware*>(aNode);
filter->Draw(this, aSourceRect, aDestPoint, aOptions);
}
void DrawTargetCairo::DrawSurfaceWithShadow(SourceSurface* aSurface,
const Point& aDest,
const ShadowOptions& aShadow,
CompositionOp aOperator) {
if (!IsValid() || !aSurface) {
gfxCriticalNote << "DrawSurfaceWithShadow with bad surface "
<< cairo_surface_status(cairo_get_group_target(mContext));
return;
}
if (aSurface->GetType() != SurfaceType::CAIRO) {
return;
}
AutoClearDeviceOffset clear(aSurface);
Float width = Float(aSurface->GetSize().width);
Float height = Float(aSurface->GetSize().height);
SourceSurfaceCairo* source = static_cast<SourceSurfaceCairo*>(aSurface);
cairo_surface_t* sourcesurf = source->GetSurface();
cairo_surface_t* blursurf;
cairo_surface_t* surf;
// We only use the A8 surface for blurred shadows. Unblurred shadows can just
// use the RGBA surface directly.
if (cairo_surface_get_type(sourcesurf) == CAIRO_SURFACE_TYPE_TEE) {
blursurf = cairo_tee_surface_index(sourcesurf, 0);
surf = cairo_tee_surface_index(sourcesurf, 1);
} else {
blursurf = sourcesurf;
surf = sourcesurf;
}
if (aShadow.mSigma != 0.0f) {
MOZ_ASSERT(cairo_surface_get_type(blursurf) == CAIRO_SURFACE_TYPE_IMAGE);
Rect extents(0, 0, width, height);
AlphaBoxBlur blur(extents, cairo_image_surface_get_stride(blursurf),
aShadow.mSigma, aShadow.mSigma);
blur.Blur(cairo_image_surface_get_data(blursurf));
}
WillChange();
ClearSurfaceForUnboundedSource(aOperator);
cairo_save(mContext);
cairo_set_operator(mContext, GfxOpToCairoOp(aOperator));
cairo_identity_matrix(mContext);
cairo_translate(mContext, aDest.x, aDest.y);
bool needsGroup = !IsOperatorBoundByMask(aOperator);
if (needsGroup) {
cairo_push_group(mContext);
}
cairo_set_source_rgba(mContext, aShadow.mColor.r, aShadow.mColor.g,
aShadow.mColor.b, aShadow.mColor.a);
cairo_mask_surface(mContext, blursurf, aShadow.mOffset.x, aShadow.mOffset.y);
if (blursurf != surf || aSurface->GetFormat() != SurfaceFormat::A8) {
// Now that the shadow has been drawn, we can draw the surface on top.
cairo_set_source_surface(mContext, surf, 0, 0);
cairo_new_path(mContext);
cairo_rectangle(mContext, 0, 0, width, height);
cairo_fill(mContext);