forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrawTargetSkia.cpp
2083 lines (1799 loc) · 70 KB
/
DrawTargetSkia.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 "DrawTargetSkia.h"
#include "SourceSurfaceSkia.h"
#include "ScaledFontBase.h"
#include "FilterNodeSoftware.h"
#include "HelpersSkia.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Vector.h"
#include "skia/include/core/SkBitmap.h"
#include "skia/include/core/SkCanvas.h"
#include "skia/include/core/SkFont.h"
#include "skia/include/core/SkSurface.h"
#include "skia/include/core/SkTextBlob.h"
#include "skia/include/core/SkTypeface.h"
#include "skia/include/effects/SkGradientShader.h"
#include "skia/include/core/SkColorFilter.h"
#include "skia/include/core/SkRegion.h"
#include "skia/include/effects/SkImageFilters.h"
#include "skia/include/private/base/SkMalloc.h"
#include "Blur.h"
#include "Logging.h"
#include "Tools.h"
#include "PathHelpers.h"
#include "PathSkia.h"
#include "Swizzle.h"
#include <algorithm>
#include <cmath>
#ifdef MOZ_WIDGET_COCOA
# include "BorrowedContext.h"
# include <ApplicationServices/ApplicationServices.h>
#endif
#ifdef XP_WIN
# include "ScaledFontDWrite.h"
#endif
namespace mozilla {
void RefPtrTraits<SkSurface>::Release(SkSurface* aSurface) {
SkSafeUnref(aSurface);
}
void RefPtrTraits<SkSurface>::AddRef(SkSurface* aSurface) {
SkSafeRef(aSurface);
}
} // namespace mozilla
namespace mozilla::gfx {
class GradientStopsSkia : public GradientStops {
public:
MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(GradientStopsSkia, override)
GradientStopsSkia(const std::vector<GradientStop>& aStops, uint32_t aNumStops,
ExtendMode aExtendMode)
: mCount(aNumStops), mExtendMode(aExtendMode) {
if (mCount == 0) {
return;
}
// Skia gradients always require a stop at 0.0 and 1.0, insert these if
// we don't have them.
uint32_t shift = 0;
if (aStops[0].offset != 0) {
mCount++;
shift = 1;
}
if (aStops[aNumStops - 1].offset != 1) {
mCount++;
}
mColors.resize(mCount);
mPositions.resize(mCount);
if (aStops[0].offset != 0) {
mColors[0] = ColorToSkColor(aStops[0].color, 1.0);
mPositions[0] = 0;
}
for (uint32_t i = 0; i < aNumStops; i++) {
mColors[i + shift] = ColorToSkColor(aStops[i].color, 1.0);
mPositions[i + shift] = SkFloatToScalar(aStops[i].offset);
}
if (aStops[aNumStops - 1].offset != 1) {
mColors[mCount - 1] = ColorToSkColor(aStops[aNumStops - 1].color, 1.0);
mPositions[mCount - 1] = SK_Scalar1;
}
}
BackendType GetBackendType() const override { return BackendType::SKIA; }
std::vector<SkColor> mColors;
std::vector<SkScalar> mPositions;
int mCount;
ExtendMode mExtendMode;
};
/**
* When constructing a temporary SkImage via GetSkImageForSurface, we may also
* have to construct a temporary DataSourceSurface, which must live as long as
* the SkImage. We attach this temporary surface to the image's pixelref, so
* that it can be released once the pixelref is freed.
*/
static void ReleaseTemporarySurface(const void* aPixels, void* aContext) {
DataSourceSurface* surf = static_cast<DataSourceSurface*>(aContext);
if (surf) {
surf->Release();
}
}
static void ReleaseTemporaryMappedSurface(const void* aPixels, void* aContext) {
DataSourceSurface* surf = static_cast<DataSourceSurface*>(aContext);
if (surf) {
surf->Unmap();
surf->Release();
}
}
static void WriteRGBXFormat(uint8_t* aData, const IntSize& aSize,
const int32_t aStride, SurfaceFormat aFormat) {
if (aFormat != SurfaceFormat::B8G8R8X8 || aSize.IsEmpty()) {
return;
}
SwizzleData(aData, aStride, SurfaceFormat::X8R8G8B8_UINT32, aData, aStride,
SurfaceFormat::A8R8G8B8_UINT32, aSize);
}
#ifdef DEBUG
static IntRect CalculateSurfaceBounds(const IntSize& aSize, const Rect* aBounds,
const Matrix* aMatrix) {
IntRect surfaceBounds(IntPoint(0, 0), aSize);
if (!aBounds) {
return surfaceBounds;
}
MOZ_ASSERT(aMatrix);
Matrix inverse(*aMatrix);
if (!inverse.Invert()) {
return surfaceBounds;
}
IntRect bounds;
Rect sampledBounds = inverse.TransformBounds(*aBounds);
if (!sampledBounds.ToIntRect(&bounds)) {
return surfaceBounds;
}
return surfaceBounds.Intersect(bounds);
}
static const int kARGBAlphaOffset =
SurfaceFormat::A8R8G8B8_UINT32 == SurfaceFormat::B8G8R8A8 ? 3 : 0;
static bool VerifyRGBXFormat(uint8_t* aData, const IntSize& aSize,
const int32_t aStride, SurfaceFormat aFormat) {
if (aFormat != SurfaceFormat::B8G8R8X8 || aSize.IsEmpty()) {
return true;
}
// We should've initialized the data to be opaque already
// On debug builds, verify that this is actually true.
int height = aSize.height;
int width = aSize.width * 4;
for (int row = 0; row < height; ++row) {
for (int column = 0; column < width; column += 4) {
if (aData[column + kARGBAlphaOffset] != 0xFF) {
gfxCriticalError() << "RGBX pixel at (" << column << "," << row
<< ") in " << width << "x" << height
<< " surface is not opaque: " << int(aData[column])
<< "," << int(aData[column + 1]) << ","
<< int(aData[column + 2]) << ","
<< int(aData[column + 3]);
}
}
aData += aStride;
}
return true;
}
// Since checking every pixel is expensive, this only checks the four corners
// and center of a surface that their alpha value is 0xFF.
static bool VerifyRGBXCorners(uint8_t* aData, const IntSize& aSize,
const int32_t aStride, SurfaceFormat aFormat,
const Rect* aBounds = nullptr,
const Matrix* aMatrix = nullptr) {
if (aFormat != SurfaceFormat::B8G8R8X8 || aSize.IsEmpty()) {
return true;
}
IntRect bounds = CalculateSurfaceBounds(aSize, aBounds, aMatrix);
if (bounds.IsEmpty()) {
return true;
}
const int height = bounds.Height();
const int width = bounds.Width();
const int pixelSize = 4;
MOZ_ASSERT(aSize.width * pixelSize <= aStride);
const int translation = bounds.Y() * aStride + bounds.X() * pixelSize;
const int topLeft = translation;
const int topRight = topLeft + (width - 1) * pixelSize;
const int bottomLeft = translation + (height - 1) * aStride;
const int bottomRight = bottomLeft + (width - 1) * pixelSize;
// Lastly the center pixel
const int middleRowHeight = height / 2;
const int middleRowWidth = (width / 2) * pixelSize;
const int middle = translation + aStride * middleRowHeight + middleRowWidth;
const int offsets[] = {topLeft, topRight, bottomRight, bottomLeft, middle};
for (int offset : offsets) {
if (aData[offset + kARGBAlphaOffset] != 0xFF) {
int row = offset / aStride;
int column = (offset % aStride) / pixelSize;
gfxCriticalError() << "RGBX corner pixel at (" << column << "," << row
<< ") in " << aSize.width << "x" << aSize.height
<< " surface, bounded by "
<< "(" << bounds.X() << "," << bounds.Y() << ","
<< width << "," << height
<< ") is not opaque: " << int(aData[offset]) << ","
<< int(aData[offset + 1]) << ","
<< int(aData[offset + 2]) << ","
<< int(aData[offset + 3]);
}
}
return true;
}
#endif
static sk_sp<SkImage> GetSkImageForSurface(SourceSurface* aSurface,
Maybe<MutexAutoLock>* aLock,
const Rect* aBounds = nullptr,
const Matrix* aMatrix = nullptr) {
if (!aSurface) {
gfxDebug() << "Creating null Skia image from null SourceSurface";
return nullptr;
}
if (aSurface->GetType() == SurfaceType::SKIA) {
return static_cast<SourceSurfaceSkia*>(aSurface)->GetImage(aLock);
}
RefPtr<DataSourceSurface> dataSurface = aSurface->GetDataSurface();
if (!dataSurface) {
gfxWarning() << "Failed getting DataSourceSurface for Skia image";
return nullptr;
}
DataSourceSurface::MappedSurface map;
SkImage::RasterReleaseProc releaseProc;
if (dataSurface->GetType() == SurfaceType::DATA_SHARED_WRAPPER) {
// Technically all surfaces should be mapped and unmapped explicitly but it
// appears SourceSurfaceSkia and DataSourceSurfaceWrapper have issues with
// this. For now, we just map SourceSurfaceSharedDataWrapper to ensure we
// don't unmap the data during the transaction (for blob images).
if (!dataSurface->Map(DataSourceSurface::MapType::READ, &map)) {
gfxWarning() << "Failed mapping DataSourceSurface for Skia image";
return nullptr;
}
releaseProc = ReleaseTemporaryMappedSurface;
} else {
map.mData = dataSurface->GetData();
map.mStride = dataSurface->Stride();
releaseProc = ReleaseTemporarySurface;
}
DataSourceSurface* surf = dataSurface.forget().take();
// Skia doesn't support RGBX surfaces so ensure that the alpha value is opaque
// white.
MOZ_ASSERT(VerifyRGBXCorners(map.mData, surf->GetSize(), map.mStride,
surf->GetFormat(), aBounds, aMatrix));
SkPixmap pixmap(MakeSkiaImageInfo(surf->GetSize(), surf->GetFormat()),
map.mData, map.mStride);
sk_sp<SkImage> image = SkImage::MakeFromRaster(pixmap, releaseProc, surf);
if (!image) {
releaseProc(map.mData, surf);
gfxDebug() << "Failed making Skia raster image for temporary surface";
}
return image;
}
DrawTargetSkia::DrawTargetSkia()
: mCanvas(nullptr),
mSnapshot(nullptr),
mSnapshotLock{"DrawTargetSkia::mSnapshotLock"}
#ifdef MOZ_WIDGET_COCOA
,
mCG(nullptr),
mColorSpace(nullptr),
mCanvasData(nullptr),
mCGSize(0, 0),
mNeedLayer(false)
#endif
{
}
DrawTargetSkia::~DrawTargetSkia() {
if (mSnapshot) {
MutexAutoLock lock(mSnapshotLock);
// We're going to go away, hand our SkSurface to the SourceSurface.
mSnapshot->GiveSurface(mSurface.forget().take());
}
#ifdef MOZ_WIDGET_COCOA
if (mCG) {
CGContextRelease(mCG);
mCG = nullptr;
}
if (mColorSpace) {
CGColorSpaceRelease(mColorSpace);
mColorSpace = nullptr;
}
#endif
}
already_AddRefed<SourceSurface> DrawTargetSkia::Snapshot(
SurfaceFormat aFormat) {
// Without this lock, this could cause us to get out a snapshot and race with
// Snapshot::~Snapshot() actually destroying itself.
MutexAutoLock lock(mSnapshotLock);
if (mSnapshot && aFormat != mSnapshot->GetFormat()) {
if (!mSnapshot->hasOneRef()) {
mSnapshot->DrawTargetWillChange();
}
mSnapshot = nullptr;
}
RefPtr<SourceSurfaceSkia> snapshot = mSnapshot;
if (mSurface && !snapshot) {
snapshot = new SourceSurfaceSkia();
sk_sp<SkImage> image;
// If the surface is raster, making a snapshot may trigger a pixel copy.
// Instead, try to directly make a raster image referencing the surface
// pixels.
SkPixmap pixmap;
if (mSurface->peekPixels(&pixmap)) {
image = SkImage::MakeFromRaster(pixmap, nullptr, nullptr);
} else {
image = mSurface->makeImageSnapshot();
}
if (!snapshot->InitFromImage(image, aFormat, this)) {
return nullptr;
}
mSnapshot = snapshot;
}
return snapshot.forget();
}
already_AddRefed<SourceSurface> DrawTargetSkia::GetBackingSurface() {
if (mBackingSurface) {
RefPtr<SourceSurface> snapshot = mBackingSurface;
return snapshot.forget();
}
return Snapshot();
}
bool DrawTargetSkia::LockBits(uint8_t** aData, IntSize* aSize, int32_t* aStride,
SurfaceFormat* aFormat, IntPoint* aOrigin) {
SkImageInfo info;
size_t rowBytes;
SkIPoint origin;
void* pixels = mCanvas->accessTopLayerPixels(&info, &rowBytes, &origin);
if (!pixels ||
// Ensure the layer is at the origin if required.
(!aOrigin && !origin.isZero())) {
return false;
}
MarkChanged();
*aData = reinterpret_cast<uint8_t*>(pixels);
*aSize = IntSize(info.width(), info.height());
*aStride = int32_t(rowBytes);
*aFormat = SkiaColorTypeToGfxFormat(info.colorType(), info.alphaType());
if (aOrigin) {
*aOrigin = IntPoint(origin.x(), origin.y());
}
return true;
}
void DrawTargetSkia::ReleaseBits(uint8_t* aData) {}
static void ReleaseImage(const void* aPixels, void* aContext) {
SkImage* image = static_cast<SkImage*>(aContext);
SkSafeUnref(image);
}
static sk_sp<SkImage> ExtractSubset(sk_sp<SkImage> aImage,
const IntRect& aRect) {
SkIRect subsetRect = IntRectToSkIRect(aRect);
if (aImage->bounds() == subsetRect) {
return aImage;
}
// makeSubset is slow, so prefer to use SkPixmap::extractSubset where
// possible.
SkPixmap pixmap, subsetPixmap;
if (aImage->peekPixels(&pixmap) &&
pixmap.extractSubset(&subsetPixmap, subsetRect)) {
// Release the original image reference so only the subset image keeps it
// alive.
return SkImage::MakeFromRaster(subsetPixmap, ReleaseImage,
aImage.release());
}
return aImage->makeSubset(subsetRect);
}
static void FreeAlphaPixels(void* aBuf, void*) { sk_free(aBuf); }
static bool ExtractAlphaBitmap(const sk_sp<SkImage>& aImage,
SkBitmap* aResultBitmap,
bool aAllowReuse = false) {
SkPixmap pixmap;
if (aAllowReuse && aImage->isAlphaOnly() && aImage->peekPixels(&pixmap)) {
SkBitmap bitmap;
bitmap.installPixels(pixmap.info(), pixmap.writable_addr(),
pixmap.rowBytes());
*aResultBitmap = bitmap;
return true;
}
SkImageInfo info = SkImageInfo::MakeA8(aImage->width(), aImage->height());
// Skia does not fully allocate the last row according to stride.
// Since some of our algorithms (i.e. blur) depend on this, we must allocate
// the bitmap pixels manually.
size_t stride = GetAlignedStride<4>(info.width(), info.bytesPerPixel());
if (stride) {
CheckedInt<size_t> size = stride;
size *= info.height();
// We need to leave room for an additional 3 bytes for a potential overrun
// in our blurring code.
size += 3;
if (size.isValid()) {
void* buf = sk_malloc_flags(size.value(), 0);
if (buf) {
SkBitmap bitmap;
if (bitmap.installPixels(info, buf, stride, FreeAlphaPixels, nullptr) &&
aImage->readPixels(bitmap.info(), bitmap.getPixels(),
bitmap.rowBytes(), 0, 0)) {
*aResultBitmap = bitmap;
return true;
}
}
}
}
gfxWarning() << "Failed reading alpha pixels for Skia bitmap";
return false;
}
static void SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern,
Maybe<MutexAutoLock>& aLock, Float aAlpha = 1.0,
const SkMatrix* aMatrix = nullptr,
const Rect* aBounds = nullptr) {
switch (aPattern.GetType()) {
case PatternType::COLOR: {
DeviceColor color = static_cast<const ColorPattern&>(aPattern).mColor;
aPaint.setColor(ColorToSkColor(color, aAlpha));
break;
}
case PatternType::LINEAR_GRADIENT: {
const LinearGradientPattern& pat =
static_cast<const LinearGradientPattern&>(aPattern);
GradientStopsSkia* stops =
pat.mStops && pat.mStops->GetBackendType() == BackendType::SKIA
? static_cast<GradientStopsSkia*>(pat.mStops.get())
: nullptr;
if (!stops || stops->mCount < 2 || !pat.mBegin.IsFinite() ||
!pat.mEnd.IsFinite() || pat.mBegin == pat.mEnd) {
aPaint.setColor(SK_ColorTRANSPARENT);
} else {
SkTileMode mode = ExtendModeToTileMode(stops->mExtendMode, Axis::BOTH);
SkPoint points[2];
points[0] = SkPoint::Make(SkFloatToScalar(pat.mBegin.x),
SkFloatToScalar(pat.mBegin.y));
points[1] = SkPoint::Make(SkFloatToScalar(pat.mEnd.x),
SkFloatToScalar(pat.mEnd.y));
SkMatrix mat;
GfxMatrixToSkiaMatrix(pat.mMatrix, mat);
if (aMatrix) {
mat.postConcat(*aMatrix);
}
sk_sp<SkShader> shader = SkGradientShader::MakeLinear(
points, &stops->mColors.front(), &stops->mPositions.front(),
stops->mCount, mode, 0, &mat);
if (shader) {
aPaint.setShader(shader);
} else {
aPaint.setColor(SK_ColorTRANSPARENT);
}
}
break;
}
case PatternType::RADIAL_GRADIENT: {
const RadialGradientPattern& pat =
static_cast<const RadialGradientPattern&>(aPattern);
GradientStopsSkia* stops =
pat.mStops && pat.mStops->GetBackendType() == BackendType::SKIA
? static_cast<GradientStopsSkia*>(pat.mStops.get())
: nullptr;
if (!stops || stops->mCount < 2 || !pat.mCenter1.IsFinite() ||
!std::isfinite(pat.mRadius1) || !pat.mCenter2.IsFinite() ||
!std::isfinite(pat.mRadius2) ||
(pat.mCenter1 == pat.mCenter2 && pat.mRadius1 == pat.mRadius2)) {
aPaint.setColor(SK_ColorTRANSPARENT);
} else {
SkTileMode mode = ExtendModeToTileMode(stops->mExtendMode, Axis::BOTH);
SkPoint points[2];
points[0] = SkPoint::Make(SkFloatToScalar(pat.mCenter1.x),
SkFloatToScalar(pat.mCenter1.y));
points[1] = SkPoint::Make(SkFloatToScalar(pat.mCenter2.x),
SkFloatToScalar(pat.mCenter2.y));
SkMatrix mat;
GfxMatrixToSkiaMatrix(pat.mMatrix, mat);
if (aMatrix) {
mat.postConcat(*aMatrix);
}
sk_sp<SkShader> shader = SkGradientShader::MakeTwoPointConical(
points[0], SkFloatToScalar(pat.mRadius1), points[1],
SkFloatToScalar(pat.mRadius2), &stops->mColors.front(),
&stops->mPositions.front(), stops->mCount, mode, 0, &mat);
if (shader) {
aPaint.setShader(shader);
} else {
aPaint.setColor(SK_ColorTRANSPARENT);
}
}
break;
}
case PatternType::CONIC_GRADIENT: {
const ConicGradientPattern& pat =
static_cast<const ConicGradientPattern&>(aPattern);
GradientStopsSkia* stops =
pat.mStops && pat.mStops->GetBackendType() == BackendType::SKIA
? static_cast<GradientStopsSkia*>(pat.mStops.get())
: nullptr;
if (!stops || stops->mCount < 2 || !pat.mCenter.IsFinite() ||
!std::isfinite(pat.mAngle)) {
aPaint.setColor(SK_ColorTRANSPARENT);
} else {
SkMatrix mat;
GfxMatrixToSkiaMatrix(pat.mMatrix, mat);
if (aMatrix) {
mat.postConcat(*aMatrix);
}
SkScalar cx = SkFloatToScalar(pat.mCenter.x);
SkScalar cy = SkFloatToScalar(pat.mCenter.y);
// Skia's sweep gradient angles are relative to the x-axis, not the
// y-axis.
Float angle = (pat.mAngle * 180.0 / M_PI) - 90.0;
if (angle != 0.0) {
mat.preRotate(angle, cx, cy);
}
SkTileMode mode = ExtendModeToTileMode(stops->mExtendMode, Axis::BOTH);
sk_sp<SkShader> shader = SkGradientShader::MakeSweep(
cx, cy, &stops->mColors.front(), &stops->mPositions.front(),
stops->mCount, mode, 360 * pat.mStartOffset, 360 * pat.mEndOffset,
0, &mat);
if (shader) {
aPaint.setShader(shader);
} else {
aPaint.setColor(SK_ColorTRANSPARENT);
}
}
break;
}
case PatternType::SURFACE: {
const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
sk_sp<SkImage> image =
GetSkImageForSurface(pat.mSurface, &aLock, aBounds, &pat.mMatrix);
if (!image) {
aPaint.setColor(SK_ColorTRANSPARENT);
break;
}
SkMatrix mat;
GfxMatrixToSkiaMatrix(pat.mMatrix, mat);
if (aMatrix) {
mat.postConcat(*aMatrix);
}
if (!pat.mSamplingRect.IsEmpty()) {
image = ExtractSubset(image, pat.mSamplingRect);
if (!image) {
aPaint.setColor(SK_ColorTRANSPARENT);
break;
}
mat.preTranslate(pat.mSamplingRect.X(), pat.mSamplingRect.Y());
}
SkTileMode xTile = ExtendModeToTileMode(pat.mExtendMode, Axis::X_AXIS);
SkTileMode yTile = ExtendModeToTileMode(pat.mExtendMode, Axis::Y_AXIS);
SkFilterMode filterMode = pat.mSamplingFilter == SamplingFilter::POINT
? SkFilterMode::kNearest
: SkFilterMode::kLinear;
sk_sp<SkShader> shader =
image->makeShader(xTile, yTile, SkSamplingOptions(filterMode), mat);
if (shader) {
aPaint.setShader(shader);
} else {
gfxDebug() << "Failed creating Skia surface shader: x-tile="
<< (int)xTile << " y-tile=" << (int)yTile
<< " matrix=" << (mat.isFinite() ? "finite" : "non-finite");
aPaint.setColor(SK_ColorTRANSPARENT);
}
break;
}
}
}
static inline Rect GetClipBounds(SkCanvas* aCanvas) {
// Use a manually transformed getClipDeviceBounds instead of
// getClipBounds because getClipBounds inflates the the bounds
// by a pixel in each direction to compensate for antialiasing.
SkIRect deviceBounds;
if (!aCanvas->getDeviceClipBounds(&deviceBounds)) {
return Rect();
}
SkMatrix inverseCTM;
if (!aCanvas->getTotalMatrix().invert(&inverseCTM)) {
return Rect();
}
SkRect localBounds;
inverseCTM.mapRect(&localBounds, SkRect::Make(deviceBounds));
return SkRectToRect(localBounds);
}
struct AutoPaintSetup {
AutoPaintSetup(SkCanvas* aCanvas, const DrawOptions& aOptions,
const Pattern& aPattern, const Rect* aMaskBounds = nullptr,
const SkMatrix* aMatrix = nullptr,
const Rect* aSourceBounds = nullptr)
: mNeedsRestore(false), mAlpha(1.0) {
Init(aCanvas, aOptions, aMaskBounds, false);
SetPaintPattern(mPaint, aPattern, mLock, mAlpha, aMatrix, aSourceBounds);
}
AutoPaintSetup(SkCanvas* aCanvas, const DrawOptions& aOptions,
const Rect* aMaskBounds = nullptr, bool aForceGroup = false)
: mNeedsRestore(false), mAlpha(1.0) {
Init(aCanvas, aOptions, aMaskBounds, aForceGroup);
}
~AutoPaintSetup() {
if (mNeedsRestore) {
mCanvas->restore();
}
}
void Init(SkCanvas* aCanvas, const DrawOptions& aOptions,
const Rect* aMaskBounds, bool aForceGroup) {
mPaint.setBlendMode(GfxOpToSkiaOp(aOptions.mCompositionOp));
mCanvas = aCanvas;
// TODO: Can we set greyscale somehow?
if (aOptions.mAntialiasMode != AntialiasMode::NONE) {
mPaint.setAntiAlias(true);
} else {
mPaint.setAntiAlias(false);
}
bool needsGroup =
aForceGroup ||
(!IsOperatorBoundByMask(aOptions.mCompositionOp) &&
(!aMaskBounds || !aMaskBounds->Contains(GetClipBounds(aCanvas))));
// TODO: We could skip the temporary for operator_source and just
// clear the clip rect. The other operators would be harder
// but could be worth it to skip pushing a group.
if (needsGroup) {
mPaint.setBlendMode(SkBlendMode::kSrcOver);
SkPaint temp;
temp.setBlendMode(GfxOpToSkiaOp(aOptions.mCompositionOp));
temp.setAlpha(ColorFloatToByte(aOptions.mAlpha));
// TODO: Get a rect here
SkCanvas::SaveLayerRec rec(nullptr, &temp,
SkCanvas::kPreserveLCDText_SaveLayerFlag);
mCanvas->saveLayer(rec);
mNeedsRestore = true;
} else {
mPaint.setAlpha(ColorFloatToByte(aOptions.mAlpha));
mAlpha = aOptions.mAlpha;
}
}
// TODO: Maybe add an operator overload to access this easier?
SkPaint mPaint;
bool mNeedsRestore;
SkCanvas* mCanvas;
Maybe<MutexAutoLock> mLock;
Float mAlpha;
};
void DrawTargetSkia::Flush() { mCanvas->flush(); }
void DrawTargetSkia::DrawSurface(SourceSurface* aSurface, const Rect& aDest,
const Rect& aSource,
const DrawSurfaceOptions& aSurfOptions,
const DrawOptions& aOptions) {
if (aSource.IsEmpty()) {
return;
}
MarkChanged();
Maybe<MutexAutoLock> lock;
sk_sp<SkImage> image = GetSkImageForSurface(aSurface, &lock);
if (!image) {
return;
}
SkRect destRect = RectToSkRect(aDest);
SkRect sourceRect = RectToSkRect(aSource - aSurface->GetRect().TopLeft());
bool forceGroup =
image->isAlphaOnly() && aOptions.mCompositionOp != CompositionOp::OP_OVER;
AutoPaintSetup paint(mCanvas, aOptions, &aDest, forceGroup);
SkFilterMode filterMode =
aSurfOptions.mSamplingFilter == SamplingFilter::POINT
? SkFilterMode::kNearest
: SkFilterMode::kLinear;
mCanvas->drawImageRect(image, sourceRect, destRect,
SkSamplingOptions(filterMode), &paint.mPaint,
SkCanvas::kStrict_SrcRectConstraint);
}
DrawTargetType DrawTargetSkia::GetType() const {
return DrawTargetType::SOFTWARE_RASTER;
}
void DrawTargetSkia::DrawFilter(FilterNode* aNode, const Rect& aSourceRect,
const Point& aDestPoint,
const DrawOptions& aOptions) {
if (!aNode || aNode->GetBackendType() != FILTER_BACKEND_SOFTWARE) {
return;
}
FilterNodeSoftware* filter = static_cast<FilterNodeSoftware*>(aNode);
filter->Draw(this, aSourceRect, aDestPoint, aOptions);
}
void DrawTargetSkia::DrawSurfaceWithShadow(SourceSurface* aSurface,
const Point& aDest,
const ShadowOptions& aShadow,
CompositionOp aOperator) {
if (aSurface->GetSize().IsEmpty()) {
return;
}
MarkChanged();
Maybe<MutexAutoLock> lock;
sk_sp<SkImage> image = GetSkImageForSurface(aSurface, &lock);
if (!image) {
return;
}
mCanvas->save();
mCanvas->resetMatrix();
SkPaint paint;
paint.setBlendMode(GfxOpToSkiaOp(aOperator));
// bug 1201272
// We can't use the SkDropShadowImageFilter here because it applies the xfer
// mode first to render the bitmap to a temporary layer, and then implicitly
// uses src-over to composite the resulting shadow.
// The canvas spec, however, states that the composite op must be used to
// composite the resulting shadow, so we must instead use a SkBlurImageFilter
// to blur the image ourselves.
SkPaint shadowPaint;
shadowPaint.setBlendMode(GfxOpToSkiaOp(aOperator));
auto shadowDest = IntPoint::Round(aDest + aShadow.mOffset);
SkBitmap blurMask;
// Extract the alpha channel of the image into a bitmap. If the image is A8
// format already, then we can directly reuse the bitmap rather than create a
// new one as the surface only needs to be drawn from once.
if (ExtractAlphaBitmap(image, &blurMask, true)) {
// Prefer using our own box blur instead of Skia's. It currently performs
// much better than SkBlurImageFilter or SkBlurMaskFilter on the CPU.
AlphaBoxBlur blur(Rect(0, 0, blurMask.width(), blurMask.height()),
int32_t(blurMask.rowBytes()), aShadow.mSigma,
aShadow.mSigma);
blur.Blur(reinterpret_cast<uint8_t*>(blurMask.getPixels()));
blurMask.notifyPixelsChanged();
shadowPaint.setColor(ColorToSkColor(aShadow.mColor, 1.0f));
mCanvas->drawImage(blurMask.asImage(), shadowDest.x, shadowDest.y,
SkSamplingOptions(SkFilterMode::kLinear), &shadowPaint);
} else {
sk_sp<SkImageFilter> blurFilter(
SkImageFilters::Blur(aShadow.mSigma, aShadow.mSigma, nullptr));
sk_sp<SkColorFilter> colorFilter(SkColorFilters::Blend(
ColorToSkColor(aShadow.mColor, 1.0f), SkBlendMode::kSrcIn));
shadowPaint.setImageFilter(blurFilter);
shadowPaint.setColorFilter(colorFilter);
mCanvas->drawImage(image, shadowDest.x, shadowDest.y,
SkSamplingOptions(SkFilterMode::kLinear), &shadowPaint);
}
if (aSurface->GetFormat() != SurfaceFormat::A8) {
// Composite the original image after the shadow
auto dest = IntPoint::Round(aDest);
mCanvas->drawImage(image, dest.x, dest.y,
SkSamplingOptions(SkFilterMode::kLinear), &paint);
}
mCanvas->restore();
}
void DrawTargetSkia::FillRect(const Rect& aRect, const Pattern& aPattern,
const DrawOptions& aOptions) {
// The sprite blitting path in Skia can be faster than the shader blitter for
// operators other than source (or source-over with opaque surface). So, when
// possible/beneficial, route to DrawSurface which will use the sprite
// blitter.
if (aPattern.GetType() == PatternType::SURFACE &&
aOptions.mCompositionOp != CompositionOp::OP_SOURCE) {
const SurfacePattern& pat = static_cast<const SurfacePattern&>(aPattern);
// Verify there is a valid surface and a pattern matrix without skew.
if (pat.mSurface &&
(aOptions.mCompositionOp != CompositionOp::OP_OVER ||
GfxFormatToSkiaAlphaType(pat.mSurface->GetFormat()) !=
kOpaque_SkAlphaType) &&
!pat.mMatrix.HasNonAxisAlignedTransform()) {
// Bound the sampling to smaller of the bounds or the sampling rect.
IntRect srcRect(IntPoint(0, 0), pat.mSurface->GetSize());
if (!pat.mSamplingRect.IsEmpty()) {
srcRect = srcRect.Intersect(pat.mSamplingRect);
}
// Transform the destination rectangle by the inverse of the pattern
// matrix so that it is in pattern space like the source rectangle.
Rect patRect = aRect - pat.mMatrix.GetTranslation();
patRect.Scale(1.0f / pat.mMatrix._11, 1.0f / pat.mMatrix._22);
// Verify the pattern rectangle will not tile or clamp.
if (!patRect.IsEmpty() && srcRect.Contains(RoundedOut(patRect))) {
// The pattern is a surface with an axis-aligned source rectangle
// fitting entirely in its bounds, so just treat it as a DrawSurface.
DrawSurface(pat.mSurface, aRect, patRect,
DrawSurfaceOptions(pat.mSamplingFilter), aOptions);
return;
}
}
}
MarkChanged();
SkRect rect = RectToSkRect(aRect);
AutoPaintSetup paint(mCanvas, aOptions, aPattern, &aRect, nullptr, &aRect);
mCanvas->drawRect(rect, paint.mPaint);
}
void DrawTargetSkia::Stroke(const Path* aPath, const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
MarkChanged();
MOZ_ASSERT(aPath, "Null path");
if (aPath->GetBackendType() != BackendType::SKIA) {
return;
}
const PathSkia* skiaPath = static_cast<const PathSkia*>(aPath);
AutoPaintSetup paint(mCanvas, aOptions, aPattern);
if (!StrokeOptionsToPaint(paint.mPaint, aStrokeOptions)) {
return;
}
if (!skiaPath->GetPath().isFinite()) {
return;
}
mCanvas->drawPath(skiaPath->GetPath(), paint.mPaint);
}
static Double DashPeriodLength(const StrokeOptions& aStrokeOptions) {
Double length = 0;
for (size_t i = 0; i < aStrokeOptions.mDashLength; i++) {
length += aStrokeOptions.mDashPattern[i];
}
if (aStrokeOptions.mDashLength & 1) {
// "If an odd number of values is provided, then the list of values is
// repeated to yield an even number of values."
// Double the length.
length += length;
}
return length;
}
static inline Double RoundDownToMultiple(Double aValue, Double aFactor) {
return floor(aValue / aFactor) * aFactor;
}
static Rect UserSpaceStrokeClip(const IntRect& aDeviceClip,
const Matrix& aTransform,
const StrokeOptions& aStrokeOptions) {
Matrix inverse = aTransform;
if (!inverse.Invert()) {
return Rect();
}
Rect deviceClip(aDeviceClip);
deviceClip.Inflate(MaxStrokeExtents(aStrokeOptions, aTransform));
return inverse.TransformBounds(deviceClip);
}
static Rect ShrinkClippedStrokedRect(const Rect& aStrokedRect,
const IntRect& aDeviceClip,
const Matrix& aTransform,
const StrokeOptions& aStrokeOptions) {
Rect userSpaceStrokeClip =
UserSpaceStrokeClip(aDeviceClip, aTransform, aStrokeOptions);
RectDouble strokedRectDouble(aStrokedRect.X(), aStrokedRect.Y(),
aStrokedRect.Width(), aStrokedRect.Height());
RectDouble intersection = strokedRectDouble.Intersect(
RectDouble(userSpaceStrokeClip.X(), userSpaceStrokeClip.Y(),
userSpaceStrokeClip.Width(), userSpaceStrokeClip.Height()));
Double dashPeriodLength = DashPeriodLength(aStrokeOptions);
if (intersection.IsEmpty() || dashPeriodLength == 0.0f) {
return Rect(intersection.X(), intersection.Y(), intersection.Width(),
intersection.Height());
}
// Reduce the rectangle side lengths in multiples of the dash period length
// so that the visible dashes stay in the same place.
MarginDouble insetBy = strokedRectDouble - intersection;
insetBy.top = RoundDownToMultiple(insetBy.top, dashPeriodLength);
insetBy.right = RoundDownToMultiple(insetBy.right, dashPeriodLength);
insetBy.bottom = RoundDownToMultiple(insetBy.bottom, dashPeriodLength);
insetBy.left = RoundDownToMultiple(insetBy.left, dashPeriodLength);
strokedRectDouble.Deflate(insetBy);
return Rect(strokedRectDouble.X(), strokedRectDouble.Y(),
strokedRectDouble.Width(), strokedRectDouble.Height());
}
void DrawTargetSkia::StrokeRect(const Rect& aRect, const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
// Stroking large rectangles with dashes is expensive with Skia (fixed
// overhead based on the number of dashes, regardless of whether the dashes
// are visible), so we try to reduce the size of the stroked rectangle as
// much as possible before passing it on to Skia.
Rect rect = aRect;
if (aStrokeOptions.mDashLength > 0 && !rect.IsEmpty()) {
IntRect deviceClip(IntPoint(0, 0), mSize);
SkIRect clipBounds;
if (mCanvas->getDeviceClipBounds(&clipBounds)) {
deviceClip = SkIRectToIntRect(clipBounds);
}
rect =
ShrinkClippedStrokedRect(rect, deviceClip, mTransform, aStrokeOptions);
if (rect.IsEmpty()) {
return;
}
}
MarkChanged();
AutoPaintSetup paint(mCanvas, aOptions, aPattern);
if (!StrokeOptionsToPaint(paint.mPaint, aStrokeOptions)) {
return;
}
mCanvas->drawRect(RectToSkRect(rect), paint.mPaint);
}
void DrawTargetSkia::StrokeLine(const Point& aStart, const Point& aEnd,
const Pattern& aPattern,
const StrokeOptions& aStrokeOptions,
const DrawOptions& aOptions) {
MarkChanged();
AutoPaintSetup paint(mCanvas, aOptions, aPattern);
if (!StrokeOptionsToPaint(paint.mPaint, aStrokeOptions)) {
return;