summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/platform/widget/widget_base.cc
blob: f779d8d09105ef07df1ab23a45600f6c13a19eb1 (plain)
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
// Copyright 2020 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/platform/widget/widget_base.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/ranges/algorithm.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/timer/elapsed_timer.h"
#include "build/build_config.h"
#include "cc/animation/animation_host.h"
#include "cc/animation/animation_id_provider.h"
#include "cc/mojo_embedder/async_layer_tree_frame_sink.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_settings.h"
#include "cc/trees/paint_holding_reason.h"
#include "cc/trees/ukm_manager.h"
#include "components/viz/common/features.h"
#include "gpu/command_buffer/client/shared_memory_limits.h"
#include "gpu/command_buffer/common/context_creation_attribs.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "services/viz/public/cpp/gpu/context_provider_command_buffer.h"
#include "services/viz/public/mojom/compositing/compositor_frame_sink.mojom-blink.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_input_event_attribution.h"
#include "third_party/blink/public/common/switches.h"
#include "third_party/blink/public/mojom/input/pointer_lock_context.mojom-blink.h"
#include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom-blink.h"
#include "third_party/blink/public/mojom/widget/visual_properties.mojom-blink.h"
#include "third_party/blink/public/platform/cross_variant_mojo_util.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/renderer/platform/graphics/raster_dark_mode_filter_impl.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/compositor_thread_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/widget_scheduler.h"
#include "third_party/blink/renderer/platform/widget/compositing/categorized_worker_pool.h"
#include "third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.h"
#include "third_party/blink/renderer/platform/widget/compositing/layer_tree_view.h"
#include "third_party/blink/renderer/platform/widget/compositing/render_frame_metadata_observer_impl.h"
#include "third_party/blink/renderer/platform/widget/compositing/widget_compositor.h"
#include "third_party/blink/renderer/platform/widget/frame_widget.h"
#include "third_party/blink/renderer/platform/widget/input/ime_event_guard.h"
#include "third_party/blink/renderer/platform/widget/input/main_thread_event_queue.h"
#include "third_party/blink/renderer/platform/widget/input/widget_input_handler_manager.h"
#include "third_party/blink/renderer/platform/widget/widget_base_client.h"
#include "ui/base/ime/mojom/text_input_state.mojom-blink.h"
#include "ui/display/display.h"
#include "ui/display/screen_info.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/presentation_feedback.h"

#if BUILDFLAG(IS_ANDROID)
#include "third_party/blink/renderer/platform/widget/compositing/android_webview/synchronous_layer_tree_frame_sink.h"
#endif

namespace blink {

namespace {

#if BUILDFLAG(IS_ANDROID)
// Unique identifier for each output surface created.
uint32_t g_next_layer_tree_frame_sink_id = 1;
#endif

// Used for renderer compositor thread context, WebGL (when high priority is
// not requested by workaround), canvas, etc.
const gpu::SchedulingPriority kGpuStreamPriorityDefault =
    gpu::SchedulingPriority::kNormal;

const uint32_t kGpuStreamIdDefault = 0;

static const int kInvalidNextPreviousFlagsValue = -1;

static const char kOOPIF[] = "OOPIF";
static const char kRenderer[] = "Renderer";

void OnDidPresentForceDrawFrame(
    mojom::blink::Widget::ForceRedrawCallback callback,
    const gfx::PresentationFeedback& feedback) {
  std::move(callback).Run();
}

bool IsDateTimeInput(ui::TextInputType type) {
  return type == ui::TEXT_INPUT_TYPE_DATE ||
         type == ui::TEXT_INPUT_TYPE_DATE_TIME ||
         type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL ||
         type == ui::TEXT_INPUT_TYPE_MONTH ||
         type == ui::TEXT_INPUT_TYPE_TIME || type == ui::TEXT_INPUT_TYPE_WEEK;
}

ui::TextInputType ConvertWebTextInputType(blink::WebTextInputType type) {
  // Check the type is in the range representable by ui::TextInputType.
  DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX))
      << "blink::WebTextInputType and ui::TextInputType not synchronized";
  return static_cast<ui::TextInputType>(type);
}

ui::TextInputMode ConvertWebTextInputMode(blink::WebTextInputMode mode) {
  // Check the mode is in the range representable by ui::TextInputMode.
  DCHECK_LE(mode, static_cast<int>(ui::TEXT_INPUT_MODE_MAX))
      << "blink::WebTextInputMode and ui::TextInputMode not synchronized";
  return static_cast<ui::TextInputMode>(mode);
}

unsigned OrientationTypeToAngle(display::mojom::blink::ScreenOrientation type) {
  unsigned angle;
  // FIXME(ostap): This relationship between orientationType and
  // orientationAngle is temporary. The test should be able to specify
  // the angle in addition to the orientation type.
  switch (type) {
    case display::mojom::blink::ScreenOrientation::kLandscapePrimary:
      angle = 90;
      break;
    case display::mojom::blink::ScreenOrientation::kLandscapeSecondary:
      angle = 270;
      break;
    case display::mojom::blink::ScreenOrientation::kPortraitSecondary:
      angle = 180;
      break;
    default:
      angle = 0;
  }
  return angle;
}

std::unique_ptr<viz::SyntheticBeginFrameSource>
CreateSyntheticBeginFrameSource() {
  base::SingleThreadTaskRunner* compositor_impl_side_task_runner =
      Platform::Current()->CompositorThreadTaskRunner()
          ? Platform::Current()->CompositorThreadTaskRunner().get()
          : base::ThreadTaskRunnerHandle::Get().get();
  return std::make_unique<viz::BackToBackBeginFrameSource>(
      std::make_unique<viz::DelayBasedTimeSource>(
          compositor_impl_side_task_runner));
}

}  // namespace

WidgetBase::WidgetBase(
    WidgetBaseClient* client,
    CrossVariantMojoAssociatedRemote<mojom::WidgetHostInterfaceBase>
        widget_host,
    CrossVariantMojoAssociatedReceiver<mojom::WidgetInterfaceBase> widget,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    bool hidden,
    bool never_composited,
    bool is_embedded,
    bool is_for_scalable_page)
    : never_composited_(never_composited),
      is_embedded_(is_embedded),
      is_for_scalable_page_(is_for_scalable_page),
      client_(client),
      widget_host_(std::move(widget_host), task_runner),
      receiver_(this, std::move(widget), task_runner),
      next_previous_flags_(kInvalidNextPreviousFlagsValue),
      is_hidden_(hidden),
      request_animation_after_delay_timer_(
          std::move(task_runner),
          this,
          &WidgetBase::RequestAnimationAfterDelayTimerFired) {}

WidgetBase::~WidgetBase() {
  // Ensure Shutdown was called.
  DCHECK(!layer_tree_view_);
}

void WidgetBase::InitializeCompositing(
    PageScheduler& page_scheduler,
    const display::ScreenInfos& screen_infos,
    const cc::LayerTreeSettings* settings,
    base::WeakPtr<mojom::blink::FrameWidgetInputHandler>
        frame_widget_input_handler) {
  DCHECK(!initialized_);

  widget_scheduler_ = page_scheduler.CreateWidgetScheduler();
  widget_scheduler_->SetHidden(is_hidden_);

  main_thread_compositor_task_runner_ =
      page_scheduler.GetAgentGroupScheduler().CompositorTaskRunner();

  auto* compositing_thread_scheduler =
      ThreadScheduler::CompositorThreadScheduler();
  layer_tree_view_ = std::make_unique<LayerTreeView>(this, widget_scheduler_);

  absl::optional<cc::LayerTreeSettings> default_settings;
  if (!settings) {
    const display::ScreenInfo& screen_info = screen_infos.current();
    default_settings = GenerateLayerTreeSettings(
        compositing_thread_scheduler, is_embedded_, is_for_scalable_page_,
        screen_info.rect.size(), screen_info.device_scale_factor);
    settings = &default_settings.value();
  }
  screen_infos_ = screen_infos;
  layer_tree_view_->Initialize(
      *settings, main_thread_compositor_task_runner_,
      compositing_thread_scheduler
          ? compositing_thread_scheduler->DefaultTaskRunner()
          : nullptr,
      CategorizedWorkerPool::GetOrCreate());

  FrameWidget* frame_widget = client_->FrameWidget();

  // Even if we have a |compositing_thread_scheduler| we do not process input
  // on the compositor thread for widgets that are not frames. (ie. popups).
  auto* widget_compositing_thread_scheduler =
      frame_widget ? compositing_thread_scheduler : nullptr;

  // We only use an external input handler for frame widgets because only
  // frames use the compositor for input handling. Other kinds of widgets
  // (e.g.  popups, plugins) must forward their input directly through
  // WidgetBaseInputHandler.
  bool uses_input_handler = frame_widget;
  widget_input_handler_manager_ = WidgetInputHandlerManager::Create(
      weak_ptr_factory_.GetWeakPtr(), std::move(frame_widget_input_handler),
      never_composited_, widget_compositing_thread_scheduler, widget_scheduler_,
      uses_input_handler, client_->AllowsScrollResampling());

  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kAllowPreCommitInput))
    widget_input_handler_manager_->AllowPreCommitInput();

  UpdateScreenInfo(screen_infos);

  // If the widget is hidden, delay starting the compositor until the user
  // shows it. Otherwise start the compositor immediately. If the widget is
  // for a provisional frame, this importantly starts the compositor before
  // the frame is inserted into the frame tree, which impacts first paint
  // metrics.
  if (!is_hidden_)
    SetCompositorVisible(true);

  if (Platform::Current()->IsThreadedAnimationEnabled()) {
    DCHECK(AnimationHost());
    scroll_animation_timeline_ = cc::AnimationTimeline::Create(
        cc::AnimationIdProvider::NextTimelineId());
    AnimationHost()->AddAnimationTimeline(scroll_animation_timeline_);
  }

  initialized_ = true;
}

void WidgetBase::InitializeNonCompositing() {
  DCHECK(!initialized_);
  // WidgetBase users implicitly expect one default ScreenInfo to exist.
  screen_infos_ = display::ScreenInfos(display::ScreenInfo());
  initialized_ = true;
}

void WidgetBase::DidFirstVisuallyNonEmptyPaint(
    base::TimeTicks& first_paint_time) {
  if (widget_input_handler_manager_) {
    widget_input_handler_manager_->DidFirstVisuallyNonEmptyPaint(
        first_paint_time);
  }
}

void WidgetBase::Shutdown() {
  // The |input_event_queue_| is refcounted and will live while an event is
  // being handled. This drops the connection back to this WidgetBase which
  // is being destroyed.
  if (widget_input_handler_manager_)
    widget_input_handler_manager_->ClearClient();

  // The LayerTreeHost may already be in the call stack, if this WidgetBase
  // is being destroyed during an animation callback for instance. We can not
  // delete it here and unwind the stack back up to it, or it will crash. So
  // we post the deletion to another task, but disconnect the LayerTreeHost
  // (via the LayerTreeView) from the destroying WidgetBase. The
  // LayerTreeView owns the LayerTreeHost, and is its client, so they are kept
  // alive together for a clean call stack.
  if (layer_tree_view_) {
    if (ScrollAnimationTimeline()) {
      DCHECK(AnimationHost());
      AnimationHost()->RemoveAnimationTimeline(ScrollAnimationTimeline());
    }

    layer_tree_view_->Disconnect();

    // The `widget_scheduler_` must be deleted last because the
    // `widget_input_handler_manager_` may request to post a task on the
    // InputTaskQueue. The `widget_input_handler_manager_` must outlive
    // the `layer_tree_view_` because it's `LayerTreeHost` holds a raw ptr to
    // the `InputHandlerProxy` interface on the compositor thread. The
    // `LayerTreeHost` destruction is synchronous and will join with the
    // compositor thread.

    scoped_refptr<base::SingleThreadTaskRunner> cleanup_runner =
        base::ThreadTaskRunnerHandle::Get();
    cleanup_runner->PostNonNestableTask(
        FROM_HERE, base::BindOnce(
                       [](std::unique_ptr<LayerTreeView> view,
                          scoped_refptr<WidgetInputHandlerManager> manager,
                          scoped_refptr<scheduler::WidgetScheduler> scheduler) {
                         view.reset();
                         manager.reset();
                         scheduler->Shutdown();
                       },
                       std::move(layer_tree_view_),
                       std::move(widget_input_handler_manager_),
                       std::move(widget_scheduler_)));
  }

  if (widget_compositor_) {
    widget_compositor_->Shutdown();
    widget_compositor_ = nullptr;
  }
}

cc::LayerTreeHost* WidgetBase::LayerTreeHost() const {
  return layer_tree_view_->layer_tree_host();
}

cc::AnimationHost* WidgetBase::AnimationHost() const {
  return layer_tree_view_ ? layer_tree_view_->animation_host() : nullptr;
}

cc::AnimationTimeline* WidgetBase::ScrollAnimationTimeline() const {
  return scroll_animation_timeline_.get();
}

scheduler::WidgetScheduler* WidgetBase::WidgetScheduler() {
  return widget_scheduler_.get();
}

void WidgetBase::ForceRedraw(
    mojom::blink::Widget::ForceRedrawCallback callback) {
  LayerTreeHost()->RequestPresentationTimeForNextFrame(
      base::BindOnce(&OnDidPresentForceDrawFrame, std::move(callback)));
  LayerTreeHost()->SetNeedsCommitWithForcedRedraw();

  // ScheduleAnimationForWebTests() which is implemented by
  // WebTestWebFrameWidgetImpl, providing the additional control over the
  // lifecycle of compositing required by web tests. This will be a no-op on
  // production.
  client_->ScheduleAnimationForWebTests();
}

void WidgetBase::GetWidgetInputHandler(
    mojo::PendingReceiver<mojom::blink::WidgetInputHandler> request,
    mojo::PendingRemote<mojom::blink::WidgetInputHandlerHost> host) {
  widget_input_handler_manager_->AddInterface(std::move(request),
                                              std::move(host));
}

void WidgetBase::UpdateVisualProperties(
    const VisualProperties& visual_properties_from_browser) {
  TRACE_EVENT0("renderer", "WidgetBase::UpdateVisualProperties");

  // UpdateVisualProperties is used to receive properties from the browser
  // process for this WidgetBase. There are roughly 4 types of
  // VisualProperties.
  // TODO(danakj): Splitting these 4 types of properties apart and making them
  // more explicit could be super useful to understanding this code.
  // 1. Unique to each WidgetBase. Computed by the RenderWidgetHost and passed
  //    to the WidgetBase which consumes it here.
  //    Example: new_size.
  // 2. Global properties, which are given to each WidgetBase (to maintain
  //    the requirement that a WidgetBase is updated atomically). These
  //    properties are usually the same for every WidgetBase, except when
  //    device emulation changes them in the main frame WidgetBase only.
  //    Example: screen_info.
  // 3. Computed in the renderer of the main frame WebFrameWidgetImpl (in blink
  //    usually). Passed down through the waterfall dance to child frame
  //    WebFrameWidgetImpl. Here that step is performed by passing the value
  //    along to all RemoteFrame objects that are below this WebFrameWidgetImpl
  //    in the frame tree. The main frame (top level) WebFrameWidgetImpl ignores
  //    this value from its RenderWidgetHost since it is controlled in the
  //    renderer. Child frame WebFrameWidgetImpls consume the value from their
  //    RenderWidgetHost. Example: page_scale_factor.
  // 4. Computed independently in the renderer for each WidgetBase (in blink
  //    usually). Passed down from the parent to the child WidgetBases through
  //    the waterfall dance, but the value only travels one step - the child
  //    frame WebFrameWidgetImpl would compute values for grandchild
  //    WebFrameWidgetImpls independently. Here the value is passed to child
  //    frame RenderWidgets by passing the value along to all RemoteFrame
  //    objects that are below this WebFrameWidgetImpl in the frame tree. Each
  //    WidgetBase consumes this value when it is received from its
  //    RenderWidgetHost. Example: compositor_viewport_pixel_rect.
  // For each of these properties:
  //   If the WebView also knows these properties, each WebFrameWidgetImpl
  //   will pass them along to the WebView as it receives it, even if there
  //   are multiple WebFrameWidgetImpls related to the same WebView.
  //   However when the main frame in the renderer is the source of truth,
  //   then child widgets must not clobber that value! In all cases child frames
  //   do not need to update state in the WebView when a local main frame is
  //   present as it always sets the value first.
  //   TODO(danakj): This does create a race if there are multiple
  //   UpdateVisualProperties updates flowing through the WebFrameWidgetImpl
  //   tree at the same time, and it seems that only one WebFrameWidgetImpl for
  //   each WebView should be responsible for this update.
  //
  //   TODO(danakj): A more explicit API to give values from here to RenderView
  //   and/or WebView would be nice. Also a more explicit API to give values to
  //   the RemoteFrame in one go, instead of setting each property
  //   independently, causing an update IPC from the
  //   RenderFrameProxy/RemoteFrame for each one.
  //
  //   See also:
  //   https://docs.google.com/document/d/1G_fR1D_0c1yke8CqDMddoKrDGr3gy5t_ImEH4hKNIII/edit#

  base::ElapsedTimer update_timer;
  VisualProperties visual_properties = visual_properties_from_browser;
  auto& screen_info = visual_properties.screen_infos.mutable_current();

  // Web tests can override the device scale factor in the renderer.
  if (auto scale_factor = client_->GetTestingDeviceScaleFactorOverride()) {
    screen_info.device_scale_factor = scale_factor;
    visual_properties.compositor_viewport_pixel_rect =
        gfx::Rect(gfx::ScaleToCeiledSize(visual_properties.new_size,
                                         screen_info.device_scale_factor));
  }

  // Inform the rendering thread of the color space indicating the presence of
  // HDR capabilities. The HDR bit happens to be globally true/false for all
  // browser windows (on Windows OS) and thus would be the same for all
  // RenderWidgets, so clobbering each other works out since only the HDR bit is
  // used. See https://crbug.com/803451 and
  // https://chromium-review.googlesource.com/c/chromium/src/+/852912/15#message-68bbd3e25c3b421a79cd028b2533629527d21fee
  Platform::Current()->SetRenderingColorSpace(
      screen_info.display_color_spaces.GetScreenInfoColorSpace());

  LayerTreeHost()->SetBrowserControlsParams(
      visual_properties.browser_controls_params);

  LayerTreeHost()->SetVisualDeviceViewportSize(
      gfx::ScaleToCeiledSize(visual_properties.visible_viewport_size,
                             screen_info.device_scale_factor));

  client_->UpdateVisualProperties(visual_properties);

  LayerTreeHost()->IncrementVisualUpdateDuration(update_timer.Elapsed());
}

void WidgetBase::UpdateScreenRects(const gfx::Rect& widget_screen_rect,
                                   const gfx::Rect& window_screen_rect,
                                   UpdateScreenRectsCallback callback) {
  if (!client_->UpdateScreenRects(widget_screen_rect, window_screen_rect)) {
    widget_screen_rect_ = widget_screen_rect;
    window_screen_rect_ = window_screen_rect;
  }
  std::move(callback).Run();
}

void WidgetBase::WasHidden() {
  // A provisional frame widget will never be hidden since that would require it
  // to be shown first. A frame must be attached to the frame tree before
  // changing visibility.
  DCHECK(!IsForProvisionalFrame());

  TRACE_EVENT0("renderer", "WidgetBase::WasHidden");

  SetHidden(true);

  tab_switch_time_recorder_.TabWasHidden();

  client_->WasHidden();
}

void WidgetBase::WasShown(bool was_evicted,
                          mojom::blink::RecordContentToVisibleTimeRequestPtr
                              record_tab_switch_time_request) {
  // The frame must be attached to the frame tree (which makes it no longer
  // provisional) before changing visibility.
  DCHECK(!IsForProvisionalFrame());

  TRACE_EVENT_WITH_FLOW0("renderer", "WidgetBase::WasShown", this,
                         TRACE_EVENT_FLAG_FLOW_IN);

  SetHidden(false);

  if (record_tab_switch_time_request) {
    LayerTreeHost()->RequestPresentationTimeForNextFrame(
        tab_switch_time_recorder_.TabWasShown(
            false /* has_saved_frames */,
            record_tab_switch_time_request->event_start_time,
            record_tab_switch_time_request->destination_is_loaded,
            record_tab_switch_time_request->show_reason_tab_switching,
            record_tab_switch_time_request->show_reason_bfcache_restore));
  }

  client_->WasShown(was_evicted);
}

void WidgetBase::RequestPresentationTimeForNextFrame(
    mojom::blink::RecordContentToVisibleTimeRequestPtr visible_time_request) {
  DCHECK(visible_time_request);
  if (is_hidden_)
    return;

  // Tab was shown while widget was already painting, eg. due to being
  // captured.
  LayerTreeHost()->RequestPresentationTimeForNextFrame(
      tab_switch_time_recorder_.TabWasShown(
          false /* has_saved_frames */, visible_time_request->event_start_time,
          visible_time_request->destination_is_loaded,
          visible_time_request->show_reason_tab_switching,
          visible_time_request->show_reason_bfcache_restore));
}

void WidgetBase::CancelPresentationTimeRequest() {
  if (is_hidden_)
    return;

  // Tab was hidden while widget keeps painting, eg. due to being captured.
  tab_switch_time_recorder_.TabWasHidden();
}

void WidgetBase::ApplyViewportChanges(
    const cc::ApplyViewportChangesArgs& args) {
  client_->ApplyViewportChanges(args);
}

void WidgetBase::UpdateCompositorScrollState(
    const cc::CompositorCommitData& commit_data) {
  client_->UpdateCompositorScrollState(commit_data);
}

void WidgetBase::OnDeferMainFrameUpdatesChanged(bool defer) {
  // LayerTreeHost::CreateThreaded() will defer main frame updates immediately
  // until it gets a LocalSurfaceId. That's before the
  // |widget_input_handler_manager_| is created, so it can be null here.
  // TODO(schenney): To avoid ping-ponging between defer main frame states
  // during initialization, and requiring null checks here, we should probably
  // pass the LocalSurfaceId to the compositor while it is
  // initialized so that it doesn't have to immediately switch into deferred
  // mode without being requested to.
  if (!widget_input_handler_manager_)
    return;

  // The input handler wants to know about the mainframe update status to
  // enable/disable input and for metrics.
  widget_input_handler_manager_->OnDeferMainFrameUpdatesChanged(defer);
}

void WidgetBase::OnDeferCommitsChanged(
    bool defer,
    cc::PaintHoldingReason reason,
    absl::optional<cc::PaintHoldingCommitTrigger> trigger) {
  // The input handler wants to know about the commit status for metric purposes
  // and to enable/disable input.
  widget_input_handler_manager_->OnDeferCommitsChanged(defer, reason);
}

void WidgetBase::OnPauseRenderingChanged(bool paused) {
  widget_input_handler_manager_->OnPauseRenderingChanged(paused);
}

void WidgetBase::DidBeginMainFrame() {
  if (base::FeatureList::IsEnabled(features::kRunTextInputUpdatePostLifecycle))
    UpdateTextInputState();
  client_->DidBeginMainFrame();
}

void WidgetBase::RequestNewLayerTreeFrameSink(
    LayerTreeFrameSinkCallback callback) {
  // For widgets that are never visible, we don't start the compositor, so we
  // never get a request for a cc::LayerTreeFrameSink.
  DCHECK(!never_composited_);

  // Provide a hook for testing to provide their own layer tree frame sink, if
  // one is returned just run the callback.
  if (std::unique_ptr<cc::LayerTreeFrameSink> sink =
          client_->AllocateNewLayerTreeFrameSink()) {
    std::move(callback).Run(std::move(sink), nullptr);
    return;
  }

  KURL url = client_->GetURLForDebugTrace();
  // The |url| is not always available, fallback to a fixed string.
  if (url.IsEmpty())
    url = KURL("chrome://gpu/WidgetBase::RequestNewLayerTreeFrameSink");

  // TODO(danakj): This may not be accurate, depending on the intent. A child
  // local root could be in the same process as the view, so if the client is
  // meant to designate the process type, it seems kRenderer would be the
  // correct choice. If client is meant to designate the widget type, then
  // kOOPIF would denote that it is not for the main frame. However, kRenderer
  // would also be used for other widgets such as popups.
  const char* client_name = is_embedded_ ? kOOPIF : kRenderer;
  const bool for_web_tests = WebTestMode();
  // Misconfigured bots (eg. crbug.com/780757) could run web tests on a
  // machine where gpu compositing doesn't work. Don't crash in that case.
  if (for_web_tests && Platform::Current()->IsGpuCompositingDisabled()) {
    LOG(FATAL) << "Web tests require gpu compositing, but it is disabled.";
    return;
  }

  // TODO(jonross): Have this generated by the LayerTreeFrameSink itself, which
  // would then handle binding.
  mojo::PendingRemote<cc::mojom::blink::RenderFrameMetadataObserver>
      render_frame_metadata_observer_remote;
  mojo::PendingRemote<cc::mojom::blink::RenderFrameMetadataObserverClient>
      render_frame_metadata_client_remote;
  mojo::PendingReceiver<cc::mojom::blink::RenderFrameMetadataObserverClient>
      render_frame_metadata_observer_client_receiver =
          render_frame_metadata_client_remote.InitWithNewPipeAndPassReceiver();
  auto render_frame_metadata_observer =
      std::make_unique<RenderFrameMetadataObserverImpl>(
          render_frame_metadata_observer_remote
              .InitWithNewPipeAndPassReceiver(),
          std::move(render_frame_metadata_client_remote));

  auto params = std::make_unique<
      cc::mojo_embedder::AsyncLayerTreeFrameSink::InitParams>();
  params->io_thread_id = Platform::Current()->GetIOThreadId();
  params->compositor_task_runner =
      Platform::Current()->CompositorThreadTaskRunner();
  if (for_web_tests && !params->compositor_task_runner) {
    // The frame sink provider expects a compositor task runner, but we might
    // not have that if we're running web tests in single threaded mode.
    // Set it to be our thread's task runner instead.
    params->compositor_task_runner = main_thread_compositor_task_runner_;
  }

  // The renderer runs animations and layout for animate_only BeginFrames.
  params->wants_animate_only_begin_frames = true;

  // In disable frame rate limit mode, also let the renderer tick as fast as it
  // can. The top level begin frame source will also be running as a back to
  // back begin frame source, but using a synthetic begin frame source here
  // reduces latency when in this mode (at least for frames starting--it
  // potentially increases it for input on the other hand.)
  if (LayerTreeHost()->GetSettings().disable_frame_rate_limit)
    params->synthetic_begin_frame_source = CreateSyntheticBeginFrameSource();

  params->client_name = client_name;

  mojo::PendingReceiver<viz::mojom::blink::CompositorFrameSink>
      compositor_frame_sink_receiver = CrossVariantMojoReceiver<
          viz::mojom::blink::CompositorFrameSinkInterfaceBase>(
          params->pipes.compositor_frame_sink_remote
              .InitWithNewPipeAndPassReceiver());
  mojo::PendingRemote<viz::mojom::blink::CompositorFrameSinkClient>
      compositor_frame_sink_client;
  params->pipes.client_receiver = CrossVariantMojoReceiver<
      viz::mojom::blink::CompositorFrameSinkClientInterfaceBase>(
      compositor_frame_sink_client.InitWithNewPipeAndPassReceiver());

  if (Platform::Current()->IsGpuCompositingDisabled()) {
    DCHECK(!for_web_tests);
    widget_host_->CreateFrameSink(std::move(compositor_frame_sink_receiver),
                                  std::move(compositor_frame_sink_client));
    widget_host_->RegisterRenderFrameMetadataObserver(
        std::move(render_frame_metadata_observer_client_receiver),
        std::move(render_frame_metadata_observer_remote));
    std::move(callback).Run(
        std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>(
            nullptr, nullptr, params.get()),
        std::move(render_frame_metadata_observer));
    return;
  }

  Platform::EstablishGpuChannelCallback finish_callback =
      base::BindOnce(&WidgetBase::FinishRequestNewLayerTreeFrameSink,
                     weak_ptr_factory_.GetWeakPtr(), url,
                     std::move(compositor_frame_sink_receiver),
                     std::move(compositor_frame_sink_client),
                     std::move(render_frame_metadata_observer_client_receiver),
                     std::move(render_frame_metadata_observer_remote),
                     std::move(render_frame_metadata_observer),
                     std::move(params), std::move(callback));
  bool needs_sync_composite_for_test =
      layer_tree_view_ && LayerTreeHost()->in_composite_for_test();
  if (base::FeatureList::IsEnabled(features::kEstablishGpuChannelAsync) &&
      !needs_sync_composite_for_test) {
    Platform::Current()->EstablishGpuChannel(std::move(finish_callback));
  } else {
    scoped_refptr<gpu::GpuChannelHost> gpu_channel_host =
        Platform::Current()->EstablishGpuChannelSync();
    std::move(finish_callback).Run(gpu_channel_host);
  }
}

void WidgetBase::FinishRequestNewLayerTreeFrameSink(
    const KURL& url,
    mojo::PendingReceiver<viz::mojom::blink::CompositorFrameSink>
        compositor_frame_sink_receiver,
    mojo::PendingRemote<viz::mojom::blink::CompositorFrameSinkClient>
        compositor_frame_sink_client,
    mojo::PendingReceiver<cc::mojom::blink::RenderFrameMetadataObserverClient>
        render_frame_metadata_observer_client_receiver,
    mojo::PendingRemote<cc::mojom::blink::RenderFrameMetadataObserver>
        render_frame_metadata_observer_remote,
    std::unique_ptr<RenderFrameMetadataObserverImpl>
        render_frame_metadata_observer,
    std::unique_ptr<cc::mojo_embedder::AsyncLayerTreeFrameSink::InitParams>
        params,
    LayerTreeFrameSinkCallback callback,
    scoped_refptr<gpu::GpuChannelHost> gpu_channel_host) {
  if (Platform::Current()->IsGpuCompositingDisabled()) {
    // GPU compositing was disabled after the check in
    // WidgetBase::RequestNewLayerTreeFrameSink(). Fail and let it retry.
    std::move(callback).Run(nullptr, nullptr);
    return;
  }

  if (!gpu_channel_host) {
    // Wait and try again. We may hear that the compositing mode has switched
    // to software in the meantime.
    std::move(callback).Run(nullptr, nullptr);
    return;
  }

  scoped_refptr<cc::RasterContextProviderWrapper>
      worker_context_provider_wrapper =
          Platform::Current()->SharedCompositorWorkerContextProvider(
              &RasterDarkModeFilterImpl::Instance());
  if (!worker_context_provider_wrapper) {
    // Cause the compositor to wait and try again.
    std::move(callback).Run(nullptr, nullptr);
    return;
  }

  // The renderer compositor context doesn't do a lot of stuff, so we don't
  // expect it to need a lot of space for commands or transfer. Raster and
  // uploads happen on the worker context instead.
  gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext();

  // This is for an offscreen context for the compositor. So the default
  // framebuffer doesn't need alpha, depth, stencil, antialiasing.
  gpu::ContextCreationAttribs attributes;
  attributes.alpha_size = -1;
  attributes.depth_size = 0;
  attributes.stencil_size = 0;
  attributes.samples = 0;
  attributes.sample_buffers = 0;
  attributes.bind_generates_resource = false;
  attributes.lose_context_when_out_of_memory = true;
  attributes.enable_gles2_interface = true;
  attributes.enable_raster_interface = false;
  attributes.enable_oop_rasterization = false;

  constexpr bool automatic_flushes = false;
  constexpr bool support_locking = false;
  constexpr bool support_grcontext = true;
  gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager =
      Platform::Current()->GetGpuMemoryBufferManager();

  auto context_provider =
      base::MakeRefCounted<viz::ContextProviderCommandBuffer>(
          gpu_channel_host, gpu_memory_buffer_manager, kGpuStreamIdDefault,
          kGpuStreamPriorityDefault, gpu::kNullSurfaceHandle, GURL(url),
          automatic_flushes, support_locking, support_grcontext, limits,
          attributes,
          viz::command_buffer_metrics::ContextType::RENDER_COMPOSITOR);

#if BUILDFLAG(IS_ANDROID)
  if (Platform::Current()->IsSynchronousCompositingEnabledForAndroidWebView() &&
      !is_embedded_) {
    // TODO(ericrk): Collapse with non-webview registration below.
    if (::features::IsUsingVizFrameSubmissionForWebView()) {
      widget_host_->CreateFrameSink(std::move(compositor_frame_sink_receiver),
                                    std::move(compositor_frame_sink_client));
    }
    widget_host_->RegisterRenderFrameMetadataObserver(
        std::move(render_frame_metadata_observer_client_receiver),
        std::move(render_frame_metadata_observer_remote));

    std::move(callback).Run(
        std::make_unique<SynchronousLayerTreeFrameSink>(
            std::move(context_provider),
            std::move(worker_context_provider_wrapper),
            Platform::Current()->CompositorThreadTaskRunner(),
            gpu_memory_buffer_manager, g_next_layer_tree_frame_sink_id++,
            std::move(params->synthetic_begin_frame_source),
            widget_input_handler_manager_->GetSynchronousCompositorRegistry(),
            CrossVariantMojoRemote<
                viz::mojom::blink::CompositorFrameSinkInterfaceBase>(
                std::move(params->pipes.compositor_frame_sink_remote)),
            CrossVariantMojoReceiver<
                viz::mojom::blink::CompositorFrameSinkClientInterfaceBase>(
                std::move(params->pipes.client_receiver))),
        std::move(render_frame_metadata_observer));
    return;
  }
#endif
  widget_host_->CreateFrameSink(std::move(compositor_frame_sink_receiver),
                                std::move(compositor_frame_sink_client));
  widget_host_->RegisterRenderFrameMetadataObserver(
      std::move(render_frame_metadata_observer_client_receiver),
      std::move(render_frame_metadata_observer_remote));
  params->gpu_memory_buffer_manager = gpu_memory_buffer_manager;
  std::move(callback).Run(
      std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>(
          std::move(context_provider),
          std::move(worker_context_provider_wrapper), params.get()),
      std::move(render_frame_metadata_observer));
}

void WidgetBase::DidCommitAndDrawCompositorFrame() {
  // NOTE: Tests may break if this event is renamed or moved. See
  // tab_capture_performancetest.cc.
  TRACE_EVENT0("gpu", "WidgetBase::DidCommitAndDrawCompositorFrame");

  client_->DidCommitAndDrawCompositorFrame();
}

void WidgetBase::DidObserveFirstScrollDelay(
    base::TimeDelta first_scroll_delay,
    base::TimeTicks first_scroll_timestamp) {
  client_->DidObserveFirstScrollDelay(first_scroll_delay,
                                      first_scroll_timestamp);
}

void WidgetBase::WillCommitCompositorFrame() {
  client_->BeginCommitCompositorFrame();
}

void WidgetBase::DidCommitCompositorFrame(base::TimeTicks commit_start_time,
                                          base::TimeTicks commit_finish_time) {
  client_->EndCommitCompositorFrame(commit_start_time, commit_finish_time);
}

void WidgetBase::DidCompletePageScaleAnimation() {
  client_->DidCompletePageScaleAnimation();
}

void WidgetBase::RecordStartOfFrameMetrics() {
  client_->RecordStartOfFrameMetrics();
}

void WidgetBase::RecordEndOfFrameMetrics(
    base::TimeTicks frame_begin_time,
    cc::ActiveFrameSequenceTrackers trackers) {
  client_->RecordEndOfFrameMetrics(frame_begin_time, trackers);
}

std::unique_ptr<cc::BeginMainFrameMetrics>
WidgetBase::GetBeginMainFrameMetrics() {
  return client_->GetBeginMainFrameMetrics();
}

std::unique_ptr<cc::WebVitalMetrics> WidgetBase::GetWebVitalMetrics() {
  return client_->GetWebVitalMetrics();
}

void WidgetBase::BeginUpdateLayers() {
  client_->BeginUpdateLayers();
}

void WidgetBase::EndUpdateLayers() {
  client_->EndUpdateLayers();
}

void WidgetBase::WillBeginMainFrame() {
  TRACE_EVENT0("gpu", "WidgetBase::WillBeginMainFrame");
  client_->SetSuppressFrameRequestsWorkaroundFor704763Only(true);
  client_->WillBeginMainFrame();
  UpdateSelectionBounds();
  // UpdateTextInputState() will cause a forced style and layout update, which
  // we would like to eliminate.
  if (!base::FeatureList::IsEnabled(features::kRunTextInputUpdatePostLifecycle))
    UpdateTextInputState();
}

void WidgetBase::RunPaintBenchmark(int repeat_count,
                                   cc::PaintBenchmarkResult& result) {
  client_->RunPaintBenchmark(repeat_count, result);
}

void WidgetBase::ScheduleAnimationForWebTests() {
  client_->ScheduleAnimationForWebTests();
}

void WidgetBase::SetCompositorVisible(bool visible) {
  if (never_composited_)
    return;

  layer_tree_view_->SetVisible(visible);
}

void WidgetBase::UpdateVisualState() {
  base::ElapsedTimer update_timer;
  // When recording main frame metrics set the lifecycle reason to
  // kBeginMainFrame, because this is the calller of UpdateLifecycle
  // for the main frame. Otherwise, set the reason to kTests, which is
  // the only other reason this method is called.
  DocumentUpdateReason lifecycle_reason =
      ShouldRecordBeginMainFrameMetrics()
          ? DocumentUpdateReason::kBeginMainFrame
          : DocumentUpdateReason::kTest;
  client_->UpdateLifecycle(WebLifecycleUpdate::kAll, lifecycle_reason);
  client_->SetSuppressFrameRequestsWorkaroundFor704763Only(false);
  LayerTreeHost()->IncrementVisualUpdateDuration(update_timer.Elapsed());
}

void WidgetBase::BeginMainFrame(base::TimeTicks frame_time) {
  base::TimeTicks raf_aligned_input_start_time;
  if (ShouldRecordBeginMainFrameMetrics()) {
    raf_aligned_input_start_time = base::TimeTicks::Now();
  }

  auto weak_this = weak_ptr_factory_.GetWeakPtr();
  widget_input_handler_manager_->input_event_queue()->DispatchRafAlignedInput(
      frame_time);
  // DispatchRafAlignedInput could have detached the frame.
  if (!weak_this)
    return;

  if (ShouldRecordBeginMainFrameMetrics()) {
    client_->RecordDispatchRafAlignedInputTime(raf_aligned_input_start_time);
  }
  client_->BeginMainFrame(frame_time);
}

bool WidgetBase::ShouldRecordBeginMainFrameMetrics() {
  // We record metrics only when running in multi-threaded mode, not
  // single-thread mode for testing.
  return Thread::CompositorThread();
}

void WidgetBase::AddPresentationCallback(
    uint32_t frame_token,
    base::OnceCallback<void(base::TimeTicks)> callback) {
  layer_tree_view_->AddPresentationCallback(frame_token, std::move(callback));
}

#if BUILDFLAG(IS_MAC)
void WidgetBase::AddCoreAnimationErrorCodeCallback(
    uint32_t frame_token,
    base::OnceCallback<void(gfx::CALayerResult)> callback) {
  layer_tree_view_->AddCoreAnimationErrorCodeCallback(frame_token,
                                                      std::move(callback));
}
#endif

void WidgetBase::SetCursor(const ui::Cursor& cursor) {
  if (input_handler_.DidChangeCursor(cursor)) {
    widget_host_->SetCursor(cursor);
  }
}

void WidgetBase::UpdateTooltipUnderCursor(const String& tooltip_text,
                                          TextDirection dir) {
  widget_host_->UpdateTooltipUnderCursor(
      tooltip_text.empty() ? "" : tooltip_text, ToBaseTextDirection(dir));
}

void WidgetBase::UpdateTooltipFromKeyboard(const String& tooltip_text,
                                           TextDirection dir,
                                           const gfx::Rect& bounds) {
  widget_host_->UpdateTooltipFromKeyboard(
      tooltip_text.empty() ? "" : tooltip_text, ToBaseTextDirection(dir),
      BlinkSpaceToEnclosedDIPs(bounds));
}

void WidgetBase::ClearKeyboardTriggeredTooltip() {
  widget_host_->ClearKeyboardTriggeredTooltip();
}

void WidgetBase::ShowVirtualKeyboard() {
  UpdateTextInputStateInternal(true, false);
}

void WidgetBase::UpdateTextInputState() {
  UpdateTextInputStateInternal(false, false);
}

bool WidgetBase::CanComposeInline() {
  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return true;
  return frame_widget->CanComposeInline();
}

void WidgetBase::UpdateTextInputStateInternal(bool show_virtual_keyboard,
                                              bool reply_to_request) {
  TRACE_EVENT0("renderer", "WidgetBase::UpdateTextInputStateInternal");
  if (ime_event_guard_) {
    DCHECK(!reply_to_request);
    if (show_virtual_keyboard)
      ime_event_guard_->set_show_virtual_keyboard(true);
    return;
  }
  ui::TextInputType new_type = GetTextInputType();
  if (IsDateTimeInput(new_type))
    return;  // Not considered as a text input field in WebKit/Chromium.

  FrameWidget* frame_widget = client_->FrameWidget();

  blink::WebTextInputInfo new_info;
  ui::mojom::VirtualKeyboardVisibilityRequest last_vk_visibility_request =
      ui::mojom::VirtualKeyboardVisibilityRequest::NONE;
  bool always_hide_ime = false;
  absl::optional<gfx::Rect> control_bounds;
  absl::optional<gfx::Rect> selection_bounds;
  if (frame_widget) {
    new_info = frame_widget->TextInputInfo();
    // This will be used to decide whether or not to show VK when VK policy is
    // manual.
    last_vk_visibility_request =
        frame_widget->GetLastVirtualKeyboardVisibilityRequest();

    // Check whether the keyboard should always be hidden for the currently
    // focused element.
    always_hide_ime = frame_widget->ShouldSuppressKeyboardForFocusedElement();
    frame_widget->GetEditContextBoundsInWindow(&control_bounds,
                                               &selection_bounds);
  }
  const ui::TextInputMode new_mode =
      ConvertWebTextInputMode(new_info.input_mode);
  const ui::mojom::VirtualKeyboardPolicy new_vk_policy =
      new_info.virtual_keyboard_policy;
  bool new_can_compose_inline = CanComposeInline();

  // Only sends text input params if they are changed or if the ime should be
  // shown.
  if (show_virtual_keyboard || reply_to_request ||
      text_input_type_ != new_type || text_input_mode_ != new_mode ||
      text_input_info_ != new_info || !new_info.ime_text_spans.empty() ||
      can_compose_inline_ != new_can_compose_inline ||
      always_hide_ime_ != always_hide_ime || vk_policy_ != new_vk_policy ||
      (new_vk_policy == ui::mojom::VirtualKeyboardPolicy::MANUAL &&
       (last_vk_visibility_request !=
        ui::mojom::VirtualKeyboardVisibilityRequest::NONE)) ||
      (control_bounds && frame_control_bounds_ != control_bounds) ||
      (selection_bounds && frame_selection_bounds_ != selection_bounds)) {
    ui::mojom::blink::TextInputStatePtr params =
        ui::mojom::blink::TextInputState::New();
    params->node_id = new_info.node_id;
    params->type = new_type;
    params->mode = new_mode;
    params->action = new_info.action;
    params->flags = new_info.flags;
    params->vk_policy = new_vk_policy;
    params->last_vk_visibility_request = last_vk_visibility_request;
    params->edit_context_control_bounds = control_bounds;
    params->edit_context_selection_bounds = selection_bounds;

    if (!new_info.ime_text_spans.empty()) {
      params->ime_text_spans_info =
          frame_widget->GetImeTextSpansInfo(new_info.ime_text_spans);
    }
#if BUILDFLAG(IS_ANDROID)
    if (next_previous_flags_ == kInvalidNextPreviousFlagsValue) {
      // Due to a focus change, values will be reset by the frame.
      // That case we only need fresh NEXT/PREVIOUS information.
      // Also we won't send WidgetHostMsg_TextInputStateChanged if next/previous
      // focusable status is changed.
      if (frame_widget) {
        next_previous_flags_ =
            frame_widget->ComputeWebTextInputNextPreviousFlags();
      } else {
        // For safety in case GetInputMethodController() is null, because -1 is
        // invalid value to send to browser process.
        next_previous_flags_ = 0;
      }
    }
#else
    next_previous_flags_ = 0;
#endif
    params->flags |= next_previous_flags_;
    params->value = new_info.value;
    params->selection =
        gfx::Range(new_info.selection_start, new_info.selection_end);
    if (new_info.composition_start != -1) {
      params->composition =
          gfx::Range(new_info.composition_start, new_info.composition_end);
    }
    params->can_compose_inline = new_can_compose_inline;
    // TODO(changwan): change instances of show_ime_if_needed to
    // show_virtual_keyboard.
    params->show_ime_if_needed = show_virtual_keyboard;
    params->always_hide_ime = always_hide_ime;
    params->reply_to_request = reply_to_request;
    widget_host_->TextInputStateChanged(std::move(params));

    text_input_info_ = new_info;
    text_input_type_ = new_type;
    text_input_mode_ = new_mode;
    vk_policy_ = new_vk_policy;
    can_compose_inline_ = new_can_compose_inline;
    always_hide_ime_ = always_hide_ime;
    text_input_flags_ = new_info.flags;
    frame_control_bounds_ = control_bounds.value_or(gfx::Rect());
    // Selection bounds are not populated in non-EditContext scenarios.
    // It is communicated to IMEs via |WidgetBase::UpdateSelectionBounds|.
    frame_selection_bounds_ = selection_bounds.value_or(gfx::Rect());
    // Reset the show/hide state in the InputMethodController.
    if (frame_widget) {
      if (last_vk_visibility_request !=
          ui::mojom::VirtualKeyboardVisibilityRequest::NONE) {
        // Reset the visibility state.
        frame_widget->ResetVirtualKeyboardVisibilityRequest();
      }
    }

#if BUILDFLAG(IS_ANDROID)
    // If we send a new TextInputStateChanged message, we must also deliver a
    // new RenderFrameMetadata, as the IME will need this info to be updated.
    // TODO(ericrk): Consider folding the above IPC into RenderFrameMetadata.
    // https://crbug.com/912309
    // Compositing might not be initialized but input can still be dispatched
    // to non-composited widgets so LayerTreeHost may be null.
    if (layer_tree_view_)
      LayerTreeHost()->RequestForceSendMetadata();
#endif
  }
}

void WidgetBase::ClearTextInputState() {
  text_input_info_ = blink::WebTextInputInfo();
  text_input_type_ = ui::TextInputType::TEXT_INPUT_TYPE_NONE;
  text_input_mode_ = ui::TextInputMode::TEXT_INPUT_MODE_DEFAULT;
  can_compose_inline_ = false;
  text_input_flags_ = 0;
  next_previous_flags_ = kInvalidNextPreviousFlagsValue;
}

void WidgetBase::ShowVirtualKeyboardOnElementFocus() {
#if BUILDFLAG(IS_CHROMEOS)
  // On ChromeOS, virtual keyboard is triggered only when users leave the
  // mouse button or the finger and a text input element is focused at that
  // time. Focus event itself shouldn't trigger virtual keyboard.
  UpdateTextInputState();
#else
  ShowVirtualKeyboard();
#endif

// TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with
// virtual keyboard.
#if !BUILDFLAG(IS_ANDROID)
  client_->FocusChangeComplete();
#endif
}

void WidgetBase::ProcessTouchAction(cc::TouchAction touch_action) {
  if (!input_handler_.ProcessTouchAction(touch_action))
    return;
  widget_input_handler_manager_->ProcessTouchAction(touch_action);
}

void WidgetBase::SetFocus(mojom::blink::FocusState focus_state) {
  has_focus_ = focus_state == mojom::blink::FocusState::kFocused;
  client_->FocusChanged(focus_state);
}

void WidgetBase::BindWidgetCompositor(
    mojo::PendingReceiver<mojom::blink::WidgetCompositor> receiver) {
  if (widget_compositor_)
    widget_compositor_->Shutdown();

  widget_compositor_ = base::MakeRefCounted<WidgetCompositor>(
      weak_ptr_factory_.GetWeakPtr(),
      LayerTreeHost()->GetTaskRunnerProvider()->MainThreadTaskRunner(),
      LayerTreeHost()->GetTaskRunnerProvider()->ImplThreadTaskRunner(),
      std::move(receiver));
}

void WidgetBase::UpdateCompositionInfo(bool immediate_request) {
  if (!monitor_composition_info_ && !immediate_request)
    return;  // Do not calculate composition info if not requested.

  TRACE_EVENT0("renderer", "WidgetBase::UpdateCompositionInfo");
  gfx::Range range;
  Vector<gfx::Rect> character_bounds;

  if (GetTextInputType() == ui::TextInputType::TEXT_INPUT_TYPE_NONE) {
    // Composition information is only available on editable node.
    range = gfx::Range::InvalidRange();
  } else {
    GetCompositionRange(&range);
    GetCompositionCharacterBounds(&character_bounds);
  }

  if (!immediate_request &&
      !ShouldUpdateCompositionInfo(range, character_bounds)) {
    return;
  }
  composition_character_bounds_ = character_bounds;
  composition_range_ = range;

  if (mojom::blink::WidgetInputHandlerHost* host =
          widget_input_handler_manager_->GetWidgetInputHandlerHost()) {
    host->ImeCompositionRangeChanged(composition_range_,
                                     composition_character_bounds_);
  }
}

void WidgetBase::ForceTextInputStateUpdate() {
#if BUILDFLAG(IS_ANDROID)
  UpdateSelectionBounds();
  UpdateTextInputStateInternal(false, true /* reply_to_request */);
#endif
}

void WidgetBase::RequestCompositionUpdates(bool immediate_request,
                                           bool monitor_updates) {
  monitor_composition_info_ = monitor_updates;
  if (!immediate_request)
    return;
  UpdateCompositionInfo(true /* immediate request */);
}

void WidgetBase::GetCompositionRange(gfx::Range* range) {
  *range = gfx::Range::InvalidRange();
  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  *range = frame_widget->CompositionRange();
}

void WidgetBase::GetCompositionCharacterBounds(Vector<gfx::Rect>* bounds) {
  DCHECK(bounds);
  bounds->clear();

  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;

  frame_widget->GetCompositionCharacterBoundsInWindow(bounds);
}

bool WidgetBase::ShouldUpdateCompositionInfo(const gfx::Range& range,
                                             const Vector<gfx::Rect>& bounds) {
  if (!range.IsValid())
    return false;
  if (composition_range_ != range)
    return true;
  if (bounds.size() != composition_character_bounds_.size())
    return true;
  for (wtf_size_t i = 0; i < bounds.size(); ++i) {
    if (bounds[i] != composition_character_bounds_[i])
      return true;
  }
  return false;
}

void WidgetBase::SetHidden(bool hidden) {
  // A provisional frame widget will never be shown or hidden, as the frame must
  // be attached to the frame tree before changing visibility.
  DCHECK(!IsForProvisionalFrame());

  if (is_hidden_ == hidden)
    return;

  // The status has changed.  Tell the RenderThread about it and ensure
  // throttled acks are released in case frame production ceases.
  is_hidden_ = hidden;

  if (widget_scheduler_)
    widget_scheduler_->SetHidden(hidden);

  // If the renderer was hidden, resolve any pending synthetic gestures so they
  // aren't blocked waiting for a compositor frame to be generated.
  if (is_hidden_)
    FlushInputProcessedCallback();

  SetCompositorVisible(!is_hidden_);
}

ui::TextInputType WidgetBase::GetTextInputType() {
  return ConvertWebTextInputType(client_->GetTextInputType());
}

void WidgetBase::UpdateSelectionBounds() {
  TRACE_EVENT0("renderer", "WidgetBase::UpdateSelectionBounds");
  if (ime_event_guard_)
    return;
#if defined(USE_AURA)
  // TODO(mohsen): For now, always send explicit selection IPC notifications for
  // Aura beucause composited selection updates are not working for webview tags
  // which regresses IME inside webview. Remove this when composited selection
  // updates are fixed for webviews. See, http://crbug.com/510568.
  bool send_ipc = true;
#else
  // With composited selection updates, the selection bounds will be reported
  // directly by the compositor, in which case explicit IPC selection
  // notifications should be suppressed.
  bool send_ipc = !RuntimeEnabledFeatures::CompositedSelectionUpdateEnabled();
#endif
  if (send_ipc) {
    bool is_anchor_first = false;
    base::i18n::TextDirection focus_dir =
        base::i18n::TextDirection::UNKNOWN_DIRECTION;
    base::i18n::TextDirection anchor_dir =
        base::i18n::TextDirection::UNKNOWN_DIRECTION;

    FrameWidget* frame_widget = client_->FrameWidget();
    if (!frame_widget)
      return;
    if (frame_widget->GetSelectionBoundsInWindow(
            &selection_focus_rect_, &selection_anchor_rect_,
            &selection_bounding_box_, &focus_dir, &anchor_dir,
            &is_anchor_first)) {
      widget_host_->SelectionBoundsChanged(
          selection_anchor_rect_, anchor_dir, selection_focus_rect_, focus_dir,
          selection_bounding_box_, is_anchor_first);
    }
  }
  UpdateCompositionInfo(false /* not an immediate request */);
}

void WidgetBase::MouseCaptureLost() {
  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  frame_widget->MouseCaptureLost();
}

void WidgetBase::SetEditCommandsForNextKeyEvent(
    Vector<mojom::blink::EditCommandPtr> edit_commands) {
  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  frame_widget->SetEditCommandsForNextKeyEvent(std::move(edit_commands));
}

void WidgetBase::CursorVisibilityChange(bool is_visible) {
  client_->SetCursorVisibilityState(is_visible);
}

void WidgetBase::SetMouseCapture(bool capture) {
  if (mojom::blink::WidgetInputHandlerHost* host =
          widget_input_handler_manager_->GetWidgetInputHandlerHost()) {
    host->SetMouseCapture(capture);
  }
}

void WidgetBase::ImeSetComposition(
    const String& text,
    const Vector<ui::ImeTextSpan>& ime_text_spans,
    const gfx::Range& replacement_range,
    int selection_start,
    int selection_end) {
  if (!ShouldHandleImeEvents())
    return;

  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  if (frame_widget->ShouldDispatchImeEventsToPlugin()) {
    frame_widget->ImeSetCompositionForPlugin(text, ime_text_spans,
                                             replacement_range, selection_start,
                                             selection_end);
    return;
  }

  ImeEventGuard guard(weak_ptr_factory_.GetWeakPtr());
  if (!frame_widget->SetComposition(text, ime_text_spans, replacement_range,
                                    selection_start, selection_end)) {
    // If we failed to set the composition text, then we need to let the browser
    // process to cancel the input method's ongoing composition session, to make
    // sure we are in a consistent state.
    if (mojom::blink::WidgetInputHandlerHost* host =
            widget_input_handler_manager_->GetWidgetInputHandlerHost()) {
      host->ImeCancelComposition();
    }
  }
  UpdateCompositionInfo(false /* not an immediate request */);
}

void WidgetBase::ImeCommitText(const String& text,
                               const Vector<ui::ImeTextSpan>& ime_text_spans,
                               const gfx::Range& replacement_range,
                               int relative_cursor_pos) {
  if (!ShouldHandleImeEvents())
    return;

  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  if (frame_widget->ShouldDispatchImeEventsToPlugin()) {
    frame_widget->ImeCommitTextForPlugin(
        text, ime_text_spans, replacement_range, relative_cursor_pos);
    return;
  }

  ImeEventGuard guard(weak_ptr_factory_.GetWeakPtr());
  input_handler_.set_handling_input_event(true);
  frame_widget->CommitText(text, ime_text_spans, replacement_range,
                           relative_cursor_pos);
  input_handler_.set_handling_input_event(false);
  UpdateCompositionInfo(false /* not an immediate request */);
}

void WidgetBase::ImeFinishComposingText(bool keep_selection) {
  if (!ShouldHandleImeEvents())
    return;

  FrameWidget* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return;
  if (frame_widget->ShouldDispatchImeEventsToPlugin()) {
    frame_widget->ImeFinishComposingTextForPlugin(keep_selection);
    return;
  }

  ImeEventGuard guard(weak_ptr_factory_.GetWeakPtr());
  input_handler_.set_handling_input_event(true);
  frame_widget->FinishComposingText(keep_selection);
  input_handler_.set_handling_input_event(false);
  UpdateCompositionInfo(false /* not an immediate request */);
}

void WidgetBase::QueueSyntheticEvent(
    std::unique_ptr<WebCoalescedInputEvent> event) {
  client_->WillQueueSyntheticEvent(*event);

  // TODO(acomminos): If/when we add support for gesture event attribution on
  //                  the impl thread, have the caller provide attribution.
  WebInputEventAttribution attribution;
  widget_input_handler_manager_->input_event_queue()->HandleEvent(
      std::move(event), MainThreadEventQueue::DispatchType::kNonBlocking,
      mojom::blink::InputEventResultState::kNotConsumed, attribution, nullptr,
      HandledEventCallback());
}

bool WidgetBase::IsForProvisionalFrame() {
  auto* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return false;
  return frame_widget->IsProvisional();
}

bool WidgetBase::ShouldHandleImeEvents() {
  auto* frame_widget = client_->FrameWidget();
  if (!frame_widget)
    return false;
  return frame_widget->ShouldHandleImeEvents();
}

void WidgetBase::RequestPresentationAfterScrollAnimationEnd(
    mojom::blink::Widget::ForceRedrawCallback callback) {
  LayerTreeHost()->RequestScrollAnimationEndNotification(
      base::BindOnce(&WidgetBase::ForceRedraw, weak_ptr_factory_.GetWeakPtr(),
                     std::move(callback)));
}

void WidgetBase::FlushInputProcessedCallback() {
  widget_input_handler_manager_->InvokeInputProcessedCallback();
}

void WidgetBase::CancelCompositionForPepper() {
  if (mojom::blink::WidgetInputHandlerHost* host =
          widget_input_handler_manager_->GetWidgetInputHandlerHost()) {
    host->ImeCancelComposition();
  }
#if BUILDFLAG(IS_MAC) || defined(USE_AURA)
  UpdateCompositionInfo(false /* not an immediate request */);
#endif
}

void WidgetBase::OnImeEventGuardStart(ImeEventGuard* guard) {
  if (!ime_event_guard_)
    ime_event_guard_ = guard;
}

void WidgetBase::OnImeEventGuardFinish(ImeEventGuard* guard) {
  if (ime_event_guard_ != guard)
    return;
  ime_event_guard_ = nullptr;

  // While handling an ime event, text input state and selection bounds updates
  // are ignored. These must explicitly be updated once finished handling the
  // ime event.
  UpdateSelectionBounds();
#if BUILDFLAG(IS_ANDROID)
  if (guard->show_virtual_keyboard())
    ShowVirtualKeyboard();
  else
    UpdateTextInputState();
#endif
}

void WidgetBase::RequestAnimationAfterDelay(const base::TimeDelta& delay) {
  if (delay.is_zero()) {
    client_->ScheduleAnimation();
    return;
  }

  // Consolidate delayed animation frame requests to keep only the longest
  // delay.
  if (request_animation_after_delay_timer_.IsActive() &&
      request_animation_after_delay_timer_.NextFireInterval() > delay) {
    request_animation_after_delay_timer_.Stop();
  }
  if (!request_animation_after_delay_timer_.IsActive()) {
    request_animation_after_delay_timer_.StartOneShot(delay, FROM_HERE);
  }
}

void WidgetBase::RequestAnimationAfterDelayTimerFired(TimerBase*) {
  client_->ScheduleAnimation();
}

float WidgetBase::GetOriginalDeviceScaleFactor() const {
  return client_->GetOriginalScreenInfos().current().device_scale_factor;
}

void WidgetBase::UpdateSurfaceAndScreenInfo(
    const viz::LocalSurfaceId& new_local_surface_id,
    const gfx::Rect& compositor_viewport_pixel_rect,
    const display::ScreenInfos& screen_infos) {
  display::ScreenInfos new_screen_infos = screen_infos;
  display::ScreenInfo& new_screen_info = new_screen_infos.mutable_current();

  // If there is a screen orientation override apply it.
  if (auto orientation_override = client_->ScreenOrientationOverride()) {
    new_screen_info.orientation_type = orientation_override.value();
    new_screen_info.orientation_angle =
        OrientationTypeToAngle(new_screen_info.orientation_type);
  }

  // RenderWidgetHostImpl::SynchronizeVisualProperties uses similar logic to
  // detect orientation changes on the display currently showing the widget.
  const display::ScreenInfo& previous_screen_info = screen_infos_.current();
  bool orientation_changed =
      previous_screen_info.orientation_angle !=
          new_screen_info.orientation_angle ||
      previous_screen_info.orientation_type != new_screen_info.orientation_type;
  display::ScreenInfos previous_original_screen_infos =
      client_->GetOriginalScreenInfos();

  local_surface_id_from_parent_ = new_local_surface_id;
  screen_infos_ = new_screen_infos;

  // Note carefully that the DSF specified in |new_screen_info| is not the
  // DSF used by the compositor during device emulation!
  LayerTreeHost()->SetViewportRectAndScale(compositor_viewport_pixel_rect,
                                           GetOriginalDeviceScaleFactor(),
                                           local_surface_id_from_parent_);
  // The VisualDeviceViewportIntersectionRect derives from the LayerTreeView's
  // viewport size, which is set above.
  LayerTreeHost()->SetVisualDeviceViewportIntersectionRect(
      client_->ViewportVisibleRect());
  if (display::Display::HasForceRasterColorProfile()) {
    LayerTreeHost()->SetDisplayColorSpaces(gfx::DisplayColorSpaces(
        display::Display::GetForcedRasterColorProfile()));
  } else {
    LayerTreeHost()->SetDisplayColorSpaces(
        screen_infos_.current().display_color_spaces);
  }

  if (orientation_changed)
    client_->OrientationChanged();

  client_->DidUpdateSurfaceAndScreen(previous_original_screen_infos);
}

void WidgetBase::UpdateScreenInfo(
    const display::ScreenInfos& new_screen_infos) {
  UpdateSurfaceAndScreenInfo(local_surface_id_from_parent_,
                             CompositorViewportRect(), new_screen_infos);
}

void WidgetBase::UpdateCompositorViewportAndScreenInfo(
    const gfx::Rect& compositor_viewport_pixel_rect,
    const display::ScreenInfos& new_screen_infos) {
  UpdateSurfaceAndScreenInfo(local_surface_id_from_parent_,
                             compositor_viewport_pixel_rect, new_screen_infos);
}

void WidgetBase::UpdateCompositorViewportRect(
    const gfx::Rect& compositor_viewport_pixel_rect) {
  UpdateSurfaceAndScreenInfo(local_surface_id_from_parent_,
                             compositor_viewport_pixel_rect, screen_infos_);
}

void WidgetBase::UpdateSurfaceAndCompositorRect(
    const viz::LocalSurfaceId& new_local_surface_id,
    const gfx::Rect& compositor_viewport_pixel_rect) {
  UpdateSurfaceAndScreenInfo(new_local_surface_id,
                             compositor_viewport_pixel_rect, screen_infos_);
}

const display::ScreenInfo& WidgetBase::GetScreenInfo() {
  return screen_infos_.current();
}

void WidgetBase::SetScreenRects(const gfx::Rect& widget_screen_rect,
                                const gfx::Rect& window_screen_rect) {
  widget_screen_rect_ = widget_screen_rect;
  window_screen_rect_ = window_screen_rect;
}

void WidgetBase::SetPendingWindowRect(const gfx::Rect& rect) {
  pending_window_rect_count_++;
  pending_window_rect_ = rect;
  // Popups don't get size updates back from the browser so just store the set
  // values.
  if (!client_->FrameWidget()) {
    SetScreenRects(rect, rect);
  }
}

void WidgetBase::AckPendingWindowRect() {
  DCHECK(pending_window_rect_count_);
  pending_window_rect_count_--;
  if (pending_window_rect_count_ == 0)
    pending_window_rect_.reset();
}

gfx::Rect WidgetBase::WindowRect() {
  gfx::Rect rect;
  if (pending_window_rect_) {
    // NOTE(mbelshe): If there is a pending_window_rect_, then getting
    // the RootWindowRect is probably going to return wrong results since the
    // browser may not have processed the Move yet.  There isn't really anything
    // good to do in this case, and it shouldn't happen - since this size is
    // only really needed for windowToScreen, which is only used for Popups.
    rect = pending_window_rect_.value();
  } else {
    rect = window_screen_rect_;
  }

  client_->ScreenRectToEmulated(rect);
  return rect;
}

gfx::Rect WidgetBase::ViewRect() {
  gfx::Rect rect = widget_screen_rect_;
  client_->ScreenRectToEmulated(rect);
  return rect;
}

gfx::Rect WidgetBase::CompositorViewportRect() const {
  return LayerTreeHost()->device_viewport_rect();
}

bool WidgetBase::ComputePreferCompositingToLCDText() {
  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kDisablePreferCompositingToLCDText))
    return false;
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
  // On Android, we never have subpixel antialiasing. On Chrome OS we prefer to
  // composite all scrollers for better scrolling performance.
  return true;
#else
  // Prefer compositing if the device scale is high enough that losing subpixel
  // antialiasing won't have a noticeable effect on text quality.
  // Note: We should keep kHighDPIDeviceScaleFactorThreshold in
  // cc/metrics/lcd_text_metrics_reporter.cc the same as the value below.
  if (screen_infos_.current().device_scale_factor >= 1.5f)
    return true;
  if (command_line.HasSwitch(switches::kEnablePreferCompositingToLCDText))
    return true;
  if (!Platform::Current()->IsLcdTextEnabled())
    return true;
  if (base::FeatureList::IsEnabled(features::kPreferCompositingToLCDText))
    return true;
  return false;
#endif
}

void WidgetBase::CountDroppedPointerDownForEventTiming(unsigned count) {
  client_->CountDroppedPointerDownForEventTiming(count);
}

gfx::PointF WidgetBase::DIPsToBlinkSpace(const gfx::PointF& point) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  return gfx::ScalePoint(point, GetOriginalDeviceScaleFactor());
}

gfx::Point WidgetBase::DIPsToRoundedBlinkSpace(const gfx::Point& point) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  return gfx::ScaleToRoundedPoint(point, GetOriginalDeviceScaleFactor());
}

gfx::PointF WidgetBase::BlinkSpaceToDIPs(const gfx::PointF& point) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  return gfx::ScalePoint(point, 1.f / GetOriginalDeviceScaleFactor());
}

gfx::Point WidgetBase::BlinkSpaceToFlooredDIPs(const gfx::Point& point) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  float reverse = 1 / GetOriginalDeviceScaleFactor();
  return gfx::ScaleToFlooredPoint(point, reverse);
}

gfx::Size WidgetBase::DIPsToCeiledBlinkSpace(const gfx::Size& size) {
  return gfx::ScaleToCeiledSize(size, GetOriginalDeviceScaleFactor());
}

gfx::RectF WidgetBase::DIPsToBlinkSpace(const gfx::RectF& rect) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  return gfx::ScaleRect(rect, GetOriginalDeviceScaleFactor());
}

float WidgetBase::DIPsToBlinkSpace(float scalar) {
  // TODO(danakj): Should this use non-original scale factor so it changes under
  // emulation?
  return GetOriginalDeviceScaleFactor() * scalar;
}

gfx::Size WidgetBase::BlinkSpaceToFlooredDIPs(const gfx::Size& size) {
  float reverse = 1 / GetOriginalDeviceScaleFactor();
  return gfx::ScaleToFlooredSize(size, reverse);
}

gfx::Rect WidgetBase::BlinkSpaceToEnclosedDIPs(const gfx::Rect& rect) {
  float reverse = 1 / GetOriginalDeviceScaleFactor();
  return gfx::ScaleToEnclosedRect(rect, reverse);
}

gfx::RectF WidgetBase::BlinkSpaceToDIPs(const gfx::RectF& rect) {
  float reverse = 1 / GetOriginalDeviceScaleFactor();
  return gfx::ScaleRect(rect, reverse);
}

}  // namespace blink