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
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
cc / trees / layer_tree_host.cc [blame]
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/trees/layer_tree_host.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include "base/atomic_sequence_num.h"
#include "base/auto_reset.h"
#include "base/command_line.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/not_fatal_until.h"
#include "base/numerics/safe_math.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/common/task_annotator.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/timer/elapsed_timer.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/traced_value.h"
#include "base/tracing/protos/chrome_track_event.pbzero.h"
#include "base/types/optional_ref.h"
#include "build/build_config.h"
#include "cc/base/devtools_instrumentation.h"
#include "cc/base/features.h"
#include "cc/base/histograms.h"
#include "cc/base/math_util.h"
#include "cc/debug/rendering_stats_instrumentation.h"
#include "cc/input/browser_controls_offset_tags_info.h"
#include "cc/input/layer_selection_bound.h"
#include "cc/input/overscroll_behavior.h"
#include "cc/input/page_scale_animation.h"
#include "cc/layers/heads_up_display_layer.h"
#include "cc/layers/heads_up_display_layer_impl.h"
#include "cc/layers/layer.h"
#include "cc/layers/painted_scrollbar_layer.h"
#include "cc/metrics/ukm_manager.h"
#include "cc/metrics/ukm_smoothness_data.h"
#include "cc/paint/paint_worklet_layer_painter.h"
#include "cc/resources/ui_resource_manager.h"
#include "cc/tiles/raster_dark_mode_filter.h"
#include "cc/trees/clip_node.h"
#include "cc/trees/commit_state.h"
#include "cc/trees/compositor_commit_data.h"
#include "cc/trees/draw_property_utils.h"
#include "cc/trees/effect_node.h"
#include "cc/trees/layer_tree_host_client.h"
#include "cc/trees/layer_tree_host_impl.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/mobile_optimized_viewport_util.h"
#include "cc/trees/mutator_host.h"
#include "cc/trees/paint_holding_reason.h"
#include "cc/trees/property_tree_builder.h"
#include "cc/trees/proxy_main.h"
#include "cc/trees/render_frame_metadata_observer.h"
#include "cc/trees/scroll_node.h"
#include "cc/trees/single_thread_proxy.h"
#include "cc/trees/swap_promise_manager.h"
#include "cc/trees/transform_node.h"
#include "cc/trees/tree_synchronizer.h"
#include "cc/view_transition/view_transition_request.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/tracing/public/cpp/perfetto/macros.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/vector2d_conversions.h"
#include "ui/gfx/presentation_feedback.h"
#include "ui/latency/latency_info.h"
namespace {
static base::AtomicSequenceNumber s_layer_tree_host_sequence_number;
static base::AtomicSequenceNumber s_image_decode_sequence_number;
} // namespace
namespace cc {
namespace {
bool AreEmbedTokensEqual(const viz::LocalSurfaceId& lsi1,
const viz::LocalSurfaceId& lsi2) {
return lsi1.embed_token() == lsi2.embed_token();
}
bool AreParentSequencesEqual(const viz::LocalSurfaceId& lsi1,
const viz::LocalSurfaceId& lsi2) {
return lsi1.parent_sequence_number() == lsi2.parent_sequence_number();
}
} // namespace
LayerTreeHost::InitParams::InitParams() = default;
LayerTreeHost::InitParams::~InitParams() = default;
LayerTreeHost::InitParams::InitParams(InitParams&&) = default;
LayerTreeHost::InitParams& LayerTreeHost::InitParams::operator=(InitParams&&) =
default;
LayerTreeHost::ScrollAnimationState::ScrollAnimationState() = default;
LayerTreeHost::ScrollAnimationState::~ScrollAnimationState() = default;
std::unique_ptr<LayerTreeHost> LayerTreeHost::CreateThreaded(
scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
InitParams params) {
DCHECK(params.settings);
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner =
params.main_task_runner;
DCHECK(main_task_runner);
DCHECK(impl_task_runner);
auto layer_tree_host = base::WrapUnique(
new LayerTreeHost(std::move(params), CompositorMode::THREADED));
layer_tree_host->InitializeThreaded(std::move(main_task_runner),
std::move(impl_task_runner));
return layer_tree_host;
}
std::unique_ptr<LayerTreeHost> LayerTreeHost::CreateSingleThreaded(
LayerTreeHostSingleThreadClient* single_thread_client,
InitParams params) {
DCHECK(params.settings);
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner =
params.main_task_runner;
auto layer_tree_host = base::WrapUnique(
new LayerTreeHost(std::move(params), CompositorMode::SINGLE_THREADED));
layer_tree_host->InitializeSingleThreaded(single_thread_client,
std::move(main_task_runner));
return layer_tree_host;
}
LayerTreeHost::LayerTreeHost(InitParams params, CompositorMode mode)
: micro_benchmark_controller_(this),
image_worker_task_runner_(std::move(params.image_worker_task_runner)),
ukm_recorder_factory_(std::move(params.ukm_recorder_factory)),
compositor_mode_(mode),
ui_resource_manager_(std::make_unique<UIResourceManager>()),
client_(params.client),
scheduling_client_(params.scheduling_client),
rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
pending_commit_state_(std::make_unique<CommitState>()),
thread_unsafe_commit_state_(params.mutator_host, *this),
settings_(*params.settings),
id_(s_layer_tree_host_sequence_number.GetNext() + 1),
task_graph_runner_(params.task_graph_runner),
mutator_host_(params.mutator_host),
dark_mode_filter_(params.dark_mode_filter) {
DCHECK(task_graph_runner_);
DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_);
pending_commit_state_->needs_gpu_rasterization_histogram =
(mode == CompositorMode::THREADED);
pending_commit_state_->needs_full_tree_sync = true;
pending_commit_state_->debug_state = settings_.initial_debug_state;
rendering_stats_instrumentation_->set_record_rendering_stats(
pending_commit_state_->debug_state.RecordRenderingStats());
}
bool LayerTreeHost::IsMobileOptimized() const {
gfx::SizeF scrollable_viewport_size;
const auto* inner_node = property_trees()->scroll_tree().Node(
pending_commit_state()->viewport_property_ids.inner_scroll);
if (!inner_node)
scrollable_viewport_size = gfx::SizeF();
else
scrollable_viewport_size = gfx::ScaleSize(
gfx::SizeF(inner_node->container_bounds),
1.0f / (pending_commit_state()->external_page_scale_factor *
page_scale_factor()));
gfx::SizeF scrollable_size;
const auto* scroll_node = property_trees()->scroll_tree().Node(
pending_commit_state()->viewport_property_ids.outer_scroll);
if (!scroll_node) {
DCHECK(!inner_node);
scrollable_size = gfx::SizeF();
} else {
const auto& scroll_tree = property_trees()->scroll_tree();
auto size = scroll_tree.scroll_bounds(scroll_node->id);
size.SetToMax(gfx::SizeF(scroll_tree.container_bounds(scroll_node->id)));
scrollable_size = size;
}
return util::IsMobileOptimized(
min_page_scale_factor(), max_page_scale_factor(), page_scale_factor(),
scrollable_viewport_size, scrollable_size,
pending_commit_state()->is_viewport_mobile_optimized);
}
void LayerTreeHost::InitializeThreaded(
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner) {
task_runner_provider_ =
TaskRunnerProvider::Create(main_task_runner, impl_task_runner);
std::unique_ptr<ProxyMain> proxy_main =
std::make_unique<ProxyMain>(this, task_runner_provider_.get());
InitializeProxy(std::move(proxy_main));
}
void LayerTreeHost::InitializeSingleThreaded(
LayerTreeHostSingleThreadClient* single_thread_client,
scoped_refptr<base::SingleThreadTaskRunner> main_task_runner) {
task_runner_provider_ = TaskRunnerProvider::Create(main_task_runner, nullptr);
InitializeProxy(SingleThreadProxy::Create(this, single_thread_client,
task_runner_provider_.get()));
}
void LayerTreeHost::InitializeForTesting(
std::unique_ptr<TaskRunnerProvider> task_runner_provider,
std::unique_ptr<Proxy> proxy_for_testing) {
task_runner_provider_ = std::move(task_runner_provider);
InitializeProxy(std::move(proxy_for_testing));
}
void LayerTreeHost::SetTaskRunnerProviderForTesting(
std::unique_ptr<TaskRunnerProvider> task_runner_provider) {
DCHECK(!task_runner_provider_);
task_runner_provider_ = std::move(task_runner_provider);
// This is done in InitializeProxy(), but not all tests call it.
mutator_host_->SetMutatorHostClient(this);
}
void LayerTreeHost::SetUIResourceManagerForTesting(
std::unique_ptr<UIResourceManager> ui_resource_manager) {
ui_resource_manager_ = std::move(ui_resource_manager);
}
void LayerTreeHost::InitializeProxy(std::unique_ptr<Proxy> proxy) {
TRACE_EVENT0("cc", "LayerTreeHost::InitializeForReal");
DCHECK(task_runner_provider_);
DCHECK(IsMainThread());
mutator_host_->SetMutatorHostClient(this);
proxy_ = std::move(proxy);
proxy_->Start();
UpdateDeferMainFrameUpdateInternal();
}
LayerTreeHost::~LayerTreeHost() {
// Track when we're inside a main frame to see if compositor is being
// destroyed midway which causes a crash. crbug.com/895883
CHECK(!inside_main_frame_);
DCHECK(!in_commit());
TRACE_EVENT0("cc", "LayerTreeHost::~LayerTreeHost");
// Clear any references into the LayerTreeHost.
mutator_host()->SetMutatorHostClient(nullptr);
if (root_layer()) {
root_layer()->SetLayerTreeHost(nullptr);
// The root layer must be destroyed before the layer tree. We've made a
// contract with our animation controllers that the animation_host will
// outlive them, and we must make good.
thread_unsafe_commit_state().root_layer = nullptr;
}
// Fail any pending image decodes.
for (auto& pair : pending_image_decodes_)
std::move(pair.second).Run(false);
if (proxy_) {
proxy_->Stop();
// Proxy must be destroyed before the Task Runner Provider.
proxy_ = nullptr;
}
}
int LayerTreeHost::GetId() const {
return id_;
}
int LayerTreeHost::SourceFrameNumber() const {
return pending_commit_state()->source_frame_number;
}
UIResourceManager* LayerTreeHost::GetUIResourceManager() {
DCHECK(IsMainThread());
return ui_resource_manager_.get();
}
TaskRunnerProvider* LayerTreeHost::GetTaskRunnerProvider() {
return task_runner_provider_.get();
}
bool LayerTreeHost::IsMainThread() const {
return task_runner_provider_ && task_runner_provider_->IsMainThread();
}
bool LayerTreeHost::IsImplThread() const {
return task_runner_provider_ && task_runner_provider_->IsImplThread();
}
bool LayerTreeHost::IsOwnerThread() const {
return task_runner_provider_->MainThreadTaskRunner()
->RunsTasksInCurrentSequence();
}
bool LayerTreeHost::InProtectedSequence() const {
return in_commit();
}
SwapPromiseManager* LayerTreeHost::GetSwapPromiseManager() {
DCHECK(IsMainThread());
return &swap_promise_manager_;
}
std::unique_ptr<EventsMetricsManager::ScopedMonitor>
LayerTreeHost::GetScopedEventMetricsMonitor(
EventsMetricsManager::ScopedMonitor::DoneCallback done_callback) {
DCHECK(IsMainThread());
return events_metrics_manager_.GetScopedMonitor(std::move(done_callback));
}
void LayerTreeHost::ClearEventsMetrics() {
// Take events metrics and drop them.
DCHECK(IsMainThread());
events_metrics_manager_.TakeSavedEventsMetrics();
}
const LayerTreeSettings& LayerTreeHost::GetSettings() const {
DCHECK(IsMainThread());
return settings_;
}
void LayerTreeHost::QueueSwapPromise(
std::unique_ptr<SwapPromise> swap_promise) {
DCHECK(IsMainThread());
swap_promise_manager_.QueueSwapPromise(std::move(swap_promise));
}
void LayerTreeHost::WillBeginMainFrame() {
DCHECK(IsMainThread());
inside_main_frame_ = true;
if (!GetSettings().is_layer_tree_for_ui) {
devtools_instrumentation::WillBeginMainThreadFrame(GetId(),
SourceFrameNumber());
}
client_->WillBeginMainFrame();
}
void LayerTreeHost::DidBeginMainFrame() {
DCHECK(IsMainThread());
inside_main_frame_ = false;
client_->DidBeginMainFrame();
}
void LayerTreeHost::BeginMainFrameNotExpectedSoon() {
DCHECK(IsMainThread());
client_->BeginMainFrameNotExpectedSoon();
}
void LayerTreeHost::BeginMainFrameNotExpectedUntil(base::TimeTicks time) {
DCHECK(IsMainThread());
client_->BeginMainFrameNotExpectedUntil(time);
}
void LayerTreeHost::BeginMainFrame(const viz::BeginFrameArgs& args) {
DCHECK(IsMainThread());
client_->BeginMainFrame(args);
}
const LayerTreeDebugState& LayerTreeHost::GetDebugState() const {
return pending_commit_state()->debug_state;
}
void LayerTreeHost::RequestMainFrameUpdate(bool report_metrics) {
DCHECK(IsMainThread());
client_->UpdateLayerTreeHost();
if (report_metrics)
pending_commit_state()->begin_main_frame_metrics =
client_->GetBeginMainFrameMetrics();
else
pending_commit_state()->begin_main_frame_metrics.reset();
}
void LayerTreeHost::ImageDecodesFinished(
const std::vector<std::pair<int, bool>>& results) {
for (const auto& pair : results) {
NotifyImageDecodeFinished(pair.first, pair.second);
}
}
void LayerTreeHost::SetNextCommitWaitsForActivation() {
pending_commit_state()->commit_waits_for_activation = true;
}
std::unique_ptr<CommitState> LayerTreeHost::WillCommit(
std::unique_ptr<CompletionEvent> completion,
bool has_updates) {
DCHECK(IsMainThread());
DCHECK(!commit_completion_event_);
std::unique_ptr<CommitState> result;
if (has_updates)
result = ActivateCommitState();
swap_promise_manager_.WillCommit();
mutator_host()->RemoveStaleTimelines();
client_->WillCommit(has_updates ? *result : *pending_commit_state());
pending_commit_state()->source_frame_number++;
commit_completion_event_ = std::move(completion);
return result;
}
std::unique_ptr<CommitState> LayerTreeHost::ActivateCommitState() {
DCHECK(IsMainThread());
DCHECK(pending_commit_state());
// Pull state not stored directly on LayerTreeHost
pending_commit_state()->event_metrics =
events_metrics_manager_.TakeSavedEventsMetrics();
pending_commit_state()->swap_promises =
GetSwapPromiseManager()->TakeSwapPromises();
pending_commit_state()->ui_resource_request_queue =
ui_resource_manager_->TakeUIResourcesRequests();
pending_commit_state()->ui_resource_sizes =
ui_resource_manager_->GetUIResourceSizes();
pending_commit_state()->benchmarks =
micro_benchmark_controller_.CreateImplBenchmarks();
// Snapshot PropertyTrees change tracking state prior to resetting it.
property_trees()->GetChangeState(
pending_commit_state()->property_trees_change_state);
property_trees()->ResetAllChangeTracking();
auto active_commit_state = std::move(pending_commit_state_);
pending_commit_state_ = std::make_unique<CommitState>(*active_commit_state);
return active_commit_state;
}
void LayerTreeHost::WaitForProtectedSequenceCompletion() const {
if (compositor_mode_ == CompositorMode::SINGLE_THREADED)
return;
WaitForCommitCompletion(/* for_protected_sequence */ true);
}
void LayerTreeHost::WaitForCommitCompletion(bool for_protected_sequence) const {
DCHECK(IsMainThread());
if (commit_completion_event_) {
TRACE_EVENT0("cc", "LayerTreeHost::WaitForCommitCompletion");
commit_completion_event_->Wait();
commit_completion_event_ = nullptr;
}
}
void LayerTreeHost::UpdateDeferMainFrameUpdateInternal() {
DCHECK(IsMainThread());
proxy_->SetDeferMainFrameUpdate(MainFrameUpdatesAreDeferred());
}
bool LayerTreeHost::MainFrameUpdatesAreDeferred() const {
return defer_main_frame_update_count_ > 0 ||
!pending_commit_state()->local_surface_id_from_parent.is_valid();
}
bool LayerTreeHost::IsUsingLayerLists() const {
return settings_.use_layer_lists;
}
void LayerTreeHost::CommitComplete(int source_frame_number,
const CommitTimestamps& commit_timestamps) {
DCHECK(IsMainThread());
// At this point, commit_completion_event_ could be for the *next* commit, and
// may not yet have been signaled. If we blocked on a protected sequence
// during the commit then the completion event for the frame will have been
// reset, which in turn unblocks starting a commit for the next frame. If we
// have a commit completion event that has been signaled, it means that we
// have not been blocked on a protected sequence during the commit. In this
// case, we still need to call WaitForCommitCompletion, which performs the
// flag reset; however, the Wait will be non-blocking given that the event was
// already signaled.
if (!in_commit()) {
mutator_host()->RemoveStaleTimelines();
}
if (commit_completion_event_ && commit_completion_event_->IsSignaled())
WaitForCommitCompletion(/* for_protected_sequence */ false);
client_->DidCommit(source_frame_number, commit_timestamps.start,
commit_timestamps.finish);
if (did_complete_scale_animation_) {
client_->DidCompletePageScaleAnimation(source_frame_number);
did_complete_scale_animation_ = false;
}
}
void LayerTreeHost::NotifyImageDecodeFinished(int request_id,
bool decode_succeeded) {
DCHECK(IsMainThread());
auto it = pending_image_decodes_.find(request_id);
CHECK(it != pending_image_decodes_.end(), base::NotFatalUntil::M130);
// Issue stored callback and remove them from the pending list.
std::move(it->second).Run(decode_succeeded);
pending_image_decodes_.erase(it);
}
void LayerTreeHost::NotifyTransitionRequestsFinished(
const uint32_t sequence_id,
const viz::ViewTransitionElementResourceRects& rects) {
DCHECK(IsMainThread());
// TODO(vmpstr): This might also be a good spot to expire long standing
// requests if they were not finished.
auto it = view_transition_callbacks_.find(sequence_id);
if (it == view_transition_callbacks_.end()) {
return;
}
std::move(it->second).Run(rects);
view_transition_callbacks_.erase(it);
}
void LayerTreeHost::SetLayerTreeFrameSink(
std::unique_ptr<LayerTreeFrameSink> surface) {
DCHECK(IsMainThread());
TRACE_EVENT0("cc", "LayerTreeHost::SetLayerTreeFrameSink");
DCHECK(surface);
DCHECK(!new_layer_tree_frame_sink_);
new_layer_tree_frame_sink_ = std::move(surface);
proxy_->SetLayerTreeFrameSink(new_layer_tree_frame_sink_.get());
}
std::unique_ptr<LayerTreeFrameSink> LayerTreeHost::ReleaseLayerTreeFrameSink() {
DCHECK(IsMainThread());
DCHECK(!visible_);
DidLoseLayerTreeFrameSink();
proxy_->ReleaseLayerTreeFrameSink();
return std::move(current_layer_tree_frame_sink_);
}
void LayerTreeHost::RequestNewLayerTreeFrameSink() {
DCHECK(IsMainThread());
client_->RequestNewLayerTreeFrameSink();
should_warm_up_ = false;
}
void LayerTreeHost::DidInitializeLayerTreeFrameSink() {
DCHECK(IsMainThread());
DCHECK(new_layer_tree_frame_sink_);
current_layer_tree_frame_sink_ = std::move(new_layer_tree_frame_sink_);
client_->DidInitializeLayerTreeFrameSink();
}
void LayerTreeHost::DidFailToInitializeLayerTreeFrameSink() {
DCHECK(IsMainThread());
DCHECK(new_layer_tree_frame_sink_);
// Note: It is safe to drop all output surface references here as
// LayerTreeHostImpl will not keep a pointer to either the old or
// new LayerTreeFrameSink after failing to initialize the new one.
current_layer_tree_frame_sink_ = nullptr;
new_layer_tree_frame_sink_ = nullptr;
client_->DidFailToInitializeLayerTreeFrameSink();
}
std::unique_ptr<LayerTreeHostImpl> LayerTreeHost::CreateLayerTreeHostImpl(
LayerTreeHostImplClient* client) {
// This method is special: it should be the only LayerTreeHost method that
// runs on the impl thread. As such, it cannot use LayerTreeHost getter
// methods that enforce DCHECK(IsMainThread()). Because it only ever runs when
// the main thread is blocked, it's safe to access member variables directly.
DCHECK(IsImplThread());
DCHECK(task_runner_provider_->IsMainThreadBlocked());
return CreateLayerTreeHostImplInternal(
client, thread_unsafe_commit_state_.mutator_host, settings_,
task_runner_provider_.get(), dark_mode_filter_, id_, task_graph_runner_,
image_worker_task_runner_, scheduling_client_,
rendering_stats_instrumentation_.get(), ukm_recorder_factory_,
compositor_delegate_weak_ptr_);
}
std::unique_ptr<LayerTreeHostImpl>
LayerTreeHost::CreateLayerTreeHostImplInternal(
LayerTreeHostImplClient* client,
MutatorHost* mutator_host,
const LayerTreeSettings& settings,
TaskRunnerProvider* task_runner_provider,
raw_ptr<RasterDarkModeFilter>& dark_mode_filter,
int id,
raw_ptr<TaskGraphRunner>& task_graph_runner,
scoped_refptr<base::SequencedTaskRunner> image_worker_task_runner,
LayerTreeHostSchedulingClient* scheduling_client,
RenderingStatsInstrumentation* rendering_stats_instrumentation,
std::unique_ptr<UkmRecorderFactory>& ukm_recorder_factory,
base::WeakPtr<CompositorDelegateForInput>& compositor_delegate_weak_ptr) {
std::unique_ptr<MutatorHost> mutator_host_impl =
mutator_host->CreateImplInstance();
if (!settings.scroll_animation_duration_for_testing.is_zero()) {
mutator_host->SetScrollAnimationDurationForTesting( // IN-TEST
settings.scroll_animation_duration_for_testing);
}
std::unique_ptr<LayerTreeHostImpl> host_impl = LayerTreeHostImpl::Create(
settings, client, task_runner_provider, rendering_stats_instrumentation,
task_graph_runner, std::move(mutator_host_impl), dark_mode_filter, id,
std::move(image_worker_task_runner), scheduling_client);
if (ukm_recorder_factory) {
host_impl->InitializeUkm(ukm_recorder_factory->CreateRecorder());
ukm_recorder_factory.reset();
}
task_graph_runner = nullptr;
dark_mode_filter = nullptr;
compositor_delegate_weak_ptr = host_impl->AsWeakPtr();
return host_impl;
}
void LayerTreeHost::DidLoseLayerTreeFrameSink() {
TRACE_EVENT0("cc", "LayerTreeHost::DidLoseLayerTreeFrameSink");
DCHECK(task_runner_provider_->IsMainThread());
SetNeedsCommit();
}
ScopedDeferMainFrameUpdate::ScopedDeferMainFrameUpdate(LayerTreeHost* host)
: host_(host->weak_ptr_factory_.GetWeakPtr()) {
host->defer_main_frame_update_count_++;
host->UpdateDeferMainFrameUpdateInternal();
}
ScopedDeferMainFrameUpdate::~ScopedDeferMainFrameUpdate() {
LayerTreeHost* host = host_.get();
if (host) {
DCHECK_GT(host->defer_main_frame_update_count_, 0u);
if (--host->defer_main_frame_update_count_ == 0)
host->UpdateDeferMainFrameUpdateInternal();
}
}
std::unique_ptr<ScopedDeferMainFrameUpdate>
LayerTreeHost::DeferMainFrameUpdate() {
DCHECK(IsMainThread());
return std::make_unique<ScopedDeferMainFrameUpdate>(this);
}
ScopedPauseRendering::ScopedPauseRendering(LayerTreeHost* host)
: host_(host->weak_ptr_factory_.GetWeakPtr()) {
host->pause_rendering_count_++;
host->proxy_->SetPauseRendering(true);
}
ScopedPauseRendering::~ScopedPauseRendering() {
LayerTreeHost* host = host_.get();
if (host) {
DCHECK_GT(host->pause_rendering_count_, 0u);
if (--host->pause_rendering_count_ == 0) {
host->SetNeedsCommit();
host->proxy_->SetPauseRendering(false);
}
}
}
std::unique_ptr<ScopedPauseRendering> LayerTreeHost::PauseRendering() {
DCHECK(IsMainThread());
return std::make_unique<ScopedPauseRendering>(this);
}
void LayerTreeHost::OnDeferMainFrameUpdatesChanged(bool defer_status) {
DCHECK(IsMainThread());
client_->OnDeferMainFrameUpdatesChanged(defer_status);
}
bool LayerTreeHost::StartDeferringCommits(base::TimeDelta timeout,
PaintHoldingReason reason) {
DCHECK(IsMainThread());
return proxy_->StartDeferringCommits(timeout, reason);
}
void LayerTreeHost::StopDeferringCommits(PaintHoldingCommitTrigger trigger) {
DCHECK(IsMainThread());
proxy_->StopDeferringCommits(trigger);
}
bool LayerTreeHost::IsDeferringCommits() const {
DCHECK(IsMainThread());
return proxy_->IsDeferringCommits();
}
bool LayerTreeHost::IsRenderingPaused() const {
return pause_rendering_count_ > 0;
}
void LayerTreeHost::OnDeferCommitsChanged(
bool defer_status,
PaintHoldingReason reason,
std::optional<PaintHoldingCommitTrigger> trigger) {
DCHECK(IsMainThread());
client_->OnDeferCommitsChanged(defer_status, reason, trigger);
}
DISABLE_CFI_PERF
void LayerTreeHost::SetNeedsAnimate() {
DCHECK(IsMainThread());
proxy_->SetNeedsAnimate();
swap_promise_manager_.NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
}
void LayerTreeHost::SetNeedsAnimateIfNotInsideMainFrame() {
DCHECK(IsMainThread());
if (!inside_main_frame_)
SetNeedsAnimate();
}
DISABLE_CFI_PERF
void LayerTreeHost::SetNeedsUpdateLayers() {
DCHECK(IsMainThread());
proxy_->SetNeedsUpdateLayers();
swap_promise_manager_.NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
}
void LayerTreeHost::SetNeedsCommit() {
DCHECK(IsMainThread());
proxy_->SetNeedsCommit();
swap_promise_manager_.NotifyLatencyInfoSwapPromiseMonitors();
events_metrics_manager_.SaveActiveEventMetrics();
}
void LayerTreeHost::OnCommitRequested() {
client_->OnCommitRequested();
}
void LayerTreeHost::SetTargetLocalSurfaceId(
const viz::LocalSurfaceId& target_local_surface_id) {
DCHECK(IsMainThread());
proxy_->SetTargetLocalSurfaceId(target_local_surface_id);
}
bool LayerTreeHost::RequestedMainFramePending() const {
DCHECK(IsMainThread());
return proxy_->RequestedAnimatePending();
}
void LayerTreeHost::SetNeedsRecalculateRasterScales() {
pending_commit_state()->next_commit_forces_recalculate_raster_scales = true;
proxy_->SetNeedsCommit();
}
void LayerTreeHost::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
DCHECK(IsMainThread());
proxy_->SetNeedsRedraw(damage_rect);
}
bool LayerTreeHost::CommitRequested() const {
DCHECK(IsMainThread());
return proxy_->CommitRequested();
}
void LayerTreeHost::SetNeedsCommitWithForcedRedraw() {
pending_commit_state()->next_commit_forces_redraw = true;
// This method is used by tests to ensure a commit before grabbing a screen
// shot or processing input, so do not defer the commit.
StopDeferringCommits(PaintHoldingCommitTrigger::kFeatureDisabled);
proxy_->SetNeedsCommit();
}
void LayerTreeHost::SetDebugState(const LayerTreeDebugState& new_debug_state) {
if (pending_commit_state()->debug_state == new_debug_state) {
return;
}
pending_commit_state()->debug_state = new_debug_state;
rendering_stats_instrumentation_->set_record_rendering_stats(
pending_commit_state()->debug_state.RecordRenderingStats());
SetNeedsCommit();
}
void LayerTreeHost::ApplyPageScaleDeltaFromImplSide(float page_scale_delta) {
DCHECK(IsMainThread());
DCHECK(syncing_deltas_for_test_ || CommitRequested());
if (page_scale_delta == 1.f)
return;
float page_scale =
pending_commit_state()->page_scale_factor * page_scale_delta;
SetPageScaleFromImplSide(page_scale);
}
void LayerTreeHost::SetVisible(bool visible) {
DCHECK(IsMainThread());
if (visible_ == visible)
return;
visible_ = visible;
// If the page becomes invisible, corresponding metrics will be discarded
// because they are invalid. The metrics will be measured when the page
// becomes visible again.
if (!visible_) {
ClearEventsMetrics();
}
proxy_->SetVisible(visible);
}
bool LayerTreeHost::IsVisible() const {
DCHECK(IsMainThread());
return visible_;
}
void LayerTreeHost::SetShouldWarmUp() {
DCHECK(IsMainThread());
CHECK(base::FeatureList::IsEnabled(features::kWarmUpCompositor));
should_warm_up_ = true;
proxy_->SetShouldWarmUp();
}
bool LayerTreeHost::ShouldWarmUp() const {
DCHECK(IsMainThread());
if (!base::FeatureList::IsEnabled(features::kWarmUpCompositor)) {
return false;
}
return should_warm_up_;
}
void LayerTreeHost::LayoutAndUpdateLayers() {
DCHECK(IsSingleThreaded());
// This function is only valid when not using the scheduler.
DCHECK(!settings_.single_thread_proxy_scheduler);
RequestMainFrameUpdate(false);
UpdateLayers();
}
void LayerTreeHost::CompositeForTest(base::TimeTicks frame_begin_time,
bool raster,
base::OnceClosure callback) {
DCHECK(!settings_.single_thread_proxy_scheduler);
proxy_->CompositeImmediatelyForTest(frame_begin_time, raster, // IN-TEST
std::move(callback));
}
bool LayerTreeHost::UpdateLayers() {
if (!root_layer()) {
property_trees()->clear();
pending_commit_state()->viewport_property_ids = ViewportPropertyIds();
return false;
}
DCHECK(!root_layer()->parent());
base::ElapsedTimer timer;
client_->WillUpdateLayers();
bool result = DoUpdateLayers();
client_->DidUpdateLayers();
micro_benchmark_controller_.DidUpdateLayers();
base::TimeDelta elapsed_delta = timer.Elapsed();
if (pending_commit_state()->begin_main_frame_metrics) {
pending_commit_state()->begin_main_frame_metrics->update_layers =
elapsed_delta;
}
if (const char* client_name = GetClientNameForMetrics()) {
auto elapsed = elapsed_delta.InMicroseconds();
// The histogram name must be a constant for the macro to work.
// GetClientNameForMetrics() guarantees to always return the same string or
// null
UMA_HISTOGRAM_COUNTS_10M(
base::StringPrintf("Compositing.%s.LayersUpdateTime", client_name),
elapsed);
}
return result;
}
void LayerTreeHost::DidPresentCompositorFrame(
uint32_t frame_token,
std::vector<PresentationTimeCallbackBuffer::Callback>
presentation_callbacks,
std::vector<PresentationTimeCallbackBuffer::SuccessfulCallbackWithDetails>
successful_presentation_callbacks,
const viz::FrameTimingDetails& frame_timing_details) {
DCHECK(IsMainThread());
for (auto& callback : presentation_callbacks)
std::move(callback).Run(frame_timing_details.presentation_feedback);
for (auto& callback : successful_presentation_callbacks)
std::move(callback).Run(frame_timing_details);
client_->DidPresentCompositorFrame(frame_token, frame_timing_details);
}
void LayerTreeHost::DidCompletePageScaleAnimation() {
DCHECK(IsMainThread());
did_complete_scale_animation_ = true;
}
std::string LayerTreeHost::LayersAsString() const {
std::string layers;
for (const auto* layer : *this)
layers += layer->ToString() + "\n";
return layers;
}
bool LayerTreeHost::CaptureContent(std::vector<NodeInfo>* content) const {
DCHECK(IsMainThread());
if (visual_device_viewport_intersection_rect_.IsEmpty())
return false;
gfx::Rect rect =
gfx::Rect(visual_device_viewport_intersection_rect_.width(),
visual_device_viewport_intersection_rect_.height());
for (const auto* layer : *this) {
// Normally, the node won't be drawn in multiple layers, even it is, such as
// text strokes, the visual rect don't have too much different.
layer->CaptureContent(rect, content);
}
return true;
}
void LayerTreeHost::DidObserveFirstScrollDelay(
int source_frame_number,
base::TimeDelta first_scroll_delay,
base::TimeTicks first_scroll_timestamp) {
DCHECK(IsMainThread());
client_->DidObserveFirstScrollDelay(source_frame_number, first_scroll_delay,
first_scroll_timestamp);
}
void LayerTreeHost::AddViewTransitionRequest(
std::unique_ptr<ViewTransitionRequest> request) {
// Store the commit callback on LayerTreeHost, so that we can invoke them
// when the request is finished.
DCHECK(!base::Contains(view_transition_callbacks_, request->sequence_id()));
if (auto callback = request->TakeFinishedCallback()) {
view_transition_callbacks_[request->sequence_id()] = std::move(callback);
}
pending_commit_state()->view_transition_requests.push_back(
std::move(request));
SetNeedsCommit();
}
bool LayerTreeHost::DoUpdateLayers() {
DCHECK(IsMainThread());
TRACE_EVENT1("cc,benchmark", "LayerTreeHost::DoUpdateLayers",
"source_frame_number", SourceFrameNumber());
UpdateHudLayer(pending_commit_state()->debug_state.ShouldCreateHudLayer());
// In layer lists mode, the cc property trees are built directly and do not
// need to be built here.
if (!IsUsingLayerLists()) {
TRACE_EVENT0("cc", "LayerTreeHost::UpdateLayers::BuildPropertyTrees");
PropertyTreeBuilder::BuildPropertyTrees(this);
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHost::UpdateLayers_BuiltPropertyTrees",
TRACE_EVENT_SCOPE_THREAD, "property_trees",
property_trees()->AsTracedValue());
} else {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("cc.debug"),
"LayerTreeHost::UpdateLayers_ReceivedPropertyTrees",
TRACE_EVENT_SCOPE_THREAD, "property_trees",
property_trees()->AsTracedValue());
// The HUD layer is managed outside the layer list sent to LayerTreeHost
// and needs to have its property tree state set.
if (hud_layer() && root_layer()) {
hud_layer()->SetTransformTreeIndex(root_layer()->transform_tree_index());
hud_layer()->SetEffectTreeIndex(root_layer()->effect_tree_index());
hud_layer()->SetClipTreeIndex(root_layer()->clip_tree_index());
hud_layer()->SetScrollTreeIndex(root_layer()->scroll_tree_index());
hud_layer()->set_property_tree_sequence_number(
root_layer()->property_tree_sequence_number());
}
}
#if DCHECK_IS_ON()
// Ensure property tree nodes were created for all layers. When using layer
// lists, this can fail if blink doesn't setup layers or nodes correctly in
// |PaintArtifactCompositor|. When not using layer lists, this can fail if
// |PropertyTreeBuilder::BuildPropertyTrees| fails to create property tree
// nodes.
for (auto* layer : *this) {
DCHECK(property_trees()->effect_tree().Node(layer->effect_tree_index()));
DCHECK(
property_trees()->transform_tree().Node(layer->transform_tree_index()));
DCHECK(property_trees()->clip_tree().Node(layer->clip_tree_index()));
DCHECK(property_trees()->scroll_tree().Node(layer->scroll_tree_index()));
}
#else
// This is a quick sanity check for readiness of paint properties.
// TODO(crbug.com/40605801): This is to help analysis of crashes of the bug.
// Remove this CHECK when we close the bug.
CHECK(
property_trees()->effect_tree().Node(root_layer()->effect_tree_index()));
#endif
draw_property_utils::UpdatePropertyTrees(this);
LayerList update_layer_list;
draw_property_utils::FindLayersThatNeedUpdates(this, &update_layer_list);
bool did_paint_content = PaintContent(update_layer_list);
return did_paint_content;
}
void LayerTreeHost::ApplyViewportChanges(
const CompositorCommitData& commit_data) {
DCHECK(IsMainThread());
gfx::Vector2dF inner_viewport_scroll_delta;
if (commit_data.inner_viewport_scroll.element_id)
inner_viewport_scroll_delta =
commit_data.inner_viewport_scroll.scroll_delta;
// When a new scroll-animation starts, it is necessary to check
// |commit_data.manipulation_info| to make sure the scroll-animation was
// started by an input event. If there is already an ongoing scroll-animation,
// then it is necessary to only look at |commit_data.ongoing_scroll_animation|
// (since it is possible for the scroll-animation to continue even if no event
// was handled).
bool new_ongoing_scroll = scroll_animation_.in_progress
? commit_data.ongoing_scroll_animation
: (commit_data.ongoing_scroll_animation &&
commit_data.manipulation_info);
scroll_animation_.in_progress = new_ongoing_scroll;
// A pointer-down event on a scrollbar button triggers two scroll animations:
// one that starts immediately and ends after one scroll increment (typically
// 40px); and an autoscroll that starts after a 250ms delay and continues
// until pointer-up or until the end of the scroll node is reached.
// scroll_animation_.end_notification should wait for the first animation to
// finish, but it should *not* wait for the autoscroll to finish.
if (!scroll_animation_.end_notification.is_null() &&
(!scroll_animation_.in_progress || commit_data.is_auto_scrolling)) {
std::move(scroll_animation_.end_notification).Run();
}
if (inner_viewport_scroll_delta.IsZero() &&
commit_data.page_scale_delta == 1.f &&
commit_data.elastic_overscroll_delta.IsZero() &&
!commit_data.top_controls_delta && !commit_data.bottom_controls_delta &&
!commit_data.browser_controls_constraint_changed &&
!commit_data.scroll_end_data.scroll_gesture_did_end &&
commit_data.is_pinch_gesture_active ==
is_pinch_gesture_active_from_impl_) {
return;
}
is_pinch_gesture_active_from_impl_ = commit_data.is_pinch_gesture_active;
// const_cast to ensure the compiler chooses to the const version of
// property_trees(), to avoid blocking on commit.
const auto* pt = const_cast<const LayerTreeHost*>(this)->property_trees();
if (const auto* inner_scroll = pt->scroll_tree().Node(
pending_commit_state()->viewport_property_ids.inner_scroll)) {
UpdateScrollOffsetFromImpl(
inner_scroll->element_id, inner_viewport_scroll_delta,
commit_data.inner_viewport_scroll.snap_target_element_ids);
}
ApplyPageScaleDeltaFromImplSide(commit_data.page_scale_delta);
SetElasticOverscrollFromImplSide(pending_commit_state()->elastic_overscroll +
commit_data.elastic_overscroll_delta);
// TODO(ccameron): pass the elastic overscroll here so that input events
// may be translated appropriately.
client_->ApplyViewportChanges(
{inner_viewport_scroll_delta, commit_data.elastic_overscroll_delta,
commit_data.page_scale_delta, commit_data.is_pinch_gesture_active,
commit_data.top_controls_delta, commit_data.bottom_controls_delta,
commit_data.browser_controls_constraint,
commit_data.scroll_end_data.scroll_gesture_did_end});
SetNeedsUpdateLayers();
}
void LayerTreeHost::UpdateScrollOffsetFromImpl(
const ElementId& id,
const gfx::Vector2dF& delta,
const std::optional<TargetSnapAreaElementIds>& snap_target_ids) {
if (IsUsingLayerLists()) {
auto& scroll_tree = property_trees()->scroll_tree_mutable();
auto new_offset = scroll_tree.current_scroll_offset(id) + delta;
TRACE_EVENT_INSTANT2("cc", "NotifyDidScroll", TRACE_EVENT_SCOPE_THREAD,
"cur_y", scroll_tree.current_scroll_offset(id).y(),
"delta", delta.y());
if (auto* scroll_node = scroll_tree.FindNodeFromElementId(id)) {
// This update closely follows
// blink::PropertyTreeManager::DirectlyUpdateScrollOffsetTransform.
scroll_tree.SetScrollOffset(id, new_offset);
// |blink::PropertyTreeManager::DirectlySetScrollOffset| (called from
// |blink::PropertyTreeManager::DirectlyUpdateScrollOffsetTransform|)
// marks the layer as needing to push properties in order to clobber
// animations, but that is not needed for an impl-side scroll.
// Update the offset in the transform node.
TransformTree& transform_tree =
property_trees()->transform_tree_mutable();
auto* transform_node = transform_tree.Node(scroll_node->transform_id);
if (transform_node && transform_node->scroll_offset != new_offset) {
transform_node->scroll_offset = new_offset;
transform_node->needs_local_transform_update = true;
transform_node->transform_changed = true;
transform_tree.set_needs_update(true);
// If the scroll was realized on the compositor, then its transform node
// is already updated (see LayerTreeImpl::DidUpdateScrollOffset) and we
// are now "catching up" to it on main, so we don't need a commit.
//
// But if the scroll should be realized on the main thread, we need a
// commit to push the transform change.
if (scroll_tree.ShouldRealizeScrollsOnMain(*scroll_node)) {
SetNeedsCommit();
}
}
// The transform tree has been modified which requires a call to
// |LayerTreeHost::UpdateLayers| to update the property trees.
SetNeedsUpdateLayers();
}
scroll_tree.NotifyDidCompositorScroll(id, new_offset, snap_target_ids);
} else if (Layer* layer = LayerByElementId(id)) {
layer->SetScrollOffsetFromImplSide(layer->scroll_offset() + delta);
SetNeedsUpdateLayers();
}
}
void LayerTreeHost::ApplyCompositorChanges(CompositorCommitData* commit_data) {
DCHECK(IsMainThread());
DCHECK(commit_data);
TRACE_EVENT0("cc", "LayerTreeHost::ApplyCompositorChanges");
using perfetto::protos::pbzero::TrackEvent;
for (auto& swap_promise : commit_data->swap_promises) {
int64_t trace_id = swap_promise->GetTraceId();
TRACE_EVENT("input,benchmark", "LatencyInfo.Flow",
[&](perfetto::EventContext ctx) {
base::TaskAnnotator::EmitTaskTimingDetails(ctx);
ui::LatencyInfo::FillTraceEvent(
ctx, trace_id,
perfetto::protos::pbzero::ChromeLatencyInfo2::Step::
STEP_MAIN_THREAD_SCROLL_UPDATE);
});
swap_promise_manager_.QueueSwapPromise(std::move(swap_promise));
}
if (has_root_layer()) {
for (auto& scroll : commit_data->scrolls) {
UpdateScrollOffsetFromImpl(scroll.element_id, scroll.scroll_delta,
scroll.snap_target_element_ids);
}
// const_cast to ensure the compiler chooses to the const version of
// property_trees(), to avoid blocking on commit.
const auto* pt = const_cast<const LayerTreeHost*>(this)->property_trees();
for (auto& scrollbar : commit_data->scrollbars) {
pt->scroll_tree().NotifyDidChangeScrollbarsHidden(scrollbar.element_id,
scrollbar.hidden);
}
}
client_->UpdateCompositorScrollState(*commit_data);
// This needs to happen after scroll deltas have been sent to prevent top
// controls from clamping the layout viewport both on the compositor and
// on the main thread.
ApplyViewportChanges(*commit_data);
}
void LayerTreeHost::ApplyMutatorEvents(std::unique_ptr<MutatorEvents> events) {
DCHECK(IsMainThread());
if (!events->IsEmpty())
mutator_host()->SetAnimationEvents(std::move(events));
}
void LayerTreeHost::RecordStartOfFrameMetrics() {
DCHECK(IsMainThread());
client_->RecordStartOfFrameMetrics();
}
void LayerTreeHost::RecordEndOfFrameMetrics(
base::TimeTicks frame_begin_time,
ActiveFrameSequenceTrackers trackers) {
DCHECK(IsMainThread());
client_->RecordEndOfFrameMetrics(frame_begin_time, trackers);
}
void LayerTreeHost::NotifyCompositorMetricsTrackerResults(
CustomTrackerResults results) {
DCHECK(IsMainThread());
client_->NotifyCompositorMetricsTrackerResults(std::move(results));
}
const base::WeakPtr<CompositorDelegateForInput>&
LayerTreeHost::GetDelegateForInput() const {
DCHECK(IsMainThread());
return compositor_delegate_weak_ptr_;
}
void LayerTreeHost::DetachInputDelegateAndRenderFrameObserver() {
DCHECK(IsMainThread());
proxy_->DetachInputDelegateAndRenderFrameObserver();
}
void LayerTreeHost::UpdateBrowserControlsState(
BrowserControlsState constraints,
BrowserControlsState current,
bool animate,
base::optional_ref<const BrowserControlsOffsetTagsInfo> offset_tags_info) {
DCHECK(IsMainThread());
// Browser controls are only used in threaded mode but Blink layout tests may
// call into this. The single threaded version is a no-op.
proxy_->UpdateBrowserControlsState(constraints, current, animate,
offset_tags_info);
}
void LayerTreeHost::AnimateLayers(base::TimeTicks monotonic_time) {
std::unique_ptr<MutatorEvents> events = mutator_host()->CreateEvents();
if (mutator_host()->TickAnimations(monotonic_time,
property_trees()->scroll_tree(), true))
mutator_host()->UpdateAnimationState(true, events.get());
if (!events->IsEmpty()) {
// If not using layer lists, animation state changes will require
// rebuilding property trees to track them.
if (!IsUsingLayerLists())
property_trees()->set_needs_rebuild(true);
// A commit is required to push animation changes to the compositor.
SetNeedsCommit();
}
}
int LayerTreeHost::ScheduleMicroBenchmark(
const std::string& benchmark_name,
base::Value::Dict settings,
MicroBenchmark::DoneCallback callback) {
DCHECK(IsMainThread());
return micro_benchmark_controller_.ScheduleRun(
benchmark_name, std::move(settings), std::move(callback));
}
bool LayerTreeHost::SendMessageToMicroBenchmark(int id,
base::Value::Dict message) {
DCHECK(IsMainThread());
return micro_benchmark_controller_.SendMessage(id, std::move(message));
}
void LayerTreeHost::SetLayerTreeMutator(
std::unique_ptr<LayerTreeMutator> mutator) {
DCHECK(IsMainThread());
// The animation worklet system assumes that the mutator will never be called
// from the main thread, which will not be the case if we're running in
// single-threaded mode.
if (!task_runner_provider_->HasImplThread()) {
DLOG(ERROR) << "LayerTreeMutator not supported in single-thread mode";
return;
}
proxy_->SetMutator(std::move(mutator));
}
void LayerTreeHost::SetPaintWorkletLayerPainter(
std::unique_ptr<PaintWorkletLayerPainter> painter) {
DCHECK(IsMainThread());
// The paint worklet system assumes that the painter will never be called from
// the main thread, which will not be the case if we're running in
// single-threaded mode.
DCHECK(task_runner_provider_->HasImplThread())
<< "PaintWorkletLayerPainter not supported in single-thread mode";
proxy_->SetPaintWorkletLayerPainter(std::move(painter));
}
bool LayerTreeHost::IsSingleThreaded() const {
DCHECK(IsMainThread());
DCHECK(compositor_mode_ != CompositorMode::SINGLE_THREADED ||
!task_runner_provider_->HasImplThread());
return compositor_mode_ == CompositorMode::SINGLE_THREADED;
}
bool LayerTreeHost::IsThreaded() const {
DCHECK(IsMainThread());
DCHECK(compositor_mode_ != CompositorMode::THREADED ||
task_runner_provider_->HasImplThread());
return compositor_mode_ == CompositorMode::THREADED;
}
void LayerTreeHost::RequestPresentationTimeForNextFrame(
PresentationTimeCallbackBuffer::Callback callback) {
pending_commit_state()->pending_presentation_callbacks.push_back(
std::move(callback));
}
void LayerTreeHost::RequestSuccessfulPresentationTimeForNextFrame(
PresentationTimeCallbackBuffer::SuccessfulCallbackWithDetails callback) {
pending_commit_state()->pending_successful_presentation_callbacks.push_back(
std::move(callback));
}
void LayerTreeHost::RequestScrollAnimationEndNotification(
base::OnceClosure callback) {
DCHECK(IsMainThread());
DCHECK(scroll_animation_.end_notification.is_null());
if (scroll_animation_.in_progress)
scroll_animation_.end_notification = std::move(callback);
else
std::move(callback).Run();
}
void LayerTreeHost::SetRootLayer(scoped_refptr<Layer> new_root_layer) {
if (root_layer() == new_root_layer.get())
return;
if (root_layer()) {
WaitForProtectedSequenceCompletion();
root_layer()->SetLayerTreeHost(nullptr);
}
thread_unsafe_commit_state().root_layer = new_root_layer;
if (root_layer()) {
DCHECK(!root_layer()->parent());
root_layer()->SetLayerTreeHost(this);
}
if (hud_layer()) {
WaitForProtectedSequenceCompletion();
hud_layer()->RemoveFromParent();
}
// Reset gpu rasterization tracking.
// This flag is sticky until a new tree comes along.
pending_commit_state()->needs_gpu_rasterization_histogram = IsThreaded();
SetNeedsFullTreeSync();
}
void LayerTreeHost::RegisterViewportPropertyIds(
const ViewportPropertyIds& ids) {
DCHECK(IsUsingLayerLists());
pending_commit_state()->viewport_property_ids = ids;
// Outer viewport properties exist only if inner viewport property exists.
DCHECK(ids.inner_scroll != kInvalidPropertyNodeId ||
(ids.outer_scroll == kInvalidPropertyNodeId &&
ids.outer_clip == kInvalidPropertyNodeId));
}
Layer* LayerTreeHost::InnerViewportScrollLayerForTesting() {
auto* scroll_node = property_trees()->scroll_tree_mutable().Node(
pending_commit_state()->viewport_property_ids.inner_scroll);
return scroll_node ? LayerByElementId(scroll_node->element_id) : nullptr;
}
Layer* LayerTreeHost::OuterViewportScrollLayerForTesting() {
return LayerByElementId(OuterViewportScrollElementId());
}
ElementId LayerTreeHost::OuterViewportScrollElementId() const {
const auto* scroll_node = property_trees()->scroll_tree().Node(
pending_commit_state()->viewport_property_ids.outer_scroll);
return scroll_node ? scroll_node->element_id : ElementId();
}
void LayerTreeHost::RegisterSelection(const LayerSelection& selection) {
if (pending_commit_state()->selection == selection)
return;
pending_commit_state()->selection = selection;
SetNeedsCommit();
}
void LayerTreeHost::SetHaveScrollEventHandlers(bool have_event_handlers) {
if (pending_commit_state()->have_scroll_event_handlers == have_event_handlers)
return;
pending_commit_state()->have_scroll_event_handlers = have_event_handlers;
SetNeedsCommit();
}
void LayerTreeHost::SetEventListenerProperties(
EventListenerClass event_class,
EventListenerProperties properties) {
if (event_listener_properties(event_class) == properties)
return;
const size_t index = static_cast<size_t>(event_class);
pending_commit_state()->event_listener_properties[index] = properties;
SetNeedsCommit();
}
void LayerTreeHost::SetViewportRectAndScale(
const gfx::Rect& device_viewport_rect,
float device_scale_factor,
const viz::LocalSurfaceId& local_surface_id_from_parent) {
const viz::LocalSurfaceId previous_local_surface_id =
pending_commit_state()->local_surface_id_from_parent;
SetLocalSurfaceIdFromParent(local_surface_id_from_parent);
TRACE_EVENT_NESTABLE_ASYNC_END1("cc", "LayerTreeHostSize",
TRACE_ID_LOCAL(this), "id", id_);
TRACE_EVENT_NESTABLE_ASYNC_BEGIN2("cc", "LayerTreeHostSize",
TRACE_ID_LOCAL(this), "size",
device_viewport_rect.ToString(), "lsid",
local_surface_id_from_parent.ToString());
bool device_viewport_rect_changed = false;
if (pending_commit_state()->device_viewport_rect != device_viewport_rect) {
pending_commit_state()->device_viewport_rect = device_viewport_rect;
device_viewport_rect_changed = true;
}
bool painted_device_scale_factor_changed = false;
bool device_scale_factor_changed = false;
if (settings_.use_painted_device_scale_factor) {
DCHECK_EQ(pending_commit_state()->device_scale_factor, 1.f);
if (pending_commit_state()->painted_device_scale_factor !=
device_scale_factor) {
pending_commit_state()->painted_device_scale_factor = device_scale_factor;
painted_device_scale_factor_changed = true;
}
} else {
DCHECK_EQ(pending_commit_state()->painted_device_scale_factor, 1.f);
if (pending_commit_state()->device_scale_factor != device_scale_factor) {
pending_commit_state()->device_scale_factor = device_scale_factor;
device_scale_factor_changed = true;
}
}
// If a new viz::LocalSurfaceId has been provided, and the viewport has
// changed, we need not begin new frames until it has activated.
if (previous_local_surface_id != local_surface_id_from_parent &&
device_viewport_rect_changed) {
SetTargetLocalSurfaceId(local_surface_id_from_parent);
}
if (device_viewport_rect_changed || painted_device_scale_factor_changed ||
device_scale_factor_changed) {
SetPropertyTreesNeedRebuild();
SetNeedsCommit();
}
}
void LayerTreeHost::SetVisualDeviceViewportIntersectionRect(
const gfx::Rect& intersection_rect) {
DCHECK(IsMainThread());
if (intersection_rect == visual_device_viewport_intersection_rect_)
return;
visual_device_viewport_intersection_rect_ = intersection_rect;
}
void LayerTreeHost::SetVisualDeviceViewportSize(
const gfx::Size& visual_device_viewport_size) {
if (visual_device_viewport_size ==
pending_commit_state()->visual_device_viewport_size)
return;
pending_commit_state()->visual_device_viewport_size =
visual_device_viewport_size;
SetNeedsCommit();
}
void LayerTreeHost::SetMaxSafeAreaInsets(
const gfx::InsetsF& max_safe_area_insets) {
if (pending_commit_state()->max_safe_area_insets == max_safe_area_insets) {
return;
}
pending_commit_state()->max_safe_area_insets = max_safe_area_insets;
SetNeedsCommit();
}
void LayerTreeHost::SetBrowserControlsParams(
const BrowserControlsParams& params) {
if (pending_commit_state()->browser_controls_params == params)
return;
pending_commit_state()->browser_controls_params = params;
SetNeedsCommit();
}
void LayerTreeHost::SetBrowserControlsShownRatio(float top_ratio,
float bottom_ratio) {
if (pending_commit_state()->top_controls_shown_ratio == top_ratio &&
pending_commit_state()->bottom_controls_shown_ratio == bottom_ratio)
return;
pending_commit_state()->top_controls_shown_ratio = top_ratio;
pending_commit_state()->bottom_controls_shown_ratio = bottom_ratio;
SetNeedsCommit();
}
void LayerTreeHost::SetOverscrollBehavior(const OverscrollBehavior& behavior) {
if (pending_commit_state()->overscroll_behavior == behavior)
return;
pending_commit_state()->overscroll_behavior = behavior;
SetNeedsCommit();
}
void LayerTreeHost::SetPageScaleFactorAndLimits(float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) {
if (pending_commit_state()->page_scale_factor == page_scale_factor &&
pending_commit_state()->min_page_scale_factor == min_page_scale_factor &&
pending_commit_state()->max_page_scale_factor == max_page_scale_factor)
return;
DCHECK_GE(page_scale_factor, min_page_scale_factor);
DCHECK_LE(page_scale_factor, max_page_scale_factor);
// We should never process non-unit page_scale_delta for an OOPIF subframe.
// TODO(wjmaclean): Remove this dcheck as a pre-condition to closing the bug.
// https://crbug.com/845097
DCHECK(settings_.is_for_scalable_page ||
page_scale_factor == pending_commit_state()->page_scale_factor)
<< "Setting PSF in oopif subframe: old psf = "
<< pending_commit_state()->page_scale_factor
<< ", new psf = " << page_scale_factor;
pending_commit_state()->page_scale_factor = page_scale_factor;
pending_commit_state()->min_page_scale_factor = min_page_scale_factor;
pending_commit_state()->max_page_scale_factor = max_page_scale_factor;
SetPropertyTreesNeedRebuild();
SetNeedsCommit();
}
void LayerTreeHost::StartPageScaleAnimation(const gfx::Point& target_offset,
bool use_anchor,
float scale,
base::TimeDelta duration) {
pending_commit_state()->pending_page_scale_animation =
std::make_unique<PendingPageScaleAnimation>(target_offset, use_anchor,
scale, duration);
SetNeedsCommit();
}
bool LayerTreeHost::HasPendingPageScaleAnimation() const {
return !!pending_commit_state()->pending_page_scale_animation.get();
}
void LayerTreeHost::SetRecordingScaleFactor(float recording_scale_factor) {
DCHECK(IsMainThread());
if (recording_scale_factor_ == recording_scale_factor)
return;
recording_scale_factor_ = recording_scale_factor;
}
void LayerTreeHost::SetDisplayColorSpaces(
const gfx::DisplayColorSpaces& display_color_spaces) {
if (pending_commit_state()->display_color_spaces == display_color_spaces)
return;
bool only_hdr_changed = gfx::DisplayColorSpaces::EqualExceptForHdrHeadroom(
pending_commit_state()->display_color_spaces, display_color_spaces);
pending_commit_state()->display_color_spaces = display_color_spaces;
// Some layers needs to re-display when HDR headroom changes (e.g, any layer
// containing an HDR image needs to re-raster, and layers with HDR video will
// require re-tone-mapping).
bool did_set_needs_display = false;
for (auto* layer : *this) {
if (!only_hdr_changed ||
layer->RequiresSetNeedsDisplayOnHdrHeadroomChange()) {
layer->SetNeedsDisplay();
did_set_needs_display = true;
}
}
if (did_set_needs_display) {
SetNeedsCommit();
}
}
void LayerTreeHost::UpdateViewportIsMobileOptimized(
bool is_viewport_mobile_optimized) {
if (pending_commit_state()->is_viewport_mobile_optimized ==
is_viewport_mobile_optimized)
return;
pending_commit_state()->is_viewport_mobile_optimized =
is_viewport_mobile_optimized;
SetNeedsCommit();
}
void LayerTreeHost::SetPrefersReducedMotion(bool prefers_reduced_motion) {
if (pending_commit_state()->prefers_reduced_motion == prefers_reduced_motion)
return;
pending_commit_state()->prefers_reduced_motion = prefers_reduced_motion;
SetNeedsCommit();
}
void LayerTreeHost::SetMayThrottleIfUndrawnFrames(
bool may_throttle_if_undrawn_frames) {
if (pending_commit_state()->may_throttle_if_undrawn_frames ==
may_throttle_if_undrawn_frames)
return;
pending_commit_state()->may_throttle_if_undrawn_frames =
may_throttle_if_undrawn_frames;
SetNeedsCommit();
}
bool LayerTreeHost::GetMayThrottleIfUndrawnFramesForTesting() const {
return pending_commit_state()->may_throttle_if_undrawn_frames;
}
void LayerTreeHost::SetExternalPageScaleFactor(
float page_scale_factor,
bool is_external_pinch_gesture_active) {
if (pending_commit_state()->external_page_scale_factor == page_scale_factor &&
pending_commit_state()->is_external_pinch_gesture_active ==
is_external_pinch_gesture_active) {
return;
}
pending_commit_state()->external_page_scale_factor = page_scale_factor;
pending_commit_state()->is_external_pinch_gesture_active =
is_external_pinch_gesture_active;
SetNeedsCommit();
}
void LayerTreeHost::SetLocalSurfaceIdFromParent(
const viz::LocalSurfaceId& local_surface_id_from_parent) {
// If the viz::LocalSurfaceId is invalid we will be hitting the early exit.
// However creating a hash for tracing of an invalid id throw an error. So
// exit here. This is either from unit testing where no ids are being setup,
// or from a disconnect in Renderer and Browser startup, in which Renderers
// have a partial state before the Browser sends the full visual properties.
//
// TODO(jonross): Untangle startup so that we don't have this invalid partial
// state. (https://crbug.com/1185286) (https://crbug.com/419087)
if (pending_commit_state()->local_surface_id_from_parent ==
local_surface_id_from_parent)
return;
const viz::LocalSurfaceId current_local_surface_id_from_parent =
pending_commit_state()->local_surface_id_from_parent;
// These traces are split into two due to the usage of TRACE_ID_GLOBAL for the
// incoming flow (it comes from a different process), and TRACE_ID_LOCAL for
// the outgoing flow. The outgoing flow uses local to ensure that it doesn't
// flow into the wrong trace in different process.
TRACE_EVENT_WITH_FLOW2(
TRACE_DISABLED_BY_DEFAULT("viz.surface_id_flow"),
"LocalSurfaceId.Submission.Flow",
TRACE_ID_GLOBAL(local_surface_id_from_parent.submission_trace_id()),
TRACE_EVENT_FLAG_FLOW_IN, "step", "SetLocalSurfaceIdFromParent",
"local_surface_id", local_surface_id_from_parent.ToString());
TRACE_EVENT_WITH_FLOW2(
TRACE_DISABLED_BY_DEFAULT("viz.surface_id_flow"),
"LocalSurfaceId.Submission.Flow",
TRACE_ID_LOCAL(local_surface_id_from_parent.submission_trace_id()),
TRACE_EVENT_FLAG_FLOW_OUT, "step", "SetLocalSurfaceIdFromParent",
"local_surface_id", local_surface_id_from_parent.ToString());
// Always update the cached state of the viz::LocalSurfaceId to reflect the
// latest value received from our parent.
pending_commit_state()->local_surface_id_from_parent =
local_surface_id_from_parent;
// If the parent sequence number has not advanced, then there is no need to
// commit anything. This can occur when the child sequence number has
// advanced. Which means that child has changed visual properites, and the
// parent agreed upon these without needing to further advance its sequence
// number. When this occurs the child is already up-to-date and a commit here
// is simply redundant.
if (AreEmbedTokensEqual(current_local_surface_id_from_parent,
local_surface_id_from_parent) &&
AreParentSequencesEqual(current_local_surface_id_from_parent,
local_surface_id_from_parent)) {
return;
}
UpdateDeferMainFrameUpdateInternal();
SetNeedsCommit();
}
void LayerTreeHost::RequestViewportScreenshot(
const base::UnguessableToken& token) {
CHECK(pending_commit_state()->new_local_surface_id_request)
<< "Must have requested a new LocalSurfaceID before making "
"this request";
pending_commit_state()->screenshot_destination_token = token;
SetNeedsCommit();
}
void LayerTreeHost::SetPrimaryMainFrameItemSequenceNumber(
int64_t primary_main_frame_item_sequence_number) {
if (pending_commit_state()->primary_main_frame_item_sequence_number ==
primary_main_frame_item_sequence_number) {
return;
}
pending_commit_state()->primary_main_frame_item_sequence_number =
primary_main_frame_item_sequence_number;
SetNeedsCommit();
}
void LayerTreeHost::RequestNewLocalSurfaceId() {
// We can still request a new viz::LocalSurfaceId but that request will be
// deferred until we have a valid viz::LocalSurfaceId from the parent.
if (pending_commit_state()->new_local_surface_id_request)
return;
pending_commit_state()->new_local_surface_id_request = true;
SetNeedsCommit();
}
void LayerTreeHost::RegisterLayer(Layer* layer) {
DCHECK(IsMainThread());
DCHECK(!LayerById(layer->id()));
DCHECK(!in_paint_layer_contents_);
layer_id_map_[layer->id()] = layer;
}
void LayerTreeHost::UnregisterLayer(Layer* layer) {
DCHECK(IsMainThread());
DCHECK(LayerById(layer->id()));
DCHECK(!in_paint_layer_contents_);
pending_commit_state()->layers_that_should_push_properties.erase(layer);
layer_id_map_.erase(layer->id());
}
Layer* LayerTreeHost::LayerById(int id) {
DCHECK(IsMainThread());
auto iter = layer_id_map_.find(id);
return iter != layer_id_map_.end() ? iter->second : nullptr;
}
bool LayerTreeHost::PaintContent(const LayerList& update_layer_list) {
DCHECK(IsMainThread());
base::AutoReset<bool> painting(&in_paint_layer_contents_, true);
bool did_paint_content = false;
for (const auto& layer : update_layer_list) {
did_paint_content |= layer->Update();
}
return did_paint_content;
}
void LayerTreeHost::AddSurfaceRange(const viz::SurfaceRange& surface_range) {
if (++pending_commit_state()->surface_ranges[surface_range] == 1) {
pending_commit_state()->needs_surface_ranges_sync = true;
SetNeedsCommit();
}
}
void LayerTreeHost::RemoveSurfaceRange(const viz::SurfaceRange& surface_range) {
auto iter = pending_commit_state()->surface_ranges.find(surface_range);
if (iter == pending_commit_state()->surface_ranges.end())
return;
if (--iter->second <= 0) {
pending_commit_state()->surface_ranges.erase(iter);
pending_commit_state()->needs_surface_ranges_sync = true;
SetNeedsCommit();
}
}
void LayerTreeHost::AddLayerShouldPushProperties(Layer* layer) {
pending_commit_state()->layers_that_should_push_properties.insert(layer);
}
void LayerTreeHost::SetPageScaleFromImplSide(float page_scale) {
DCHECK(syncing_deltas_for_test_ || CommitRequested());
// We should never process non-unit page_scale_delta for an OOPIF subframe.
// TODO(wjmaclean): Remove this check as a pre-condition to closing the bug.
// https://crbug.com/845097
DCHECK(settings_.is_for_scalable_page ||
page_scale == pending_commit_state()->page_scale_factor)
<< "Setting PSF in oopif subframe: old psf = "
<< pending_commit_state()->page_scale_factor
<< ", new psf = " << page_scale;
bool changed = (page_scale != pending_commit_state()->page_scale_factor);
pending_commit_state()->page_scale_factor = page_scale;
if (changed)
SetPropertyTreesNeedRebuild();
}
void LayerTreeHost::SetElasticOverscrollFromImplSide(
gfx::Vector2dF elastic_overscroll) {
DCHECK(syncing_deltas_for_test_ || CommitRequested());
pending_commit_state()->elastic_overscroll = elastic_overscroll;
}
void LayerTreeHost::UpdateHudLayer(bool show_hud_info) {
if (show_hud_info) {
if (!hud_layer()) {
hud_layer_ = HeadsUpDisplayLayer::Create();
pending_commit_state()->hud_layer_id = hud_layer()->id();
}
if (root_layer() && !hud_layer()->parent())
root_layer()->AddChild(hud_layer());
hud_layer()->UpdateLocationAndSize(
pending_commit_state()->device_viewport_rect.size(),
pending_commit_state()->device_scale_factor);
} else if (hud_layer()) {
hud_layer()->RemoveFromParent();
hud_layer_ = nullptr;
pending_commit_state()->hud_layer_id = Layer::INVALID_ID;
}
}
bool LayerTreeHost::is_hud_layer(const Layer* layer) const {
return hud_layer() == layer;
}
void LayerTreeHost::SetNeedsFullTreeSync() {
pending_commit_state()->needs_full_tree_sync = true;
property_trees()->set_needs_rebuild(true);
SetNeedsCommit();
}
void LayerTreeHost::ResetNeedsFullTreeSyncForTesting() {
pending_commit_state()->needs_full_tree_sync = false;
}
void LayerTreeHost::SetPropertyTreesNeedRebuild() {
property_trees()->set_needs_rebuild(true);
SetNeedsUpdateLayers();
}
Layer* LayerTreeHost::LayerByElementId(ElementId element_id) {
DCHECK(IsMainThread());
auto iter = element_layers_map_.find(element_id);
return iter != element_layers_map_.end() ? iter->second : nullptr;
}
const Layer* LayerTreeHost::LayerByElementId(ElementId element_id) const {
DCHECK(IsMainThread());
auto iter = element_layers_map_.find(element_id);
return iter != element_layers_map_.end() ? iter->second : nullptr;
}
void LayerTreeHost::RegisterElement(ElementId element_id,
Layer* layer) {
DCHECK(IsMainThread());
element_layers_map_[element_id] = layer;
}
void LayerTreeHost::UnregisterElement(ElementId element_id) {
DCHECK(IsMainThread());
if (!IsUsingLayerLists()) {
mutator_host()->RemoveElementId(element_id);
}
element_layers_map_.erase(element_id);
}
void LayerTreeHost::SetElementIdsForTesting() {
for (auto* layer : *this)
layer->SetElementId(LayerIdToElementIdForTesting(layer->id()));
}
void LayerTreeHost::BuildPropertyTreesForTesting() {
PropertyTreeBuilder::BuildPropertyTrees(this);
}
bool LayerTreeHost::IsElementInPropertyTrees(ElementId element_id,
ElementListType list_type) const {
DCHECK(IsMainThread());
if (IsUsingLayerLists()) {
return list_type == ElementListType::ACTIVE &&
property_trees()->HasElement(element_id);
}
return list_type == ElementListType::ACTIVE && LayerByElementId(element_id);
}
void LayerTreeHost::SetMutatorsNeedCommit() {
SetNeedsCommit();
}
void LayerTreeHost::SetMutatorsNeedRebuildPropertyTrees() {
property_trees()->set_needs_rebuild(true);
}
void LayerTreeHost::SetElementFilterMutated(ElementId element_id,
ElementListType list_type,
const FilterOperations& filters) {
if (list_type != ElementListType::ACTIVE)
return;
if (IsUsingLayerLists()) {
// In BlinkGenPropertyTrees/CompositeAfterPaint we always have property
// tree nodes and can set the filter directly on the effect node.
property_trees()->effect_tree_mutable().OnFilterAnimated(element_id,
filters);
return;
}
Layer* layer = LayerByElementId(element_id);
DCHECK(layer);
layer->OnFilterAnimated(filters);
}
void LayerTreeHost::SetElementBackdropFilterMutated(
ElementId element_id,
ElementListType list_type,
const FilterOperations& backdrop_filters) {
if (list_type != ElementListType::ACTIVE)
return;
if (IsUsingLayerLists()) {
// In BlinkGenPropertyTrees/CompositeAfterPaint we always have property
// tree nodes and can set the backdrop_filter directly on the effect node.
property_trees()->effect_tree_mutable().OnBackdropFilterAnimated(
element_id, backdrop_filters);
return;
}
Layer* layer = LayerByElementId(element_id);
DCHECK(layer);
layer->OnBackdropFilterAnimated(backdrop_filters);
}
void LayerTreeHost::SetElementOpacityMutated(ElementId element_id,
ElementListType list_type,
float opacity) {
DCHECK_GE(opacity, 0.f);
DCHECK_LE(opacity, 1.f);
if (list_type != ElementListType::ACTIVE)
return;
if (IsUsingLayerLists()) {
property_trees()->effect_tree_mutable().OnOpacityAnimated(element_id,
opacity);
return;
}
Layer* layer = LayerByElementId(element_id);
DCHECK(layer);
layer->OnOpacityAnimated(opacity);
if (EffectNode* node = property_trees()->effect_tree_mutable().Node(
layer->effect_tree_index())) {
DCHECK_EQ(layer->effect_tree_index(), node->id);
if (node->opacity == opacity)
return;
node->opacity = opacity;
property_trees()->effect_tree_mutable().set_needs_update(true);
}
SetNeedsUpdateLayers();
}
void LayerTreeHost::SetElementTransformMutated(
ElementId element_id,
ElementListType list_type,
const gfx::Transform& transform) {
if (list_type != ElementListType::ACTIVE)
return;
if (IsUsingLayerLists()) {
property_trees()->transform_tree_mutable().OnTransformAnimated(element_id,
transform);
return;
}
Layer* layer = LayerByElementId(element_id);
DCHECK(layer);
layer->OnTransformAnimated(transform);
if (layer->has_transform_node()) {
TransformNode* node = property_trees()->transform_tree_mutable().Node(
layer->transform_tree_index());
if (node->local == transform)
return;
node->local = transform;
node->needs_local_transform_update = true;
node->has_potential_animation = true;
property_trees()->transform_tree_mutable().set_needs_update(true);
}
SetNeedsUpdateLayers();
}
void LayerTreeHost::SetElementScrollOffsetMutated(
ElementId element_id,
ElementListType list_type,
const gfx::PointF& scroll_offset) {
DCHECK(IsMainThread());
// Do nothing. Scroll deltas will be sent from the compositor thread back
// to the main thread in the same manner as during non-animated
// compositor-driven scrolling.
}
void LayerTreeHost::ElementIsAnimatingChanged(
const PropertyToElementIdMap& element_id_map,
ElementListType list_type,
const PropertyAnimationState& mask,
const PropertyAnimationState& state) {
if (list_type == ElementListType::PENDING)
return;
property_trees()->ElementIsAnimatingChanged(element_id_map, mask, state,
true);
}
void LayerTreeHost::MaximumScaleChanged(ElementId element_id,
ElementListType list_type,
float maximum_scale) {
if (list_type == ElementListType::PENDING)
return;
property_trees()->MaximumAnimationScaleChanged(element_id, maximum_scale);
}
bool LayerTreeHost::RunsOnCurrentThread() const {
return !task_runner_provider_ || task_runner_provider_->IsMainThread();
}
void LayerTreeHost::QueueImageDecode(const PaintImage& image,
base::OnceCallback<void(bool)> callback) {
TRACE_EVENT0("cc", "LayerTreeHost::QueueImageDecode");
int next_id = s_image_decode_sequence_number.GetNext();
if (base::FeatureList::IsEnabled(
features::kSendExplicitDecodeRequestsImmediately)) {
proxy()->QueueImageDecode(next_id, image);
} else {
pending_commit_state()->queued_image_decodes.emplace_back(
next_id, std::make_unique<PaintImage>(image));
}
pending_image_decodes_.emplace(next_id, std::move(callback));
SetNeedsCommit();
}
LayerListIterator LayerTreeHost::begin() {
return LayerListIterator(root_layer());
}
LayerListConstIterator LayerTreeHost::begin() const {
DCHECK(IsMainThread());
return LayerListConstIterator(root_layer());
}
LayerListIterator LayerTreeHost::end() {
DCHECK(IsMainThread());
return LayerListIterator(nullptr);
}
LayerListConstIterator LayerTreeHost::end() const {
DCHECK(IsMainThread());
return LayerListConstIterator(nullptr);
}
LayerListReverseIterator LayerTreeHost::rbegin() {
DCHECK(IsMainThread());
return LayerListReverseIterator(root_layer());
}
LayerListReverseConstIterator LayerTreeHost::rbegin() const {
DCHECK(IsMainThread());
return LayerListReverseConstIterator(root_layer());
}
LayerListReverseIterator LayerTreeHost::rend() {
return LayerListReverseIterator(nullptr);
}
LayerListReverseConstIterator LayerTreeHost::rend() const {
return LayerListReverseConstIterator(nullptr);
}
void LayerTreeHost::SetPropertyTreesForTesting(
const PropertyTrees* property_trees) {
thread_unsafe_commit_state().property_trees = *property_trees;
}
void LayerTreeHost::SetNeedsDisplayOnAllLayers() {
for (auto* layer : *this)
layer->SetNeedsDisplay();
}
void LayerTreeHost::SetHasCopyRequest(bool has_copy_request) {
DCHECK(IsMainThread());
has_copy_request_ = has_copy_request;
}
void LayerTreeHost::RequestBeginMainFrameNotExpected(bool new_state) {
DCHECK(IsMainThread());
proxy_->RequestBeginMainFrameNotExpected(new_state);
}
void LayerTreeHost::SetSourceURL(ukm::SourceId source_id, const GURL& url) {
DCHECK(IsMainThread());
// Clears image caches and resets the scheduling history for the content
// produced by this host so far.
pending_commit_state()->clear_caches_on_next_commit = true;
proxy_->SetSourceURL(source_id, url);
// If this is not used as a common web page, don't show HUD.
if (!url.SchemeIsHTTPOrHTTPS())
pending_commit_state()->debug_state.TurnOffHudInfoDisplay();
}
base::ReadOnlySharedMemoryRegion
LayerTreeHost::CreateSharedMemoryForSmoothnessUkm() {
DCHECK(IsMainThread());
const auto size = sizeof(UkmSmoothnessDataShared);
auto ukm_smoothness_mapping = base::ReadOnlySharedMemoryRegion::Create(size);
if (!ukm_smoothness_mapping.IsValid())
return {};
proxy_->SetUkmSmoothnessDestination(
std::move(ukm_smoothness_mapping.mapping));
return std::move(ukm_smoothness_mapping.region);
}
void LayerTreeHost::SetRenderFrameObserver(
std::unique_ptr<RenderFrameMetadataObserver> observer) {
DCHECK(IsMainThread());
proxy_->SetRenderFrameObserver(std::move(observer));
}
void LayerTreeHost::SetDelegatedInkMetadata(
std::unique_ptr<gfx::DelegatedInkMetadata> metadata) {
pending_commit_state()->delegated_ink_metadata = std::move(metadata);
SetNeedsCommit();
}
std::vector<ViewTransitionRequest::ViewTransitionCaptureCallback>
LayerTreeHost::TakeViewTransitionCallbacksForTesting() {
DCHECK(IsMainThread());
std::vector<ViewTransitionRequest::ViewTransitionCaptureCallback> result;
for (auto& item : view_transition_callbacks_)
result.push_back(std::move(item.second));
view_transition_callbacks_.clear();
return result;
}
double LayerTreeHost::GetPercentDroppedFrames() const {
DCHECK(IsMainThread());
return proxy_->GetPercentDroppedFrames();
}
void LayerTreeHost::DropActiveScrollDeltaNextCommit(ElementId scroll_element) {
pending_commit_state()->scrollers_clobbering_active_value.insert(
scroll_element);
SetNeedsCommit();
}
void LayerTreeHost::CrashGpuProcessForTesting() {
if (current_layer_tree_frame_sink_) {
current_layer_tree_frame_sink_->CrashGpuProcessForTesting(); // IN-TEST
}
}
} // namespace cc