File: GraphicsContextSkia.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (1144 lines) | stat: -rw-r--r-- 41,010 bytes parent folder | download | duplicates (6)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
/*
 * Copyright (C) 2024 Igalia S.L.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "GraphicsContextSkia.h"

#if USE(SKIA)
#include "AffineTransform.h"
#include "DecomposedGlyphs.h"
#include "FloatRect.h"
#include "FloatRoundedRect.h"
#include "FontRenderOptions.h"
#include "GLContext.h"
#include "ImageBuffer.h"
#include "IntRect.h"
#include "NotImplemented.h"
#include "PlatformDisplay.h"
#include "ProcessCapabilities.h"
#include "SkiaPaintingEngine.h"
#include <cmath>
WTF_IGNORE_WARNINGS_IN_THIRD_PARTY_CODE_BEGIN
#include <skia/core/SkColorFilter.h>
#include <skia/core/SkImage.h>
#include <skia/core/SkPath.h>
#include <skia/core/SkPathEffect.h>
#include <skia/core/SkPathTypes.h>
#include <skia/core/SkPictureRecorder.h>
#include <skia/core/SkPoint3.h>
#include <skia/core/SkRRect.h>
#include <skia/core/SkRegion.h>
#include <skia/core/SkSurface.h>
#include <skia/core/SkTileMode.h>
#include <skia/effects/SkImageFilters.h>
#include <skia/gpu/ganesh/GrBackendSurface.h>
#include <skia/gpu/ganesh/SkSurfaceGanesh.h>
WTF_IGNORE_WARNINGS_IN_THIRD_PARTY_CODE_END
#include <wtf/MathExtras.h>

#if USE(THEME_ADWAITA)
#include "Adwaita.h"
#endif

namespace WebCore {

GraphicsContextSkia::GraphicsContextSkia(SkCanvas& canvas, RenderingMode renderingMode, RenderingPurpose renderingPurpose, CompletionHandler<void()>&& destroyNotify)
    : m_canvas(canvas)
    , m_renderingMode(renderingMode)
    , m_renderingPurpose(renderingPurpose)
    , m_destroyNotify(WTFMove(destroyNotify))
    , m_colorSpace(canvas.imageInfo().colorSpace() ? DestinationColorSpace(canvas.imageInfo().refColorSpace()) : DestinationColorSpace::SRGB())
{
}

GraphicsContextSkia::~GraphicsContextSkia()
{
    if (m_destroyNotify)
        m_destroyNotify();
}

bool GraphicsContextSkia::hasPlatformContext() const
{
    return true;
}

AffineTransform GraphicsContextSkia::getCTM(IncludeDeviceScale includeScale) const
{
    UNUSED_PARAM(includeScale);
    return m_canvas.getTotalMatrix();
}

SkCanvas* GraphicsContextSkia::platformContext() const
{
    return &m_canvas;
}

const DestinationColorSpace& GraphicsContextSkia::colorSpace() const
{
    return m_colorSpace;
}

bool GraphicsContextSkia::makeGLContextCurrentIfNeeded() const
{
    if (m_renderingMode == RenderingMode::Unaccelerated || m_renderingPurpose != RenderingPurpose::Canvas)
        return true;

    return PlatformDisplay::sharedDisplay().skiaGLContext()->makeContextCurrent();
}

void GraphicsContextSkia::save(GraphicsContextState::Purpose purpose)
{
    GraphicsContext::save(purpose);
    m_skiaStateStack.append(m_skiaState);
    m_canvas.save();
}

void GraphicsContextSkia::restore(GraphicsContextState::Purpose purpose)
{
    if (!stackSize())
        return;

    GraphicsContext::restore(purpose);

    if (!m_skiaStateStack.isEmpty()) {
        m_skiaState = m_skiaStateStack.takeLast();
        if (m_skiaStateStack.isEmpty())
            m_skiaStateStack.clear();
    }

    m_canvas.restore();
}

// Draws a filled rectangle with a stroked border.
void GraphicsContextSkia::drawRect(const FloatRect& rect, float borderThickness)
{
    ASSERT(!rect.isEmpty());
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    setupFillSource(paint);
    m_canvas.drawRect(rect, paint);
    if (strokeStyle() == StrokeStyle::NoStroke)
        return;

    SkIRect rects[4] = {
        SkIRect::MakeXYWH(rect.x(), rect.y(), rect.width(), borderThickness),
        SkIRect::MakeXYWH(rect.x(), rect.maxY() - borderThickness, rect.width(), borderThickness),
        SkIRect::MakeXYWH(rect.x(), rect.y() + borderThickness, borderThickness, rect.height() - 2 * borderThickness),
        SkIRect::MakeXYWH(rect.maxX() - borderThickness, rect.y() + borderThickness, borderThickness, rect.height() - 2 * borderThickness)
    };

    SkRegion region;
    region.setRects(rects, 4);
    SkPaint strokePaint = createStrokePaint();
    setupStrokeSource(strokePaint);
    m_canvas.drawRegion(region, strokePaint);
}

static SkBlendMode toSkiaBlendMode(CompositeOperator operation, BlendMode blendMode)
{
    switch (blendMode) {
    case BlendMode::Normal:
        switch (operation) {
        case CompositeOperator::Clear:
            return SkBlendMode::kClear;
        case CompositeOperator::Copy:
            return SkBlendMode::kSrc;
        case CompositeOperator::SourceOver:
            return SkBlendMode::kSrcOver;
        case CompositeOperator::SourceIn:
            return SkBlendMode::kSrcIn;
        case CompositeOperator::SourceOut:
            return SkBlendMode::kSrcOut;
        case CompositeOperator::SourceAtop:
            return SkBlendMode::kSrcATop;
        case CompositeOperator::DestinationOver:
            return SkBlendMode::kDstOver;
        case CompositeOperator::DestinationIn:
            return SkBlendMode::kDstIn;
        case CompositeOperator::DestinationOut:
            return SkBlendMode::kDstOut;
        case CompositeOperator::DestinationAtop:
            return SkBlendMode::kDstATop;
        case CompositeOperator::XOR:
            return SkBlendMode::kXor;
        case CompositeOperator::PlusLighter:
            return SkBlendMode::kPlus;
        case CompositeOperator::PlusDarker:
            notImplemented();
            return SkBlendMode::kSrcOver;
        case CompositeOperator::Difference:
            return SkBlendMode::kDifference;
        }
        break;
    case BlendMode::Multiply:
        return SkBlendMode::kMultiply;
    case BlendMode::Screen:
        return SkBlendMode::kScreen;
    case BlendMode::Overlay:
        return SkBlendMode::kOverlay;
    case BlendMode::Darken:
        return SkBlendMode::kDarken;
    case BlendMode::Lighten:
        return SkBlendMode::kLighten;
    case BlendMode::ColorDodge:
        return SkBlendMode::kColorDodge;
    case BlendMode::ColorBurn:
        return SkBlendMode::kColorBurn;
    case BlendMode::HardLight:
        return SkBlendMode::kHardLight;
    case BlendMode::SoftLight:
        return SkBlendMode::kSoftLight;
    case BlendMode::Difference:
        return SkBlendMode::kDifference;
    case BlendMode::Exclusion:
        return SkBlendMode::kExclusion;
    case BlendMode::Hue:
        return SkBlendMode::kHue;
    case BlendMode::Saturation:
        return SkBlendMode::kSaturation;
    case BlendMode::Color:
        return SkBlendMode::kColor;
    case BlendMode::Luminosity:
        return SkBlendMode::kLuminosity;
    case BlendMode::PlusLighter:
        return SkBlendMode::kPlus;
    case BlendMode::PlusDarker:
        notImplemented();
        break;
    }

    return SkBlendMode::kSrcOver;
}

static SkSamplingOptions toSkSamplingOptions(InterpolationQuality quality)
{
    switch (quality) {
    case InterpolationQuality::DoNotInterpolate:
        return SkSamplingOptions(SkFilterMode::kNearest, SkMipmapMode::kNone);
    case InterpolationQuality::Low:
        return SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNone);
    case InterpolationQuality::Medium:
    case InterpolationQuality::Default:
        return SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNearest);
    case InterpolationQuality::High:
        return SkSamplingOptions(SkCubicResampler::CatmullRom());
    }

    return SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kNearest);
}

void GraphicsContextSkia::drawNativeImageInternal(NativeImage& nativeImage, const FloatRect& destRect, const FloatRect& srcRect, ImagePaintingOptions options)
{
    auto image = nativeImage.platformImage();
    if (!image)
        return;

    auto imageSize = nativeImage.size();
    if (options.orientation().usesWidthAsHeight())
        imageSize = imageSize.transposedSize();
    auto imageRect = FloatRect { { }, imageSize };
    auto normalizedSrcRect = normalizeRect(srcRect);
    if (!imageRect.intersects(normalizedSrcRect))
        return;

    if (options.orientation().usesWidthAsHeight())
        normalizedSrcRect = normalizedSrcRect.transposedRect();

    if (!makeGLContextCurrentIfNeeded())
        return;

    auto normalizedDestRect = normalizeRect(destRect);
    if (options.orientation() != ImageOrientation::Orientation::None) {
        m_canvas.save();

        // ImageOrientation expects the origin to be at (0, 0).
        m_canvas.translate(normalizedDestRect.x(), normalizedDestRect.y());
        normalizedDestRect.setLocation(FloatPoint());
        m_canvas.concat(options.orientation().transformFromDefault(normalizedDestRect.size()));

        if (options.orientation().usesWidthAsHeight()) {
            // The destination rectangle will have its width and height already reversed for the orientation of
            // the image, as it was needed for page layout, so we need to reverse it back here.
            normalizedDestRect.setSize(normalizedDestRect.size().transposedSize());
        }
    }

    SkPaint paint = createFillPaint();
    paint.setAlphaf(alpha());
    paint.setBlendMode(toSkiaBlendMode(options.compositeOperator(), options.blendMode()));
    bool inExtraTransparencyLayer = false;
    auto clampingConstraint = options.strictImageClamping() == StrictImageClamping::Yes ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint;

    SkImage* useImage = image.get();

    sk_sp<SkImage> rasterImage;
    if (hasDropShadow()) {
        if (image->isTextureBacked()) {
            if (renderingMode() == RenderingMode::Unaccelerated) {
                // When drawing GPU-backed image on CPU-backed canvas with filter, we need to convert image to CPU-backed one.
                rasterImage = image->makeRasterImage();
                useImage = rasterImage.get();
            } else
                trackAcceleratedRenderingFenceIfNeeded(image);
        }
        inExtraTransparencyLayer = drawOutsetShadow(paint, [&](const SkPaint& paint) {
            m_canvas.drawImageRect(useImage, normalizedSrcRect, normalizedDestRect, toSkSamplingOptions(m_state.imageInterpolationQuality()), &paint, clampingConstraint);
        });
    } else
        trackAcceleratedRenderingFenceIfNeeded(image);

    m_canvas.drawImageRect(useImage, normalizedSrcRect, normalizedDestRect, toSkSamplingOptions(m_state.imageInterpolationQuality()), &paint, clampingConstraint);
    if (inExtraTransparencyLayer)
        endTransparencyLayer();

    if (options.orientation() != ImageOrientation::Orientation::None)
        m_canvas.restore();
}

// This is only used to draw borders, so we should not draw shadows.
void GraphicsContextSkia::drawLine(const FloatPoint& point1, const FloatPoint& point2)
{
    if (strokeStyle() == StrokeStyle::NoStroke)
        return;

    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createStrokePaint();
    paint.setColor(SkColor(strokeColor().colorWithAlphaMultipliedBy(alpha())));

    const bool isVertical = (point1.x() + strokeThickness() == point2.x());
    float strokeWidth = isVertical ? point2.y() - point1.y() : point2.x() - point1.x();
    if (!strokeThickness() || !strokeWidth)
        return;

    float cornerWidth = 0;

    if (strokeStyle() == StrokeStyle::DottedStroke || strokeStyle() == StrokeStyle::DashedStroke) {
        // Figure out end points to ensure we always paint corners.
        cornerWidth = dashedLineCornerWidthForStrokeWidth(strokeWidth);
        if (isVertical) {
            fillRect(FloatRect(point1.x(), point1.y(), strokeThickness(), cornerWidth), strokeColor());
            fillRect(FloatRect(point1.x(), point2.y() - cornerWidth, strokeThickness(), cornerWidth), strokeColor());
        } else {
            fillRect(FloatRect(point1.x(), point1.y(), cornerWidth, strokeThickness()), strokeColor());
            fillRect(FloatRect(point2.x() - cornerWidth, point1.y(), cornerWidth, strokeThickness()), strokeColor());
        }
        strokeWidth -= 2 * cornerWidth;
        const float patternWidth = dashedLinePatternWidthForStrokeWidth(strokeWidth);
        // Check if corner drawing sufficiently covers the line.
        if (strokeWidth <= patternWidth + 1)
            return;

        const SkScalar dashIntervals[] = { SkFloatToScalar(patternWidth), SkFloatToScalar(patternWidth) };
        const float patternOffset = dashedLinePatternOffsetForPatternAndStrokeWidth(patternWidth, strokeWidth);
        paint.setPathEffect(SkDashPathEffect::Make(dashIntervals, 2, patternOffset));
    }

    const auto centeredPoints = centerLineAndCutOffCorners(isVertical, cornerWidth, point1, point2);
    const auto& centeredPoint1 = centeredPoints[0];
    const auto& centeredPoint2 = centeredPoints[1];

    m_canvas.drawLine(SkFloatToScalar(centeredPoint1.x()), SkFloatToScalar(centeredPoint1.y()), SkFloatToScalar(centeredPoint2.x()), SkFloatToScalar(centeredPoint2.y()), paint);
}

// This method is only used to draw the little circles used in lists.
void GraphicsContextSkia::drawEllipse(const FloatRect& boundaries)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    setupFillSource(paint);
    m_canvas.drawOval(boundaries, paint);
}

static inline SkPathFillType toSkiaFillType(const WindRule& windRule)
{
    switch (windRule) {
    case WindRule::EvenOdd:
        return SkPathFillType::kEvenOdd;
    case WindRule::NonZero:
        return SkPathFillType::kWinding;
    }

    return SkPathFillType::kWinding;
}

void GraphicsContextSkia::drawSkiaPath(const SkPath& path, SkPaint& paint)
{
    bool inExtraTransparencyLayer = false;
    if (hasDropShadow()) {
        inExtraTransparencyLayer = drawOutsetShadow(paint, [&](const SkPaint& paint) {
            m_canvas.drawPath(path, paint);
        });
    }
    m_canvas.drawPath(path, paint);
    if (inExtraTransparencyLayer)
        endTransparencyLayer();
}

void GraphicsContextSkia::fillPath(const Path& path)
{
    if (path.isEmpty())
        return;

    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    setupFillSource(paint);

    auto fillRule = toSkiaFillType(state().fillRule());
    auto& skiaPath= *path.platformPath();
    if (skiaPath.getFillType() == fillRule) {
        drawSkiaPath(skiaPath, paint);
        return;
    }

    auto skiaPathCopy = skiaPath;
    skiaPathCopy.setFillType(fillRule);
    drawSkiaPath(skiaPathCopy, paint);
}

void GraphicsContextSkia::strokePath(const Path& path)
{
    if (path.isEmpty())
        return;

    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint strokePaint = createStrokePaint();
    setupStrokeSource(strokePaint);
    drawSkiaPath(*path.platformPath(), strokePaint);
}

sk_sp<SkImageFilter> GraphicsContextSkia::createDropShadowFilterIfNeeded(ShadowStyle shadowStyle) const
{
    if (!hasDropShadow())
        return nullptr;

    const auto& shadow = dropShadow();
    ASSERT(shadow);

    auto offset = shadow->offset;
    const auto& shadowColor = shadow->color;

    if (!shadowColor.isVisible() || (!offset.width() && !offset.height() && !shadow->radius))
        return nullptr;

    const auto& state = this->state();
    auto sigma = shadow->radius / 2.0;

    if (shadowStyle == ShadowStyle::Inset) {
        auto dropShadow = SkImageFilters::DropShadowOnly(offset.width(), offset.height(), sigma, sigma, SK_ColorBLACK, nullptr);
        return SkImageFilters::ColorFilter(SkColorFilters::Blend(shadowColor, SkBlendMode::kSrcIn), dropShadow);
    }

    RELEASE_ASSERT(shadowStyle == ShadowStyle::Outset);

    if (!state.shadowsIgnoreTransforms())
        return SkImageFilters::DropShadowOnly(offset.width(), offset.height(), sigma, sigma, shadowColor, nullptr);

    // Fast path: identity CTM doesn't need the transform compensation
    AffineTransform ctm = getCTM(GraphicsContext::IncludeDeviceScale::PossiblyIncludeDeviceScale);
    if (ctm.isIdentity())
        return SkImageFilters::DropShadowOnly(offset.width(), offset.height(), sigma, sigma, shadowColor, nullptr);

    // Ignoring the CTM is practically equal as applying the inverse of
    // the CTM when post-processing the drop shadow.
    if (const std::optional<SkMatrix>& inverse = ctm.inverse()) {
        SkPoint3 p = SkPoint3::Make(offset.width(), offset.height(), 0);
        inverse->mapHomogeneousPoints(&p, &p, 1);
        sigma = inverse->mapRadius(sigma);
        return SkImageFilters::DropShadowOnly(p.x(), p.y(), sigma, sigma, shadowColor, nullptr);
    }

    return nullptr;
}

bool GraphicsContextSkia::drawOutsetShadow(SkPaint& paint, Function<void(const SkPaint&)>&& drawFunction)
{
    auto shadow = createDropShadowFilterIfNeeded(ShadowStyle::Outset);
    if (!shadow)
        return false;

    paint.setImageFilter(shadow);
    drawFunction(paint);
    paint.setImageFilter(nullptr);
    if (!m_layerStateStack.isEmpty()) {
        if (auto compositeMode = m_layerStateStack.last().compositeMode) {
            beginTransparencyLayer(compositeMode->operation, compositeMode->blendMode);
            return true;
        }
    }
    return false;
}

SkPaint GraphicsContextSkia::createFillPaint() const
{
    SkPaint paint;
    paint.setAntiAlias(shouldAntialias());
    paint.setStyle(SkPaint::kFill_Style);
    paint.setBlendMode(toSkiaBlendMode(compositeMode().operation, blendMode()));

    return paint;
}

void GraphicsContextSkia::setupFillSource(SkPaint& paint)
{
    if (auto fillPattern = fillBrush().pattern()) {
        paint.setShader(fillPattern->createPlatformPattern({ }, toSkSamplingOptions(imageInterpolationQuality())));
        paint.setAlphaf(alpha());
        trackAcceleratedRenderingFenceIfNeeded(paint);
    } else if (auto fillGradient = fillBrush().gradient())
        paint.setShader(fillGradient->shader(alpha(), fillBrush().gradientSpaceTransform()));
    else
        paint.setColor(SkColor(fillColor().colorWithAlphaMultipliedBy(alpha())));
}

SkPaint GraphicsContextSkia::createStrokePaint() const
{
    SkPaint paint;
    paint.setAntiAlias(shouldAntialias());
    paint.setStyle(SkPaint::kStroke_Style);
    paint.setBlendMode(toSkiaBlendMode(compositeMode().operation, blendMode()));
    paint.setStrokeCap(m_skiaState.m_stroke.cap);
    paint.setStrokeJoin(m_skiaState.m_stroke.join);
    paint.setStrokeMiter(m_skiaState.m_stroke.miter);
    paint.setStrokeWidth(SkFloatToScalar(strokeThickness()));
    paint.setPathEffect(m_skiaState.m_stroke.dash);
    return paint;
}

void GraphicsContextSkia::setupStrokeSource(SkPaint& paint)
{
    if (auto strokePattern = strokeBrush().pattern()) {
        paint.setShader(strokePattern->createPlatformPattern({ }, toSkSamplingOptions(imageInterpolationQuality())));
        trackAcceleratedRenderingFenceIfNeeded(paint);
    } else if (auto strokeGradient = strokeBrush().gradient())
        paint.setShader(strokeGradient->shader(alpha(), strokeBrush().gradientSpaceTransform()));
    else
        paint.setColor(SkColor(strokeBrush().color().colorWithAlphaMultipliedBy(alpha())));
}

void GraphicsContextSkia::drawSkiaRect(const SkRect& boundaries, SkPaint& paint)
{
    bool inExtraTransparencyLayer = false;
    if (hasDropShadow()) {
        inExtraTransparencyLayer = drawOutsetShadow(paint, [&](const SkPaint& paint) {
            m_canvas.drawRect(boundaries, paint);
        });
    }
    m_canvas.drawRect(boundaries, paint);
    if (inExtraTransparencyLayer)
        endTransparencyLayer();
}

void GraphicsContextSkia::fillRect(const FloatRect& boundaries, RequiresClipToRect)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    setupFillSource(paint);
    drawSkiaRect(boundaries, paint);
}

void GraphicsContextSkia::fillRect(const FloatRect& boundaries, const Color& fillColor)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    paint.setColor(SkColor(fillColor));
    drawSkiaRect(boundaries, paint);
}

void GraphicsContextSkia::fillRect(const FloatRect& boundaries, Gradient& gradient, const AffineTransform& gradientSpaceTransform, RequiresClipToRect)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    paint.setShader(gradient.shader(alpha(), gradientSpaceTransform));
    drawSkiaRect(boundaries, paint);
}

void GraphicsContextSkia::resetClip()
{
    notImplemented();
}

void GraphicsContextSkia::clip(const FloatRect& rect)
{
    m_canvas.clipRect(rect, SkClipOp::kIntersect, false);
}

void GraphicsContextSkia::clipPath(const Path& path, WindRule clipRule)
{
    auto fillRule = toSkiaFillType(clipRule);
    auto& skiaPath = *path.platformPath();
    if (skiaPath.getFillType() == fillRule) {
        m_canvas.clipPath(skiaPath, true);
        return;
    }

    auto skiaPathCopy = skiaPath;
    skiaPathCopy.setFillType(fillRule);
    m_canvas.clipPath(skiaPathCopy, true);
}

IntRect GraphicsContextSkia::clipBounds() const
{
    return enclosingIntRect(m_canvas.getLocalClipBounds());
}

void GraphicsContextSkia::clipToImageBuffer(ImageBuffer& buffer, const FloatRect& destRect)
{
    if (auto nativeImage = nativeImageForDrawing(buffer)) {
        auto image = nativeImage->platformImage();
        trackAcceleratedRenderingFenceIfNeeded(image);
        m_canvas.clipShader(image->makeShader(SkTileMode::kDecal, SkTileMode::kDecal, { }, SkMatrix::Translate(SkFloatToScalar(destRect.x()), SkFloatToScalar(destRect.y()))));
    }
}

void GraphicsContextSkia::drawFocusRing(const Path& path, float, const Color& color)
{
#if USE(THEME_ADWAITA)
    Adwaita::paintFocus(*this, path, color);
#else
    notImplemented();
    UNUSED_PARAM(path);
    UNUSED_PARAM(color);
#endif
}

void GraphicsContextSkia::drawFocusRing(const Vector<FloatRect>& rects, float, float, const Color& color)
{
#if USE(THEME_ADWAITA)
    Adwaita::paintFocus(*this, rects, color);
#else
    notImplemented();
    UNUSED_PARAM(rects);
    UNUSED_PARAM(color);
#endif
}

void GraphicsContextSkia::drawLinesForText(const FloatPoint& point, float thickness, std::span<const FloatSegment> lineSegments, bool printing, bool doubleUnderlines, StrokeStyle strokeStyle)
{
    auto [rects, strokeColor] = computeRectsAndStrokeColorForLinesForText(point, thickness, lineSegments, printing, doubleUnderlines, strokeStyle);
    if (rects.isEmpty())
        return;
    for (auto& rect : rects)
        fillRect(rect, strokeColor);
}

// Creates a path comprising of two triangle waves separated by some empty space in Y axis.
// The empty space can be filled using SkPaint::kFill_Style thus forming an elegant triangle wave.
// Such triangle wave can be used e.g. as an error underline for text.
static SkPath createErrorUnderlinePath(const FloatRect& boundaries)
{
    const double y = boundaries.y();
    double width = boundaries.width();
    const double height = boundaries.height();
    static const double heightSquares = 2.5;

    const double square = height / heightSquares;
    const double halfSquare = 0.5 * square;

    const double unitWidth = (heightSquares - 1.0) * square;
    const int widthUnits = static_cast<int>((width + 0.5 * unitWidth) / unitWidth);

    double x = boundaries.x() + 0.5 * (width - widthUnits * unitWidth);
    width = widthUnits * unitWidth;

    const double bottom = y + height;
    const double top = y;

    SkPath path;

    // Bottom triangle wave, left to right.
    path.moveTo(SkDoubleToScalar(x - halfSquare), SkDoubleToScalar(top + halfSquare));

    int i = 0;
    for (i = 0; i < widthUnits; i += 2) {
        const double middle = x + (i + 1) * unitWidth;
        const double right = x + (i + 2) * unitWidth;

        path.lineTo(SkDoubleToScalar(middle), SkDoubleToScalar(bottom));

        if (i + 2 == widthUnits)
            path.lineTo(SkDoubleToScalar(right + halfSquare), SkDoubleToScalar(top + halfSquare));
        else if (i + 1 != widthUnits)
            path.lineTo(SkDoubleToScalar(right), SkDoubleToScalar(top + square));
    }

    // Top triangle wave, right to left.
    for (i -= 2; i >= 0; i -= 2) {
        const double left = x + i * unitWidth;
        const double middle = x + (i + 1) * unitWidth;
        const double right = x + (i + 2) * unitWidth;

        if (i + 1 == widthUnits)
            path.lineTo(SkDoubleToScalar(middle + halfSquare), SkDoubleToScalar(bottom - halfSquare));
        else {
            if (i + 2 == widthUnits)
                path.lineTo(SkDoubleToScalar(right), SkDoubleToScalar(top));

            path.lineTo(SkDoubleToScalar(middle), SkDoubleToScalar(bottom - halfSquare));
        }

        path.lineTo(SkDoubleToScalar(left), SkDoubleToScalar(top));
    }

    return path;
}

void GraphicsContextSkia::drawDotsForDocumentMarker(const FloatRect& boundaries, DocumentMarkerLineStyle style)
{
    if (style.mode != DocumentMarkerLineStyleMode::Spelling
        && style.mode != DocumentMarkerLineStyleMode::Grammar)
        return;

    SkPaint paint = createFillPaint();
    paint.setColor(SkColor(style.color));
    m_canvas.drawPath(createErrorUnderlinePath(boundaries), paint);
}

void GraphicsContextSkia::translate(float x, float y)
{
    m_canvas.translate(SkFloatToScalar(x), SkFloatToScalar(y));
}

void GraphicsContextSkia::didUpdateState(GraphicsContextState& state)
{
    // FIXME: Handle stroke changes.
    state.didApplyChanges();
}

void GraphicsContextSkia::concatCTM(const AffineTransform& ctm)
{
    m_canvas.concat(ctm);
}

void GraphicsContextSkia::setCTM(const AffineTransform& ctm)
{
    m_canvas.setMatrix(ctm);
}

void GraphicsContextSkia::beginTransparencyLayer(float opacity)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    GraphicsContext::beginTransparencyLayer(opacity);
    m_layerStateStack.append({ });

    SkPaint paint;
    paint.setAlphaf(opacity);
    paint.setBlendMode(toSkiaBlendMode(m_state.compositeMode().operation, m_state.compositeMode().blendMode));
    m_canvas.saveLayer(nullptr, &paint);
}

void GraphicsContextSkia::beginTransparencyLayer(CompositeOperator operation, BlendMode blendMode)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    GraphicsContext::beginTransparencyLayer(operation, blendMode);
    m_layerStateStack.append({ CompositeMode(operation, blendMode) });

    SkPaint paint;
    paint.setBlendMode(toSkiaBlendMode(operation, blendMode));
    m_canvas.saveLayer(nullptr, &paint);
    // When on transparency layer, we don't want to blend operations as when layer ends, we blend it as a whole.
    setCompositeMode({ CompositeOperator::SourceOver, BlendMode::Normal });
}

void GraphicsContextSkia::endTransparencyLayer()
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    GraphicsContext::endTransparencyLayer();
    m_canvas.restore();
    if (!m_layerStateStack.isEmpty()) {
        auto layerState = m_layerStateStack.takeLast();
        if (layerState.compositeMode)
            setCompositeMode(*layerState.compositeMode);
    }
}

void GraphicsContextSkia::clearRect(const FloatRect& rect)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    auto paint = createFillPaint();
    paint.setBlendMode(SkBlendMode::kClear);
    m_canvas.drawRect(rect, paint);
}

void GraphicsContextSkia::strokeRect(const FloatRect& boundaries, float lineWidth)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    auto strokePaint = createStrokePaint();
    strokePaint.setStrokeWidth(SkFloatToScalar(lineWidth));
    setupStrokeSource(strokePaint);
    drawSkiaRect(boundaries, strokePaint);
}

void GraphicsContextSkia::setLineCap(LineCap lineCap)
{
    auto toSkiaCap = [](const LineCap& lineCap) -> SkPaint::Cap {
        switch (lineCap) {
        case LineCap::Butt:
            return SkPaint::Cap::kButt_Cap;
        case LineCap::Round:
            return SkPaint::Cap::kRound_Cap;
        case LineCap::Square:
            return SkPaint::Cap::kSquare_Cap;
        }

        return SkPaint::Cap::kDefault_Cap;
    };

    m_skiaState.m_stroke.cap = toSkiaCap(lineCap);
}

static bool isValidDashArray(const DashArray& dashArray)
{
    // See 'dom-context-2d-setlinedash': if the array contains not finite or negative values, return.
    DashArray::value_type total = 0;
    for (const auto& dash : dashArray) {
        if (dash < 0 || !std::isfinite(dash))
            return false;
        total += dash;
    }
    // Nothing to be done for all-zero or empty arrays.
    return total > 0;
}

void GraphicsContextSkia::setLineDash(const DashArray& dashArray, float dashOffset)
{
    if (!isValidDashArray(dashArray)) {
        m_skiaState.m_stroke.dash = nullptr;
        return;
    }

    if (dashArray.size() % 2 == 1) {
        // Repeat the array to ensure even number of dash array elements, see e.g. 'stroke-dasharray' spec.
        DashArray repeatedDashArray(dashArray);
        repeatedDashArray.appendVector(dashArray);
        m_skiaState.m_stroke.dash = SkDashPathEffect::Make(repeatedDashArray.data(), repeatedDashArray.size(), dashOffset);
    } else
        m_skiaState.m_stroke.dash = SkDashPathEffect::Make(dashArray.data(), dashArray.size(), dashOffset);
}

void GraphicsContextSkia::setLineJoin(LineJoin lineJoin)
{
    auto toSkiaJoin = [](const LineJoin& lineJoin) -> SkPaint::Join {
        switch (lineJoin) {
        case LineJoin::Miter:
            return SkPaint::Join::kMiter_Join;
        case LineJoin::Round:
            return SkPaint::Join::kRound_Join;
        case LineJoin::Bevel:
            return SkPaint::Join::kBevel_Join;
        }

        return SkPaint::Join::kDefault_Join;
    };

    m_skiaState.m_stroke.join = toSkiaJoin(lineJoin);
}

void GraphicsContextSkia::setMiterLimit(float miter)
{
    m_skiaState.m_stroke.miter = SkFloatToScalar(miter);
}

void GraphicsContextSkia::clipOut(const Path& path)
{
    auto& skiaPath = *path.platformPath();
    skiaPath.toggleInverseFillType();
    m_canvas.clipPath(skiaPath, true);
    skiaPath.toggleInverseFillType();
}

void GraphicsContextSkia::rotate(float radians)
{
    m_canvas.rotate(SkFloatToScalar(rad2deg(radians)));
}

void GraphicsContextSkia::scale(const FloatSize& scale)
{
    m_canvas.scale(SkFloatToScalar(scale.width()), SkFloatToScalar(scale.height()));
}

void GraphicsContextSkia::clipOut(const FloatRect& rect)
{
    m_canvas.clipRect(rect, SkClipOp::kDifference, false);
}

void GraphicsContextSkia::fillRoundedRectImpl(const FloatRoundedRect& rect, const Color& color)
{
    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    paint.setColor(SkColor(color));
    bool inExtraTransparencyLayer = false;
    if (hasDropShadow()) {
        inExtraTransparencyLayer = drawOutsetShadow(paint, [&](const SkPaint& paint) {
            m_canvas.drawRRect(rect, paint);
        });
    }
    m_canvas.drawRRect(rect, paint);
    if (inExtraTransparencyLayer)
        endTransparencyLayer();
}

void GraphicsContextSkia::fillRectWithRoundedHole(const FloatRect& outerRect, const FloatRoundedRect& innerRRect, const Color& color)
{
    if (!color.isValid())
        return;

    if (!makeGLContextCurrentIfNeeded())
        return;

    SkPaint paint = createFillPaint();
    paint.setColor(SkColor(color));
    paint.setImageFilter(createDropShadowFilterIfNeeded(ShadowStyle::Inset));
    m_canvas.drawDRRect(SkRRect::MakeRect(outerRect), innerRRect, paint);
}

// FIXME: Make this a GraphicsContextSkia static function, and use it throughout WebCore.
static sk_sp<SkSurface> createAcceleratedSurface(const IntSize& size)
{
    auto* glContext = PlatformDisplay::sharedDisplay().skiaGLContext();
    if (!glContext || !glContext->makeContextCurrent())
        return nullptr;

    auto* grContext = PlatformDisplay::sharedDisplay().skiaGrContext();
    RELEASE_ASSERT(grContext);

    auto imageInfo = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType, kPremul_SkAlphaType, SkColorSpace::MakeSRGB());
    SkSurfaceProps properties { 0, FontRenderOptions::singleton().subpixelOrder() };
    auto surface = SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, imageInfo, PlatformDisplay::sharedDisplay().msaaSampleCount(), kTopLeft_GrSurfaceOrigin, &properties);
    if (!surface || !surface->getCanvas())
        return nullptr;

    return surface;
}

void GraphicsContextSkia::drawPattern(NativeImage& nativeImage, const FloatRect& destRect, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize& spacing, ImagePaintingOptions options)
{
    if (!patternTransform.isInvertible())
        return;

    auto image = nativeImage.platformImage();
    if (!image)
        return;

    if (!makeGLContextCurrentIfNeeded())
        return;

    FloatPoint phaseOffset(tileRect.location());
    phaseOffset.scale(patternTransform.a(), patternTransform.d());
    phaseOffset.moveBy(phase);
    SkMatrix phaseMatrix;
    phaseMatrix.setTranslate(phaseOffset.x(), phaseOffset.y());
    SkMatrix shaderMatrix = SkMatrix::Concat(phaseMatrix, patternTransform);
    auto samplingOptions = toSkSamplingOptions(m_state.imageInterpolationQuality());

    SkPaint paint = createFillPaint();
    paint.setBlendMode(toSkiaBlendMode(options.compositeOperator(), options.blendMode()));

    auto size = nativeImage.size();
    if (spacing.isZero() && tileRect.size() == size) {
        // Check whether we're sampling the pattern beyond the image size. If this is the case, we need to set the repeat
        // flag when sampling. Otherwise we use the clamp flag. This is done to avoid a situation where the pattern is scaled
        // to fit perfectly the destinationRect, but if we use the repeat flag in that case the edges are wrong because the
        // scaling interpolation is using pixels from the other end of the image.
        bool repeatX = true;
        bool repeatY = true;
        SkMatrix inverse;
        if (shaderMatrix.invert(&inverse)) {
            SkRect imageSampledRect;
            inverse.mapRect(&imageSampledRect, SkRect::MakeXYWH(destRect.x(), destRect.y(), destRect.width(), destRect.height()));
            repeatX = imageSampledRect.x() < 0 || std::trunc(imageSampledRect.right()) > size.width();
            repeatY = imageSampledRect.y() < 0 || std::trunc(imageSampledRect.bottom()) > size.height();
        }
        paint.setShader(image->makeShader(repeatX ? SkTileMode::kRepeat : SkTileMode::kClamp, repeatY ? SkTileMode::kRepeat : SkTileMode::kClamp, samplingOptions, &shaderMatrix));
        trackAcceleratedRenderingFenceIfNeeded(image);
    } else {
        auto tileFloatRectWithSpacing = FloatRect(0, 0, tileRect.width() + spacing.width() / patternTransform.a(), tileRect.height() + spacing.height() / patternTransform.d());
        if (image->isTextureBacked()) {
            auto enclosingTileIntRect = enclosingIntRect(tileRect);
            auto dstRect = SkRect::MakeWH(enclosingTileIntRect.width(), enclosingTileIntRect.height());
            auto clipRect = enclosingIntRect(tileFloatRectWithSpacing);
            if (auto surface = createAcceleratedSurface({ clipRect.width(), clipRect.height() })) {
                surface->getCanvas()->drawImageRect(image, tileRect, dstRect, samplingOptions, nullptr, SkCanvas::kStrict_SrcRectConstraint);
                auto tileImage = surface->makeImageSnapshot();
                paint.setShader(tileImage->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, samplingOptions, &shaderMatrix));
                trackAcceleratedRenderingFenceIfNeeded(tileImage);
            }
        } else {
            auto dstRect = SkRect::MakeWH(tileRect.width(), tileRect.height());
            auto clipRect = SkRect::MakeWH(tileFloatRectWithSpacing.width(), tileFloatRectWithSpacing.height());
            // For raster images we can save creating a copy altogether, by using SkPicture recording instead.
            SkPictureRecorder recorder;
            auto* recordCanvas = recorder.beginRecording(clipRect);
            // The below call effectively extracts a tile from the image thus performing a clipping.
            recordCanvas->drawImageRect(image, tileRect, dstRect, samplingOptions, nullptr, SkCanvas::kStrict_SrcRectConstraint);
            auto picture = recorder.finishRecordingAsPicture();
            paint.setShader(picture->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, samplingOptions.filter, &shaderMatrix, nullptr));
        }
    }

    m_canvas.drawRect(destRect, paint);
}

void GraphicsContextSkia::beginRecording()
{
    ASSERT(m_contextMode == ContextMode::PaintingMode);
    m_contextMode = ContextMode::RecordingMode;
}

SkiaImageToFenceMap GraphicsContextSkia::endRecording()
{
    ASSERT(m_contextMode == ContextMode::RecordingMode);
    m_contextMode = ContextMode::PaintingMode;
    return WTFMove(m_imageToFenceMap);
}

template<typename T>
inline std::unique_ptr<GLFence> createAcceleratedRenderingFence(T object)
{
    auto* glContext = PlatformDisplay::sharedDisplay().skiaGLContext();
    if (!glContext || !glContext->makeContextCurrent())
        return nullptr;

    auto* grContext = PlatformDisplay::sharedDisplay().skiaGrContext();
    RELEASE_ASSERT(grContext);

    grContext->flush(object);

    if (GLFence::isSupported()) {
        grContext->submit(GrSyncCpu::kNo);

        if (auto fence = GLFence::create())
            return fence;
    }

    grContext->submit(GrSyncCpu::kYes);
    return nullptr;
}

std::unique_ptr<GLFence> GraphicsContextSkia::createAcceleratedRenderingFenceIfNeeded(SkSurface* surface)
{
    if (!surface || !surface->recordingContext())
        return nullptr;
    return createAcceleratedRenderingFence<SkSurface*>(surface);
}

std::unique_ptr<GLFence> GraphicsContextSkia::createAcceleratedRenderingFenceIfNeeded(const sk_sp<SkImage>& image)
{
    if (!image || !image->isTextureBacked())
        return nullptr;
    return createAcceleratedRenderingFence<const sk_sp<SkImage>>(image);
}

void GraphicsContextSkia::trackAcceleratedRenderingFenceIfNeeded(const sk_sp<SkImage>& image)
{
    if (m_contextMode != ContextMode::RecordingMode)
        return;

    if (auto fence = createAcceleratedRenderingFenceIfNeeded(image))
        m_imageToFenceMap.add(image.get(), WTFMove(fence));
}

void GraphicsContextSkia::trackAcceleratedRenderingFenceIfNeeded(SkPaint& paint)
{
    if (m_contextMode != ContextMode::RecordingMode)
        return;

    auto* shader = paint.getShader();
    auto* image = shader ? shader->isAImage(nullptr, nullptr) : nullptr;
    if (auto fence = createAcceleratedRenderingFenceIfNeeded(sk_ref_sp(image)))
        m_imageToFenceMap.add(image, WTFMove(fence));
}

void GraphicsContextSkia::drawSkiaText(const sk_sp<SkTextBlob>& blob, SkScalar x, SkScalar y, bool enableAntialias, bool isVertical)
{
    if (isVertical) {
        m_canvas.save();

        SkMatrix matrix;
        matrix.setSinCos(-1, 0, x, y);
        m_canvas.concat(matrix);
    }

    if (textDrawingMode().contains(TextDrawingMode::Fill)) {
        SkPaint paint = createFillPaint();
        setupFillSource(paint);
        paint.setAntiAlias(enableAntialias);
        bool inExtraTransparencyLayer = false;
        if (hasDropShadow()) {
            inExtraTransparencyLayer = drawOutsetShadow(paint, [&](const SkPaint& paint) {
                m_canvas.drawTextBlob(blob, x, y, paint);
            });
        }
        m_canvas.drawTextBlob(blob, x, y, paint);
        if (inExtraTransparencyLayer)
            endTransparencyLayer();
    }

    if (textDrawingMode().contains(TextDrawingMode::Stroke)) {
        SkPaint paint = createStrokePaint();
        setupStrokeSource(paint);
        paint.setAntiAlias(enableAntialias);
        m_canvas.drawTextBlob(blob, x, y, paint);
    }

    if (isVertical)
        m_canvas.restore();
}

RenderingMode GraphicsContextSkia::renderingMode() const
{
    return m_renderingMode;
}

} // namespace WebCore

#endif // USE(SKIA)