File: base_rendering_context_2d.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1677 lines) | stat: -rw-r--r-- 66,232 bytes parent folder | download | duplicates (2)
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h"

#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <optional>
#include <utility>

#include "base/check.h"
#include "base/check_op.h"
#include "base/location.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/numerics/checked_math.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "cc/paint/paint_canvas.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_image.h"
#include "components/viz/common/resources/shared_image_format_utils.h"
#include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
#include "third_party/blink/public/common/metrics/document_update_reason.h"
#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink-forward.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_canvas_text_align.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_canvas_text_baseline.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_text_cluster_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_2d_gpu_transfer_option.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_direction.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_font_kerning.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_font_stretch.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_font_variant_caps.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_canvas_text_rendering.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_texture_format.h"
#include "third_party/blink/renderer/core/canvas_interventions/canvas_interventions_enums.h"
#include "third_party/blink/renderer/core/canvas_interventions/canvas_interventions_helper.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/event_type_names.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_font_cache.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_performance_monitor.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/html/canvas/text_cluster.h"
#include "third_party/blink/renderer/core/html/canvas/text_metrics.h"
#include "third_party/blink/renderer/core/html/canvas/unique_font_selector.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_2d_recorder_context.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/identifiability_study_helper.h"
#include "third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.h"
#include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h"
#include "third_party/blink/renderer/modules/webgpu/dawn_enum_conversions.h"
#include "third_party/blink/renderer/modules/webgpu/gpu.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_device.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_texture.h"
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/fonts/font_selection_types.h"
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
#include "third_party/blink/renderer/platform/fonts/plain_text_painter.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
#include "third_party/blink/renderer/platform/fonts/text_run_paint_info.h"
#include "third_party/blink/renderer/platform/geometry/path.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/blend_mode.h"
#include "third_party/blink/renderer/platform/graphics/canvas_deferred_paint_record.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_host.h"
#include "third_party/blink/renderer/platform/graphics/flush_reason.h"
#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h"
#include "third_party/blink/renderer/platform/graphics/gpu/webgpu_cpp.h"
#include "third_party/blink/renderer/platform/graphics/gpu/webgpu_mailbox_texture.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/image_data_buffer.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/video_frame_image_util.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/privacy_budget/identifiability_digest_helpers.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/layout_locale.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
#include "third_party/blink/renderer/platform/text/unicode_bidi.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "ui/gfx/geometry/skia_conversions.h"

// Including "base/time/time.h" triggers a bug in IWYU.
// https://github.com/include-what-you-use/include-what-you-use/issues/1122
// IWYU pragma: no_include "base/numerics/clamped_math.h"

namespace blink {
namespace {

wgpu::TextureFormat AsDawnType(const viz::SharedImageFormat& format) {
  // NOTE: Canvas2D can be only RGBA_8888, BGRA_8888, or F16.
  if (format == viz::SinglePlaneFormat::kRGBA_8888) {
    return wgpu::TextureFormat::RGBA8Unorm;
  } else if (format == viz::SinglePlaneFormat::kBGRA_8888) {
    return wgpu::TextureFormat::BGRA8Unorm;
  } else if (format == viz::SinglePlaneFormat::kRGBA_F16) {
    return wgpu::TextureFormat::RGBA16Float;
  } else {
    return wgpu::TextureFormat::Undefined;
  }
}

bool IsContextProviderValid() {
  base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper =
      SharedGpuContext::ContextProviderWrapper();
  return context_provider_wrapper &&
         !context_provider_wrapper->ContextProvider().IsContextLost();
}

}  // namespace

constexpr char kDefaultFont[] = "10px sans-serif";
const char BaseRenderingContext2D::kInheritString[] = "inherit";

BaseRenderingContext2D::BaseRenderingContext2D(
    CanvasRenderingContextHost* canvas,
    const CanvasContextCreationAttributesCore& attrs,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : CanvasRenderingContext(canvas, attrs, CanvasRenderingAPI::k2D),
      dispatch_context_lost_event_timer_(
          task_runner,
          this,
          &BaseRenderingContext2D::DispatchContextLostEvent),
      dispatch_context_restored_event_timer_(
          task_runner,
          this,
          &BaseRenderingContext2D::DispatchContextRestoredEvent),
      try_restore_context_event_timer_(
          task_runner,
          this,
          &BaseRenderingContext2D::TryRestoreContextEvent),
      color_params_(attrs.color_space, attrs.pixel_format, attrs.alpha) {}

void BaseRenderingContext2D::ResetInternal() {
  Canvas2DRecorderContext::ResetInternal();

  // If a WebGPU transfer texture exists, we must destroy it immediately. We
  // can't allow it to continue to exist, as it would be subject to Javascript
  // garbage-collection and could vanish any time Oilpan runs a sweep. Normally
  // it's okay for Oilpan to delete GPUTextures, since Dawn maintains its own
  // ownership graph of GPU resources, but in our case, destruction of the
  // GPUTexture will also result in destruction of the associated SharedImage.
  if (webgpu_access_texture_) {
    webgpu_access_texture_->destroy();
    webgpu_access_texture_ = nullptr;
  }
}

CanvasRenderingContext2DSettings* BaseRenderingContext2D::getContextAttributes()
    const {
  return ToCanvasRenderingContext2DSettings(CreationAttributes());
}

bool BaseRenderingContext2D::IsDrawElementEligible(
    Element* element,
    ExceptionState& exception_state) {
  HTMLCanvasElement* canvas_element = HostAsHTMLCanvasElement();
  if (!canvas_element || !canvas_element->GetDocument().View()) {
    return false;
  }

  if (!GetOrCreatePaintCanvas()) {
    return false;
  }

  if (element->parentElement() != canvas_element) {
    exception_state.ThrowTypeError(
        "Only immediate children of the <canvas> element can be passed to "
        "drawElement().");
    return false;
  }

  if (!canvas_element->layoutSubtree()) {
    exception_state.ThrowTypeError(
        "<canvas> elements without layoutsubtree do not support "
        "drawElement().");
    return false;
  }

  if (!element->GetLayoutObject()) {
    exception_state.ThrowTypeError(
        "The canvas and element used with drawElement() must have been laid "
        "out. Detached canvases are not supported, nor canvas or children that "
        "are `display: none`.");
    return false;
  }

  // TODO(crbug.com/413728246): Maybe we can support canvas element.
  if (IsA<HTMLCanvasElement>(element)) {
    exception_state.ThrowTypeError(
        "<canvas> children of a <canvas> cannot be passed to drawElement().");
    return false;
  }

  return true;
}

void BaseRenderingContext2D::DispatchContextLostEvent(TimerBase*) {
  // If `need_dispatch_context_restored_` is `true`, the context has been
  // restored already (e.g. by fixing a `kInvalidCanvasSize` context loss), but
  // the oncontextrestored event was postponed until the oncontextlost event was
  // dispatched first. This is happening now, so irrespective of how this
  // function returns, `need_dispatch_context_restored_` should be cleared.
  absl::Cleanup cleanup = [this] { need_dispatch_context_restored_ = false; };

  Event* event = Event::CreateCancelable(event_type_names::kContextlost);
  GetCanvasRenderingContextHost()->HostDispatchEvent(event);

  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DContextLostEvent);
  if (event->defaultPrevented()) {
    context_restorable_ = false;
  }

  if (!context_restorable_) {
    return;
  }

  if (need_dispatch_context_restored_) {
    // The context is already restored (an invalid canvas size was probably
    // fixed). We can send the restored event right away.
    dispatch_context_restored_event_timer_.StartOneShot(base::TimeDelta(),
                                                        FROM_HERE);
    return;
  }

  if (context_lost_mode_ == CanvasRenderingContext::kRealLostContext ||
      context_lost_mode_ == CanvasRenderingContext::kSyntheticLostContext) {
    try_restore_context_attempt_count_ = 0;
    try_restore_context_event_timer_.StartRepeating(
        try_restore_context_interval_, FROM_HERE);
  }
}

void BaseRenderingContext2D::DispatchContextRestoredEvent(TimerBase*) {
  // Since canvas may trigger contextlost event by multiple different ways (ex:
  // gpu crashes and frame eviction), it's possible to triggeer this
  // function while the context is already restored. In this case, we
  // abort it here.
  if (context_lost_mode_ == CanvasRenderingContext::kNotLostContext) {
    return;
  }

  if (!context_restorable_) {
    return;
  }

  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  if (host == nullptr) {
    // This function can be called in a new task, via
    // `dispatch_context_restored_event_timer_`. Abort if the host was disposed
    // since the task was queued.
    return;
  }

  host->ClearLayerTexture();
  ResetInternal();
  context_lost_mode_ = CanvasRenderingContext::kNotLostContext;
  Event* event(Event::Create(event_type_names::kContextrestored));
  host->HostDispatchEvent(event);
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DContextRestoredEvent);
}

void BaseRenderingContext2D::TryRestoreContextEvent(TimerBase* timer) {
  const CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  if (host == nullptr) [[unlikely]] {
    // The host was disposed while this callback was pending.
    try_restore_context_event_timer_.Stop();
    return;
  }

  DCHECK(context_lost_mode_ !=
         CanvasRenderingContext::kWebGLLoseContextLostContext);

  // The canvas was changed to an invalid size since the context was lost. We
  // can't restore the context until the canvas is given a valid size. Abort
  // here to avoid creating a shared GPU context we would not use.
  if (!IsValidImageSize(host->Size()) && !host->Size().IsEmpty()) {
    context_lost_mode_ = kInvalidCanvasSize;
    try_restore_context_event_timer_.Stop();
    return;
  }

  // For real context losses, we can only restore if the SharedGpuContext is
  // ready.
  if (context_lost_mode_ != CanvasRenderingContext::kRealLostContext ||
      (SharedGpuContext::IsGpuCompositingEnabled() &&
       IsContextProviderValid()) ||
      (!SharedGpuContext::IsGpuCompositingEnabled() &&
       SharedGpuContext::SharedImageInterfaceProvider())) {
    RestoreGuard context_is_being_restored(*this);
    if (GetOrCreateCanvas2DResourceProvider()) {
      try_restore_context_event_timer_.Stop();
      DispatchContextRestoredEvent(nullptr);
      return;
    }
  }

  // Retry up to `kMaxTryRestoreContextAttempts` times before giving up.
  if (++try_restore_context_attempt_count_ > kMaxTryRestoreContextAttempts) {
    try_restore_context_event_timer_.Stop();
    if (on_restore_failed_callback_for_testing_) {
      on_restore_failed_callback_for_testing_.Run();
    }
  }
}

void BaseRenderingContext2D::RestoreFromInvalidSizeIfNeeded() {
  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  if (!context_restorable_ || context_lost_mode_ != kInvalidCanvasSize ||
      !host) {
    return;
  }
  DCHECK(!host->ResourceProvider());

  if (IsValidImageSize(host->Size())) {
    if (dispatch_context_lost_event_timer_.IsActive()) {
      // An oncontextlost event is still pending. We can't send the
      // oncontextrestored right away because the oncontextlost callback could
      // choose to prevent restoration. Thus, we need to delay queuing the
      // restored event to after the lost event completed.
      need_dispatch_context_restored_ = true;
    } else {
      dispatch_context_restored_event_timer_.StartOneShot(base::TimeDelta(),
                                                          FROM_HERE);
    }
  }
}

ImageData* BaseRenderingContext2D::createImageData(
    ImageData* image_data,
    ExceptionState& exception_state) const {
  ImageData::ValidateAndCreateParams params;
  params.context_2d_error_mode = true;
  return ImageData::ValidateAndCreate(
      image_data->Size().width(), image_data->Size().height(), std::nullopt,
      image_data->getSettings(), params, exception_state);
}

ImageData* BaseRenderingContext2D::createImageData(
    int sw,
    int sh,
    ExceptionState& exception_state) const {
  ImageData::ValidateAndCreateParams params;
  params.context_2d_error_mode = true;
  params.default_color_space = GetDefaultImageDataColorSpace();
  return ImageData::ValidateAndCreate(std::abs(sw), std::abs(sh), std::nullopt,
                                      /*settings=*/nullptr, params,
                                      exception_state);
}

ImageData* BaseRenderingContext2D::createImageData(
    int sw,
    int sh,
    ImageDataSettings* image_data_settings,
    ExceptionState& exception_state) const {
  ImageData::ValidateAndCreateParams params;
  params.context_2d_error_mode = true;
  params.default_color_space = GetDefaultImageDataColorSpace();
  return ImageData::ValidateAndCreate(std::abs(sw), std::abs(sh), std::nullopt,
                                      image_data_settings, params,
                                      exception_state);
}

ImageData* BaseRenderingContext2D::getImageData(
    int sx,
    int sy,
    int sw,
    int sh,
    ExceptionState& exception_state) {
  return getImageDataInternal(sx, sy, sw, sh, /*image_data_settings=*/nullptr,
                              exception_state);
}

ImageData* BaseRenderingContext2D::getImageData(
    int sx,
    int sy,
    int sw,
    int sh,
    ImageDataSettings* image_data_settings,
    ExceptionState& exception_state) {
  return getImageDataInternal(sx, sy, sw, sh, image_data_settings,
                              exception_state);
}
perfetto::EventContext GetEventContext();

ImageData* BaseRenderingContext2D::getImageDataInternal(
    int sx,
    int sy,
    int sw,
    int sh,
    ImageDataSettings* image_data_settings,
    ExceptionState& exception_state) {
  if (!base::CheckMul(sw, sh).IsValid<int>()) {
    exception_state.ThrowRangeError("Out of memory at ImageData creation");
    return nullptr;
  }

  if (layer_count_ != 0) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "`getImageData()` cannot be called with open layers.");
    return nullptr;
  }

  if (!OriginClean()) {
    exception_state.ThrowSecurityError(
        "The canvas has been tainted by cross-origin data.");
  } else if (!sw || !sh) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kIndexSizeError,
        String::Format("The source %s is 0.", sw ? "height" : "width"));
  }

  if (exception_state.HadException())
    return nullptr;

  if (sw < 0) {
    if (!base::CheckAdd(sx, sw).IsValid<int>()) {
      exception_state.ThrowRangeError("Out of memory at ImageData creation");
      return nullptr;
    }
    sx += sw;
    sw = base::saturated_cast<int>(base::SafeUnsignedAbs(sw));
  }
  if (sh < 0) {
    if (!base::CheckAdd(sy, sh).IsValid<int>()) {
      exception_state.ThrowRangeError("Out of memory at ImageData creation");
      return nullptr;
    }
    sy += sh;
    sh = base::saturated_cast<int>(base::SafeUnsignedAbs(sh));
  }

  if (!base::CheckAdd(sx, sw).IsValid<int>() ||
      !base::CheckAdd(sy, sh).IsValid<int>()) {
    exception_state.ThrowRangeError("Out of memory at ImageData creation");
    return nullptr;
  }

  const gfx::Rect image_data_rect(sx, sy, sw, sh);

  ImageData::ValidateAndCreateParams validate_and_create_params;
  validate_and_create_params.context_2d_error_mode = true;
  validate_and_create_params.default_color_space =
      GetDefaultImageDataColorSpace();

  if (isContextLost()) {
    return ImageData::ValidateAndCreate(
        sw, sh, std::nullopt, image_data_settings, validate_and_create_params,
        exception_state);
  }

  // Deferred offscreen canvases might have recorded commands, make sure
  // that those get drawn here
  FinalizeFrame(FlushReason::kGetImageData);

  num_readbacks_performed_++;
  CanvasContextCreationAttributesCore::WillReadFrequently
      will_read_frequently_value = GetCanvasRenderingContextHost()
                                       ->RenderingContext()
                                       ->CreationAttributes()
                                       .will_read_frequently;
  if (num_readbacks_performed_ == 2 && GetCanvasRenderingContextHost() &&
      GetCanvasRenderingContextHost()->RenderingContext()) {
    if (will_read_frequently_value ==
        CanvasContextCreationAttributesCore::WillReadFrequently::kUndefined) {
      if (auto* execution_context = GetTopExecutionContext()) {
        const String& message =
            "Canvas2D: Multiple readback operations using getImageData are "
            "faster with the willReadFrequently attribute set to true. See: "
            "https://html.spec.whatwg.org/multipage/"
            "canvas.html#concept-canvas-will-read-frequently";
        execution_context->AddConsoleMessage(
            MakeGarbageCollected<ConsoleMessage>(
                mojom::blink::ConsoleMessageSource::kRendering,
                mojom::blink::ConsoleMessageLevel::kWarning, message));
      }
    }
  }

  // The default behavior before the willReadFrequently feature existed:
  // Accelerated canvases fall back to CPU when there is a readback.
  if (will_read_frequently_value ==
      CanvasContextCreationAttributesCore::WillReadFrequently::kUndefined) {
    // GetImageData is faster in Unaccelerated canvases.
    // In Desynchronized canvas disabling the acceleration will break
    // putImageData: crbug.com/1112060.
    if (IsAccelerated() && !IsDesynchronized()) {
      read_count_++;
      if (read_count_ >= kFallbackToCPUAfterReadbacks ||
          ShouldDisableAccelerationBecauseOfReadback()) {
        DisableAcceleration();
        base::UmaHistogramEnumeration("Blink.Canvas.GPUFallbackToCPU",
                                      GPUFallbackToCPUScenario::kGetImageData);
      }
    }
  }

  scoped_refptr<StaticBitmapImage> snapshot =
      GetImage(FlushReason::kGetImageData);

  bool noised = false;
  if (auto* host = GetCanvasRenderingContextHost()) {
    if (snapshot) {
      noised = CanvasInterventionsHelper::MaybeNoiseSnapshot(
          host->RenderingContext(), GetTopExecutionContext(), snapshot);
    }
  }

  TRACE_EVENT_INSTANT(
      TRACE_DISABLED_BY_DEFAULT("identifiability.high_entropy_api"),
      "CanvasReadback", perfetto::Flow::FromPointer(this),
      [&](perfetto::EventContext ctx) {
        String data = "data:,";
        if (snapshot) {
          std::unique_ptr<ImageDataBuffer> data_buffer =
              ImageDataBuffer::Create(snapshot);
          if (data_buffer) {
            data = data_buffer->ToDataURL(ImageEncodingMimeType::kMimeTypePng,
                                          -1.0);
          }
        }
        ctx.AddDebugAnnotation("data_url", data.Utf8());
        ctx.AddDebugAnnotation("noised", noised);
      });

  // Determine if the array should be zero initialized, or if it will be
  // completely overwritten.
  validate_and_create_params.zero_initialize = false;
  if (IsAccelerated()) {
    // GPU readback may fail silently.
    validate_and_create_params.zero_initialize = true;
  } else if (snapshot) {
    // Zero-initialize if some of the readback area is out of bounds.
    if (image_data_rect.x() < 0 || image_data_rect.y() < 0 ||
        image_data_rect.right() > snapshot->Size().width() ||
        image_data_rect.bottom() > snapshot->Size().height()) {
      validate_and_create_params.zero_initialize = true;
    }
  } else {
    // If there's no snapshot, the buffer will not be overwritten and hence must
    // be zero-initialized.
    validate_and_create_params.zero_initialize = true;
  }

  ImageData* image_data =
      ImageData::ValidateAndCreate(sw, sh, std::nullopt, image_data_settings,
                                   validate_and_create_params, exception_state);
  if (!image_data)
    return nullptr;

  // Read pixels into |image_data|.
  if (snapshot) {
    gfx::Rect snapshot_rect{snapshot->Size()};
    if (!snapshot_rect.Intersects(image_data_rect)) {
      // If the readback area is completely out of bounds just return a zero
      // initialized buffer. No point in trying to perform out of bounds read.
      CHECK(validate_and_create_params.zero_initialize);
      return image_data;
    }

    SkPixmap image_data_pixmap = image_data->GetSkPixmap();
    const bool read_pixels_successful =
        snapshot->PaintImageForCurrentFrame().readPixels(
            image_data_pixmap.info(), image_data_pixmap.writable_addr(),
            image_data_pixmap.rowBytes(), sx, sy);
    if (!read_pixels_successful) {
      SkIRect bounds =
          snapshot->PaintImageForCurrentFrame().GetSkImageInfo().bounds();
      DCHECK(!bounds.intersect(SkIRect::MakeXYWH(sx, sy, sw, sh)));
    }
  }

  return image_data;
}

void BaseRenderingContext2D::putImageData(ImageData* data,
                                          int dx,
                                          int dy,
                                          ExceptionState& exception_state) {
  putImageData(data, dx, dy, 0, 0, data->width(), data->height(),
               exception_state);
}

void BaseRenderingContext2D::putImageData(ImageData* data,
                                          int dx,
                                          int dy,
                                          int dirty_x,
                                          int dirty_y,
                                          int dirty_width,
                                          int dirty_height,
                                          ExceptionState& exception_state) {
  if (!base::CheckMul(dirty_width, dirty_height).IsValid<int>()) {
    return;
  }

  if (data->IsBufferBaseDetached()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "The source data has been detached.");
    return;
  }

  if (layer_count_ != 0) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "`putImageData()` cannot be called with open layers.");
    return;
  }

  if (isContextLost() || !CanCreateCanvas2dResourceProvider()) [[unlikely]] {
    return;
  }

  if (identifiability_study_helper_.ShouldUpdateBuilder()) [[unlikely]] {
    identifiability_study_helper_.UpdateBuilder(
        CanvasOps::kPutImageData, data->width(), data->height(),
        data->GetPredefinedColorSpace(), data->GetSkColorType(), dx, dy,
        dirty_x, dirty_y, dirty_width, dirty_height);
    identifiability_study_helper_.set_encountered_partially_digested_image();
  }

  if (dirty_width < 0) {
    if (dirty_x < 0) {
      dirty_x = dirty_width = 0;
    } else {
      dirty_x += dirty_width;
      dirty_width =
          base::saturated_cast<int>(base::SafeUnsignedAbs(dirty_width));
    }
  }

  if (dirty_height < 0) {
    if (dirty_y < 0) {
      dirty_y = dirty_height = 0;
    } else {
      dirty_y += dirty_height;
      dirty_height =
          base::saturated_cast<int>(base::SafeUnsignedAbs(dirty_height));
    }
  }

  gfx::Rect dest_rect(dirty_x, dirty_y, dirty_width, dirty_height);
  dest_rect.Intersect(gfx::Rect(0, 0, data->width(), data->height()));
  gfx::Vector2d dest_offset(static_cast<int>(dx), static_cast<int>(dy));
  dest_rect.Offset(dest_offset);
  dest_rect.Intersect(gfx::Rect(0, 0, Width(), Height()));
  if (dest_rect.IsEmpty())
    return;

  gfx::Rect source_rect = dest_rect;
  source_rect.Offset(-dest_offset);

  SkPixmap data_pixmap = data->GetSkPixmap();

  // WritePixels (called by PutByteArray) requires that the source and
  // destination pixel formats have the same bytes per pixel.
  SkColorType dest_color_type =
      viz::ToClosestSkColorType(GetSharedImageFormat());
  if (SkColorTypeBytesPerPixel(dest_color_type) !=
      SkColorTypeBytesPerPixel(data_pixmap.colorType())) {
    SkImageInfo converted_info =
        data_pixmap.info().makeColorType(dest_color_type);
    SkBitmap converted_bitmap;
    if (!converted_bitmap.tryAllocPixels(converted_info)) {
      exception_state.ThrowRangeError("Out of memory in putImageData");
      return;
    }
    if (!converted_bitmap.writePixels(data_pixmap, 0, 0)) {
      NOTREACHED() << "Failed to convert ImageData with writePixels.";
    }

    PutByteArray(converted_bitmap.pixmap(), source_rect, dest_offset);
    if (GetPaintCanvas()) {
      WillDraw(gfx::RectToSkIRect(dest_rect),
               CanvasPerformanceMonitor::DrawType::kImageData);
    }
    return;
  }

  PutByteArray(data_pixmap, source_rect, dest_offset);
  if (GetPaintCanvas()) {
    WillDraw(gfx::RectToSkIRect(dest_rect),
             CanvasPerformanceMonitor::DrawType::kImageData);
  }
}

void BaseRenderingContext2D::PutByteArray(const SkPixmap& source,
                                          const gfx::Rect& source_rect,
                                          const gfx::Vector2d& dest_offset) {
  if (!IsCanvas2DBufferValid())
    return;

  DCHECK(gfx::Rect(source.width(), source.height()).Contains(source_rect));
  int dest_x = dest_offset.x() + source_rect.x();
  DCHECK_GE(dest_x, 0);
  DCHECK_LT(dest_x, Width());
  int dest_y = dest_offset.y() + source_rect.y();
  DCHECK_GE(dest_y, 0);
  DCHECK_LT(dest_y, Height());

  SkImageInfo info =
      source.info().makeWH(source_rect.width(), source_rect.height());
  if (!HasAlpha()) {
    // If the surface is opaque, tell it that we are writing opaque
    // pixels.  Writing non-opaque pixels to opaque is undefined in
    // Skia.  There is some discussion about whether it should be
    // defined in skbug.com/6157.  For now, we can get the desired
    // behavior (memcpy) by pretending the write is opaque.
    info = info.makeAlphaType(kOpaque_SkAlphaType);
  } else {
    info = info.makeAlphaType(kUnpremul_SkAlphaType);
  }

  WritePixels(info, source.addr(source_rect.x(), source_rect.y()),
              source.rowBytes(), dest_x, dest_y);
}

String BaseRenderingContext2D::letterSpacing() const {
  return GetState().GetLetterSpacing();
}

String BaseRenderingContext2D::wordSpacing() const {
  return GetState().GetWordSpacing();
}

V8CanvasTextRendering BaseRenderingContext2D::textRendering() const {
  return GetState().GetTextRendering();
}

V8CanvasTextAlign BaseRenderingContext2D::textAlign() const {
  return GetState().GetTextAlign();
}

void BaseRenderingContext2D::setTextAlign(const V8CanvasTextAlign align) {
  if (identifiability_study_helper_.ShouldUpdateBuilder()) [[unlikely]] {
    identifiability_study_helper_.UpdateBuilder(
        CanvasOps::kSetTextAlign,
        IdentifiabilityBenignStringToken(align.AsString()));
  }
  GetState().SetTextAlign(align);
}

V8CanvasTextBaseline BaseRenderingContext2D::textBaseline() const {
  return GetState().GetTextBaseline();
}

void BaseRenderingContext2D::setTextBaseline(
    const V8CanvasTextBaseline baseline) {
  if (identifiability_study_helper_.ShouldUpdateBuilder()) [[unlikely]] {
    identifiability_study_helper_.UpdateBuilder(
        CanvasOps::kSetTextBaseline,
        IdentifiabilityBenignStringToken(baseline.AsString()));
  }
  GetState().SetTextBaseline(baseline);
}

V8CanvasFontKerning BaseRenderingContext2D::fontKerning() const {
  switch (GetState().GetFontKerning()) {
    case (FontDescription::Kerning::kAutoKerning):
      return V8CanvasFontKerning(V8CanvasFontKerning::Enum::kAuto);
    case (FontDescription::Kerning::kNoneKerning):
      return V8CanvasFontKerning(V8CanvasFontKerning::Enum::kNone);
    case (FontDescription::Kerning::kNormalKerning):
      return V8CanvasFontKerning(V8CanvasFontKerning::Enum::kNormal);
  }
}

V8CanvasFontStretch BaseRenderingContext2D::fontStretch() const {
  return GetState().GetFontStretch();
}

V8CanvasFontVariantCaps BaseRenderingContext2D::fontVariantCaps() const {
  switch (GetState().GetFontVariantCaps()) {
    case (FontDescription::FontVariantCaps::kCapsNormal):
      return V8CanvasFontVariantCaps(V8CanvasFontVariantCaps::Enum::kNormal);
    case (FontDescription::FontVariantCaps::kSmallCaps):
      return V8CanvasFontVariantCaps(V8CanvasFontVariantCaps::Enum::kSmallCaps);
    case (FontDescription::FontVariantCaps::kAllSmallCaps):
      return V8CanvasFontVariantCaps(
          V8CanvasFontVariantCaps::Enum::kAllSmallCaps);
    case (FontDescription::FontVariantCaps::kPetiteCaps):
      return V8CanvasFontVariantCaps(
          V8CanvasFontVariantCaps::Enum::kPetiteCaps);
    case (FontDescription::FontVariantCaps::kAllPetiteCaps):
      return V8CanvasFontVariantCaps(
          V8CanvasFontVariantCaps::Enum::kAllPetiteCaps);
    case (FontDescription::FontVariantCaps::kTitlingCaps):
      return V8CanvasFontVariantCaps(
          V8CanvasFontVariantCaps::Enum::kTitlingCaps);
    case (FontDescription::FontVariantCaps::kUnicase):
      return V8CanvasFontVariantCaps(V8CanvasFontVariantCaps::Enum::kUnicase);
  }
}

void BaseRenderingContext2D::Trace(Visitor* visitor) const {
  visitor->Trace(dispatch_context_lost_event_timer_);
  visitor->Trace(dispatch_context_restored_event_timer_);
  visitor->Trace(try_restore_context_event_timer_);
  visitor->Trace(webgpu_access_texture_);
  CanvasRenderingContext::Trace(visitor);
  Canvas2DRecorderContext::Trace(visitor);
}

void BaseRenderingContext2D::RestoreCanvasMatrixClipStack(
    cc::PaintCanvas* c) const {
  RestoreMatrixClipStack(c);
}

void BaseRenderingContext2D::Reset() {
  ResetInternal();
}

void BaseRenderingContext2D::WillUseCurrentFont() const {
  if (HTMLCanvasElement* canvas = HostAsHTMLCanvasElement();
      canvas != nullptr) {
    canvas->GetDocument().GetCanvasFontCache()->WillUseCurrentFont();
  }
}

String BaseRenderingContext2D::font() const {
  const CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    return kDefaultFont;
  }

  WillUseCurrentFont();
  StringBuilder serialized_font;
  const FontDescription& font_description = state.GetFontDescription();

  if (font_description.Style() == kItalicSlopeValue) {
    serialized_font.Append("italic ");
  }
  if (font_description.Weight() == kBoldWeightValue) {
    serialized_font.Append("bold ");
  } else if (font_description.Weight() != kNormalWeightValue) {
    int weight_as_int = static_cast<int>((float)font_description.Weight());
    serialized_font.AppendNumber(weight_as_int);
    serialized_font.Append(" ");
  }
  if (font_description.VariantCaps() == FontDescription::kSmallCaps) {
    serialized_font.Append("small-caps ");
  }

  serialized_font.AppendNumber(font_description.ComputedSize());
  serialized_font.Append("px ");

  serialized_font.Append(
      ComputedStyleUtils::ValueForFontFamily(font_description.Family())
          ->CssText());

  return serialized_font.ToString();
}

bool BaseRenderingContext2D::WillSetFont() const {
  return true;
}

bool BaseRenderingContext2D::CurrentFontResolvedAndUpToDate() const {
  const CanvasRenderingContext2DState& state = GetState();
  return state.HasRealizedFont() && !state.LangIsDirty();
}

void BaseRenderingContext2D::setFont(const String& new_font) {
  if (!WillSetFont()) [[unlikely]] {
    return;
  }

  if (identifiability_study_helper_.ShouldUpdateBuilder()) [[unlikely]] {
    identifiability_study_helper_.UpdateBuilder(
        CanvasOps::kSetFont, IdentifiabilityBenignStringToken(new_font));
  }

  CanvasRenderingContext2DState& state = GetState();
  if (new_font == state.UnparsedFont() && CurrentFontResolvedAndUpToDate()) {
    return;
  }

  if (!ResolveFont(new_font)) {
    return;
  }

  // The parse succeeded.
  state.SetUnparsedFont(new_font);
}

static inline TextDirection ToTextDirection(
    V8CanvasDirection direction,
    CanvasRenderingContextHost* host,
    const ComputedStyle* style = nullptr) {
  switch (direction.AsEnum()) {
    case V8CanvasDirection::Enum::kInherit:
      return host ? host->GetTextDirection(style) : TextDirection::kLtr;
    case V8CanvasDirection::Enum::kRtl:
      return TextDirection::kRtl;
    case V8CanvasDirection::Enum::kLtr:
      return TextDirection::kLtr;
  }
  NOTREACHED();
}

V8CanvasDirection BaseRenderingContext2D::direction() const {
  const CanvasRenderingContext2DState& state = GetState();
  bool value_is_inherit =
      state.GetDirection() == V8CanvasDirection::Enum::kInherit;
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasTextDirectionGet);
  if (value_is_inherit) {
    UseCounter::Count(GetTopExecutionContext(),
                      WebFeature::kCanvasTextDirectionGetInherit);
  }
  return ToTextDirection(state.GetDirection(),
                         GetCanvasRenderingContextHost()) == TextDirection::kRtl
             ? V8CanvasDirection(V8CanvasDirection::Enum::kRtl)
             : V8CanvasDirection(V8CanvasDirection::Enum::kLtr);
}

void BaseRenderingContext2D::setDirection(const V8CanvasDirection direction) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasTextDirectionSet);
  if (direction == V8CanvasDirection::Enum::kInherit) {
    UseCounter::Count(GetTopExecutionContext(),
                      WebFeature::kCanvasTextDirectionSetInherit);
  }

  CanvasRenderingContext2DState& state = GetState();
  state.SetDirection(direction);
}

void BaseRenderingContext2D::fillText(const String& text, double x, double y) {
  CanvasRenderingContext2DState& state = GetState();
  DrawTextInternal(text, x, y, CanvasRenderingContext2DState::kFillPaintType,
                   state.GetTextAlign(), state.GetTextBaseline(), 0,
                   text.length());
}

void BaseRenderingContext2D::fillText(const String& text,
                                      double x,
                                      double y,
                                      double max_width) {
  CanvasRenderingContext2DState& state = GetState();
  DrawTextInternal(text, x, y, CanvasRenderingContext2DState::kFillPaintType,
                   state.GetTextAlign(), state.GetTextBaseline(), 0,
                   text.length(), &max_width);
}

void BaseRenderingContext2D::fillTextCluster(const TextCluster* text_cluster,
                                             double x,
                                             double y) {
  fillTextCluster(text_cluster, x, y, /*cluster_options=*/nullptr);
}

void BaseRenderingContext2D::fillTextCluster(
    const TextCluster* text_cluster,
    double x,
    double y,
    const TextClusterOptions* cluster_options) {
  DCHECK(text_cluster);
  V8CanvasTextAlign cluster_align = text_cluster->align();
  V8CanvasTextBaseline cluster_baseline = text_cluster->baseline();
  double cluster_x = text_cluster->x();
  double cluster_y = text_cluster->y();
  if (cluster_options != nullptr) {
    if (cluster_options->hasX()) {
      cluster_x = cluster_options->x();
    }
    if (cluster_options->hasY()) {
      cluster_y = cluster_options->y();
    }
    if (cluster_options->hasAlign()) {
      cluster_align = cluster_options->align();
    }
    if (cluster_options->hasBaseline()) {
      cluster_baseline = cluster_options->baseline();
    }
  }
  DrawTextInternal(text_cluster->text(), cluster_x + x, cluster_y + y,
                   CanvasRenderingContext2DState::kFillPaintType, cluster_align,
                   cluster_baseline, text_cluster->start(), text_cluster->end(),
                   nullptr, text_cluster->textMetrics()->GetFont());
}

void BaseRenderingContext2D::strokeText(const String& text,
                                        double x,
                                        double y) {
  CanvasRenderingContext2DState& state = GetState();
  DrawTextInternal(text, x, y, CanvasRenderingContext2DState::kStrokePaintType,
                   state.GetTextAlign(), state.GetTextBaseline(), 0,
                   text.length());
}

void BaseRenderingContext2D::strokeText(const String& text,
                                        double x,
                                        double y,
                                        double max_width) {
  CanvasRenderingContext2DState& state = GetState();
  DrawTextInternal(text, x, y, CanvasRenderingContext2DState::kStrokePaintType,
                   state.GetTextAlign(), state.GetTextBaseline(), 0,
                   text.length(), &max_width);
}

void BaseRenderingContext2D::strokeTextCluster(const TextCluster* text_cluster,
                                               double x,
                                               double y) {
  strokeTextCluster(text_cluster, x, y, /*cluster_options=*/nullptr);
}

void BaseRenderingContext2D::strokeTextCluster(
    const TextCluster* text_cluster,
    double x,
    double y,
    const TextClusterOptions* cluster_options) {
  DCHECK(text_cluster);
  V8CanvasTextAlign cluster_align = text_cluster->align();
  V8CanvasTextBaseline cluster_baseline = text_cluster->baseline();
  double cluster_x = text_cluster->x();
  double cluster_y = text_cluster->y();
  if (cluster_options != nullptr) {
    if (cluster_options->hasX()) {
      cluster_x = cluster_options->x();
    }
    if (cluster_options->hasY()) {
      cluster_y = cluster_options->y();
    }
    if (cluster_options->hasAlign()) {
      cluster_align = cluster_options->align();
    }
    if (cluster_options->hasBaseline()) {
      cluster_baseline = cluster_options->baseline();
    }
  }
  DrawTextInternal(text_cluster->text(), cluster_x + x, cluster_y + y,
                   CanvasRenderingContext2DState::kStrokePaintType,
                   cluster_align, cluster_baseline, text_cluster->start(),
                   text_cluster->end(), nullptr,
                   text_cluster->textMetrics()->GetFont());
}

void BaseRenderingContext2D::DrawTextInternal(
    const String& text,
    double x,
    double y,
    CanvasRenderingContext2DState::PaintType paint_type,
    V8CanvasTextAlign align,
    V8CanvasTextBaseline baseline,
    unsigned run_start,
    unsigned run_end,
    double* max_width,
    const Font* cluster_font) {
  HTMLCanvasElement* canvas = HostAsHTMLCanvasElement();
  if (canvas) {
    // The style resolution required for fonts is not available in frame-less
    // documents.
    if (!canvas->GetDocument().GetFrame()) {
      return;
    }

    // accessFont needs the style to be up to date, but updating style can cause
    // script to run, (e.g. due to autofocus) which can free the canvas (set
    // size to 0, for example), so update style before grabbing the PaintCanvas.
    canvas->GetDocument().UpdateStyleAndLayoutTreeForElement(
        canvas, DocumentUpdateReason::kCanvas);
  }

  // Abort if we don't have a paint canvas (e.g. the context was lost).
  cc::PaintCanvas* paint_canvas = GetOrCreatePaintCanvas();
  if (!paint_canvas) {
    return;
  }

  if (!std::isfinite(x) || !std::isfinite(y)) {
    return;
  }
  if (max_width && (!std::isfinite(*max_width) || *max_width <= 0)) {
    return;
  }

  // TODO(crbug.com/40191831): Remove once identifiability study is removed.
  if (identifiability_study_helper_.ShouldUpdateBuilder()) [[unlikely]] {
    identifiability_study_helper_.UpdateBuilder(
        paint_type == CanvasRenderingContext2DState::kFillPaintType
            ? CanvasOps::kFillText
            : CanvasOps::kStrokeText,
        IdentifiabilitySensitiveStringToken(text), x, y,
        max_width ? *max_width : -1);
    identifiability_study_helper_.set_encountered_sensitive_ops();
  }

  const Font* font =
      (cluster_font != nullptr) ? cluster_font : AccessFont(canvas);
  const SimpleFontData* font_data = font->PrimaryFont();
  DCHECK(font_data);
  if (!font_data) {
    return;
  }

  // FIXME: Need to turn off font smoothing.

  const CanvasRenderingContext2DState& state = GetState();
  const ComputedStyle* computed_style =
      canvas ? canvas->EnsureComputedStyle() : nullptr;
  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  TextDirection direction =
      ToTextDirection(state.GetDirection(), host, computed_style);
  bool is_rtl = direction == TextDirection::kRtl;
  bool bidi_override =
      computed_style ? IsOverride(computed_style->GetUnicodeBidi()) : false;

  PlainTextPainter* text_painter = RuntimeEnabledFeatures::CanvasTextNgEnabled(
                                       host->GetTopExecutionContext())
                                       ? &host->GetPlainTextPainter()
                                       : nullptr;
  TextRun text_run(text, direction, bidi_override, /* normalize_space */ true);
  // Draw the item text at the correct point.
  gfx::PointF location(ClampTo<float>(x), ClampTo<float>(y));
  gfx::RectF bounds;
  double font_width = 0;
  if (text_painter) {
    if (run_start == 0 && run_end == text.length()) [[likely]] {
      font_width = text_painter->ComputeInlineSize(text_run, *font, &bounds);
    } else {
      font_width = text_painter->ComputeSubInlineSize(text_run, run_start,
                                                      run_end, *font, &bounds);
    }
  } else {
    if (run_start == 0 && run_end == text.length()) [[likely]] {
      font_width = font->DeprecatedWidth(text_run, &bounds);
    } else {
      font_width =
          font->DeprecatedSubRunWidth(text_run, run_start, run_end, &bounds);
    }
  }

  bool use_max_width = (max_width && *max_width < font_width);
  double width = use_max_width ? *max_width : font_width;

  if (align == V8CanvasTextAlign::Enum::kStart) {
    align = is_rtl ? V8CanvasTextAlign(V8CanvasTextAlign::Enum::kRight)
                   : V8CanvasTextAlign(V8CanvasTextAlign::Enum::kLeft);
  } else if (align == V8CanvasTextAlign::Enum::kEnd) {
    align = is_rtl ? V8CanvasTextAlign(V8CanvasTextAlign::Enum::kLeft)
                   : V8CanvasTextAlign(V8CanvasTextAlign::Enum::kRight);
  }

  switch (align.AsEnum()) {
    case V8CanvasTextAlign::Enum::kCenter:
      location.set_x(location.x() - width / 2);
      break;
    case V8CanvasTextAlign::Enum::kRight:
      location.set_x(location.x() - width);
      break;
    default:
      break;
  }

  location.Offset(0,
                  TextMetrics::GetFontBaseline(baseline.AsEnum(), *font_data));

  bounds.Offset(location.x(), location.y());
  if (paint_type == CanvasRenderingContext2DState::kStrokePaintType) {
    InflateStrokeRect(bounds);
  }

  if (use_max_width) {
    paint_canvas->save();
    // We draw when fontWidth is 0 so compositing operations (eg, a "copy" op)
    // still work. As the width of canvas is scaled, so text can be scaled to
    // match the given maxwidth, update text location so it appears on desired
    // place.
    paint_canvas->scale(ClampTo<float>(width / font_width), 1);
    location.set_x(location.x() / ClampTo<float>(width / font_width));
  }

  // Only fill and stroke are used for DrawTextInternal.
  AddTriggersForCanvasIntervention(
      paint_type == CanvasRenderingContext2DState::kFillPaintType
          ? CanvasOperationType::kFillText
          : CanvasOperationType::kStrokeText);

  Draw<OverdrawOp::kNone>(
      [font, text = std::move(text), direction, bidi_override, location,
       run_start, run_end, canvas, text_painter](
          cc::PaintCanvas* c, const cc::PaintFlags* flags)  // draw lambda
      {
        TextRun text_run(text, direction, bidi_override,
                         /* normalize_space */ true);
        // Font::DrawType::kGlyphsAndClusters is required for printing to PDF,
        // otherwise the character to glyph mapping will not be reversible,
        // which prevents text data from being extracted from PDF files or
        // from the print preview. This is only needed in vector printing mode
        // (i.e. when rendering inside the beforeprint event listener),
        // because in all other cases the canvas is just a rectangle of pixels.
        // Note: Test coverage for this is assured by manual (non-automated)
        // web test printing/manual/canvas2d-vector-text.html
        // That test should be run manually against CLs that touch this code.
        Font::DrawType draw_type = (canvas && canvas->IsPrinting())
                                       ? Font::DrawType::kGlyphsAndClusters
                                       : Font::DrawType::kGlyphsOnly;
        if (text_painter) {
          text_painter->DrawWithBidiReorder(text_run, run_start, run_end, *font,
                                            Font::kUseFallbackIfFontNotReady,
                                            *c, location, *flags, draw_type);
        } else {
          TextRunPaintInfo text_run_paint_info(text_run);
          text_run_paint_info.from = run_start;
          text_run_paint_info.to = run_end;
          font->DeprecatedDrawBidiText(c, text_run_paint_info, location,
                                       Font::kUseFallbackIfFontNotReady, *flags,
                                       draw_type);
        }
      },
      [](const SkIRect& rect)  // overdraw test lambda
      { return false; },
      bounds, paint_type, CanvasRenderingContext2DState::kNoImage,
      CanvasPerformanceMonitor::DrawType::kText);

  if (use_max_width) {
    // Make sure that `paint_canvas` is still valid and active. Calling `Draw`
    // might reset `paint_canvas`. If that happens, `GetOrCreatePaintCanvas`
    // will create a new `paint_canvas` and return a new address. This new
    // canvas won't have the `save()` added above, so it would be invalid to
    // call `restore()` here.
    if (paint_canvas == GetOrCreatePaintCanvas()) {
      paint_canvas->restore();
    }
  }
  ValidateStateStack();
}

TextMetrics* BaseRenderingContext2D::measureText(const String& text) {
  // The style resolution required for fonts is not available in frame-less
  // documents.
  HTMLCanvasElement* canvas = HostAsHTMLCanvasElement();

  if (canvas) {
    if (!canvas->GetDocument().GetFrame()) {
      return MakeGarbageCollected<TextMetrics>();
    }

    canvas->GetDocument().UpdateStyleAndLayoutTreeForElement(
        canvas, DocumentUpdateReason::kCanvas);
  }

  const Font* font = AccessFont(canvas);

  const CanvasRenderingContext2DState& state = GetState();
  const ComputedStyle* computed_style =
      canvas ? canvas->EnsureComputedStyle() : nullptr;
  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  TextDirection direction =
      ToTextDirection(state.GetDirection(), host, computed_style);

  return MakeGarbageCollected<TextMetrics>(
      font, direction, state.GetTextBaseline().AsEnum(),
      state.GetTextAlign().AsEnum(), text,
      RuntimeEnabledFeatures::CanvasTextNgEnabled(
          host->GetTopExecutionContext())
          ? &host->GetPlainTextPainter()
          : nullptr);
}

String BaseRenderingContext2D::lang() const {
  return GetState().GetLang();
}

void BaseRenderingContext2D::setLang(const String& lang_string) {
  CanvasRenderingContext2DState& state = GetState();
  if (state.GetLang() == lang_string) {
    return;
  }

  // TODO(crbug.com/40191831): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();

  state.SetLang(lang_string);

  // If the font has been realized, reset it to account for the new lang
  // setting. When not yet realized, the lang will be accounted for the first
  // time the font is realized.
  if (state.HasRealizedFont()) {
    setFont(font());
  }
}

const LayoutLocale* BaseRenderingContext2D::LocaleFromLang() {
  String lang_string = GetState().GetLang();
  if (lang_string == kInheritString) {
    return GetCanvasRenderingContextHost()->GetLocale();
  }

  return &LayoutLocale::ValueOrDefault(
      LayoutLocale::Get(AtomicString(lang_string)));
}

void BaseRenderingContext2D::setLetterSpacing(const String& letter_spacing) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DLetterSpacing);
  // TODO(crbug.com/40191831): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();
  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }

  state.SetLetterSpacing(letter_spacing, GetFontSelector());
}

void BaseRenderingContext2D::setWordSpacing(const String& word_spacing) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DWordSpacing);
  // TODO(crbug.com/1234113): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();

  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }

  state.SetWordSpacing(word_spacing, GetFontSelector());
}

void BaseRenderingContext2D::setTextRendering(
    const V8CanvasTextRendering& text_rendering) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DTextRendering);
  // TODO(crbug.com/1234113): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();
  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }

  if (state.GetTextRendering() == text_rendering) {
    return;
  }
  state.SetTextRendering(text_rendering, GetFontSelector());
}

void BaseRenderingContext2D::setFontKerning(
    const V8CanvasFontKerning font_kerning) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DFontKerning);
  // TODO(crbug.com/1234113): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();
  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }
  FontDescription::Kerning kerning = state.GetFontKerning();
  switch (font_kerning.AsEnum()) {
    case V8CanvasFontKerning::Enum::kAuto:
      kerning = FontDescription::kAutoKerning;
      break;
    case V8CanvasFontKerning::Enum::kNone:
      kerning = FontDescription::kNoneKerning;
      break;
    case V8CanvasFontKerning::Enum::kNormal:
      kerning = FontDescription::kNormalKerning;
      break;
  }

  state.SetFontKerning(kerning, GetFontSelector());
}

void BaseRenderingContext2D::setFontStretch(
    const V8CanvasFontStretch& font_stretch) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DFontStretch);
  // TODO(crbug.com/1234113): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();
  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }

  if (state.GetFontStretch() == font_stretch) {
    return;
  }
  state.SetFontStretch(font_stretch, GetFontSelector());
}

void BaseRenderingContext2D::setFontVariantCaps(
    const V8CanvasFontVariantCaps& font_variant_caps) {
  UseCounter::Count(GetTopExecutionContext(),
                    WebFeature::kCanvasRenderingContext2DFontVariantCaps);
  // TODO(crbug.com/1234113): Instrument new canvas APIs.
  identifiability_study_helper_.set_encountered_skipped_ops();
  CanvasRenderingContext2DState& state = GetState();
  if (!state.HasRealizedFont()) {
    setFont(font());
  }
  FontDescription::FontVariantCaps variant_caps = state.GetFontVariantCaps();
  switch (font_variant_caps.AsEnum()) {
    case (V8CanvasFontVariantCaps::Enum::kNormal):
      variant_caps = FontDescription::kCapsNormal;
      break;
    case (V8CanvasFontVariantCaps::Enum::kSmallCaps):
      variant_caps = FontDescription::kSmallCaps;
      break;
    case (V8CanvasFontVariantCaps::Enum::kAllSmallCaps):
      variant_caps = FontDescription::kAllSmallCaps;
      break;
    case (V8CanvasFontVariantCaps::Enum::kPetiteCaps):
      variant_caps = FontDescription::kPetiteCaps;
      break;
    case (V8CanvasFontVariantCaps::Enum::kAllPetiteCaps):
      variant_caps = FontDescription::kAllPetiteCaps;
      break;
    case (V8CanvasFontVariantCaps::Enum::kUnicase):
      variant_caps = FontDescription::kUnicase;
      break;
    case (V8CanvasFontVariantCaps::Enum::kTitlingCaps):
      variant_caps = FontDescription::kTitlingCaps;
      break;
  }

  state.SetFontVariantCaps(variant_caps, GetFontSelector());
}

UniqueFontSelector* BaseRenderingContext2D::GetFontSelector() const {
  return nullptr;
}

V8GPUTextureFormat BaseRenderingContext2D::getTextureFormat() const {
  return FromDawnEnum(AsDawnType(GetSharedImageFormat()));
}

GPUTexture* BaseRenderingContext2D::transferToGPUTexture(
    const Canvas2dGPUTransferOption* access_options,
    ExceptionState& exception_state) {
  if (!OriginClean()) {
    exception_state.ThrowSecurityError(
        "The canvas has been tainted by cross-origin data.");
    return nullptr;
  }

  blink::GPUDevice* blink_device = access_options->getDeviceOr(nullptr);
  if (!blink_device) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "GPUDevice cannot be null.");
    return nullptr;
  }

  // Verify that we are not inside a canvas layer.
  if (layer_count_ > 0) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "A layer is currently active.");
    return nullptr;
  }

  // Verify that the usage flags are supported.
  constexpr wgpu::TextureUsage kSupportedUsageFlags =
      wgpu::TextureUsage::CopySrc | wgpu::TextureUsage::CopyDst |
      wgpu::TextureUsage::TextureBinding | wgpu::TextureUsage::RenderAttachment;

  // If `transferToGPUTexture` is called twice without an intervening call to
  // `transferBackFromGPUTexture`, the semantics are that the current ongoing
  // transfer should be discarded and the new transfer given the 2D canvas in
  // its current state (defined to be blank post-initiation of the first
  // transfer but then incorporating any canvas 2D operations that have
  // subsequently occurred on the canvas). Implement that semantics here.
  // Note that the canvas will have been made blank by the removal of the
  // CanvasResourceProvider at the initiation of the first transfer but will
  // then incorporate any canvas 2D operations that have subsequently occurred
  // on the canvas via the usage of the CanvasResourceProvider that those
  // operations would have caused to be created as the source for the new
  // transfer below.
  if (webgpu_access_texture_) {
    webgpu_access_texture_->destroy();
    webgpu_access_texture_ = nullptr;
    resource_provider_from_webgpu_access_.reset();
  }

  wgpu::TextureUsage tex_usage =
      AsDawnFlags<wgpu::TextureUsage>(access_options->usage());
  if (tex_usage & ~kSupportedUsageFlags) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Usage flags are not supported.");
    return nullptr;
  }

  // Prepare to flush the canvas to a WebGPU texture.
  FinalizeFrame(FlushReason::kWebGPUTexture);

  // We will need to access the canvas' resource provider.
  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  if (!host) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Unable to access canvas image.");
    return nullptr;
  }
  host->SetTransferToGPUTextureWasInvoked();

  // Ensure that the canvas host lives on the GPU. This call is a no-op if the
  // host is already accelerated.
  // TODO(crbug.com/340911120): if the user requested WillReadFrequently, do we
  // want to behave differently here?
  const bool host_is_accelerated = host->EnableAcceleration();

  // A texture needs to exist on the GPU. If we aren't able to enable
  // acceleration, the canvas pixels live on the CPU and we weren't able to
  // transfer them; in that case, WebGPU access is not possible.
  CanvasResourceProvider* provider = GetOrCreateCanvas2DResourceProvider();
  if (!host_is_accelerated || !provider || !provider->IsAccelerated()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Unable to transfer canvas to GPU.");
    return nullptr;
  }

  // Get the SharedImage backing this canvas resource, signaling that an
  // external write will occur. This call will ensure that a copy occurs if
  // needed for CopyOnWrite or for creation of a SharedImage with WebGPU usage
  // and will end the canvas access.
  gpu::SyncToken canvas_access_sync_token;
  bool performed_copy = false;
  scoped_refptr<gpu::ClientSharedImage> client_si =
      host->ResourceProvider()->GetBackingClientSharedImageForExternalWrite(
          &canvas_access_sync_token,
          gpu::SHARED_IMAGE_USAGE_WEBGPU_READ |
              gpu::SHARED_IMAGE_USAGE_WEBGPU_WRITE,
          &performed_copy);
  if (access_options->requireZeroCopy() && performed_copy) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "Transferring canvas to GPU was not zero-copy.");
    return nullptr;
  }

  // If the backing SharedImage is not available (e.g., because the GPU context
  // has been lost), zero-copy transfer is not possible.
  if (!client_si) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "Unable to transfer canvas to GPU.");
    return nullptr;
  }

  wgpu::TextureFormat dawn_format = AsDawnType(client_si->format());
  wgpu::TextureDescriptor desc = {
      .usage = tex_usage,
      .size = {base::checked_cast<uint32_t>(client_si->size().width()),
               base::checked_cast<uint32_t>(client_si->size().height())},
      .format = dawn_format,
  };

  // Create a WebGPU texture backed by the resource's SharedImage.
  scoped_refptr<WebGPUMailboxTexture> texture =
      WebGPUMailboxTexture::FromExistingSharedImage(
          blink_device->GetDawnControlClient(), blink_device->GetHandle(), desc,
          client_si,
          // Ensure that WebGPU waits for the 2D canvas service-side operations
          // on this resource to complete.
          canvas_access_sync_token);

  webgpu_access_texture_ = MakeGarbageCollected<GPUTexture>(
      blink_device, dawn_format, tex_usage, std::move(texture),
      access_options->getLabelOr(String()));

  // We take away the canvas' resource provider here, which will cause the
  // canvas to be treated as a brand new surface if additional draws occur.
  // It also gives us a mechanism to detect post-transfer-out draws, which is
  // used in `transferBackFromWebGPU` to raise an exception.
  resource_provider_from_webgpu_access_ =
      host->ReplaceResourceProvider(nullptr);

  // The user isn't obligated to ever transfer back, which means this resource
  // provider might stick around for while. Jettison any unnecessary resources.
  resource_provider_from_webgpu_access_->ClearUnusedResources();

  WillDraw(SkIRect::MakeXYWH(0, 0, Width(), Height()),
           CanvasPerformanceMonitor::DrawType::kOther);

  return webgpu_access_texture_;
}

void BaseRenderingContext2D::transferBackFromGPUTexture(
    ExceptionState& exception_state) {
  // If the context is lost or doesn't exist, this call should be a no-op.
  // We don't want to throw an exception or attempt any changes if
  // `transferBackFromWebGPU` is called during teardown.
  CanvasRenderingContextHost* host = GetCanvasRenderingContextHost();
  if (!host || isContextLost()) [[unlikely]] {
    return;
  }

  // Prevent unbalanced calls to transferBackFromGPUTexture without an earlier
  // call to transferToGPUTexture.
  if (!webgpu_access_texture_ || !resource_provider_from_webgpu_access_) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "This canvas is not currently in use by WebGPU.");
    webgpu_access_texture_ = nullptr;
    resource_provider_from_webgpu_access_ = nullptr;
    return;
  }

  // If this canvas already has a resource provider, this means that drawing has
  // occurred after `transferToWebGPU`. We disallow transferring back in this
  // case, and raise an exception instead.
  if (host->ResourceProvider()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "The canvas was touched after transferToGPUTexture.");
    webgpu_access_texture_ = nullptr;
    resource_provider_from_webgpu_access_ = nullptr;
    return;
  }

  // If the caller explicitly destroyed the WebGPU access texture, there is
  // nothing to transfer.
  if (webgpu_access_texture_->IsDestroyed()) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      "The texture has been destroyed.");
    webgpu_access_texture_ = nullptr;
    resource_provider_from_webgpu_access_ = nullptr;
    return;
  }

  // Restore the canvas' resource provider back onto the canvas host,
  // surrendering our temporary ownership of the provider.
  CanvasResourceProvider* resource_provider =
      resource_provider_from_webgpu_access_.get();
  host->ReplaceResourceProvider(
      std::move(resource_provider_from_webgpu_access_));
  resource_provider->SetCanvasResourceHost(host);

  // Disassociate the WebGPU texture from the SharedImage to end its
  // SharedImage access.
  gpu::SyncToken webgpu_completion_sync_token =
      webgpu_access_texture_->GetMailboxTexture()->Dissociate();

  // Signal to the resource provider that the external write to the resource has
  // completed to ensure that it waits on the WebGPU service-side operations to
  // complete before any further canvas operations occur.
  resource_provider->EndExternalWrite(webgpu_completion_sync_token);

  // Destroy the WebGPU texture to prevent it from being used after
  // `transferBackFromGPUTexture`.
  webgpu_access_texture_->destroy();

  // We are finished with the WebGPU texture and its associated device.
  webgpu_access_texture_ = nullptr;

  WillDraw(SkIRect::MakeXYWH(0, 0, Width(), Height()),
           CanvasPerformanceMonitor::DrawType::kOther);
}

int BaseRenderingContext2D::LayerCount() const {
  return Canvas2DRecorderContext::LayerCount();
}

}  // namespace blink