/
render_widget_host_view_android.cc
2818 lines (2441 loc) · 104 KB
/
render_widget_host_view_android.cc
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include <android/bitmap.h>
#include <limits>
#include <utility>
#include "base/android/build_info.h"
#include "base/android/callback_android.h"
#include "base/android/jni_string.h"
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/thread_task_runner_handle.h"
#include "cc/base/math_util.h"
#include "cc/layers/layer.h"
#include "cc/layers/surface_layer.h"
#include "cc/trees/latency_info_swap_promise.h"
#include "cc/trees/layer_tree_host.h"
#include "components/viz/common/features.h"
#include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/surfaces/frame_sink_id_allocator.h"
#include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "content/browser/accessibility/browser_accessibility_manager_android.h"
#include "content/browser/accessibility/web_contents_accessibility_android.h"
#include "content/browser/android/gesture_listener_manager.h"
#include "content/browser/android/ime_adapter_android.h"
#include "content/browser/android/overscroll_controller_android.h"
#include "content/browser/android/selection/selection_popup_controller.h"
#include "content/browser/android/synchronous_compositor_host.h"
#include "content/browser/android/text_suggestion_host_android.h"
#include "content/browser/bad_message.h"
#include "content/browser/compositor/surface_utils.h"
#include "content/browser/devtools/render_frame_devtools_agent_host.h"
#include "content/browser/gpu/gpu_process_host.h"
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/browser/renderer_host/delegated_frame_host_client_android.h"
#include "content/browser/renderer_host/input/input_router.h"
#include "content/browser/renderer_host/input/synthetic_gesture_target_android.h"
#include "content/browser/renderer_host/input/touch_selection_controller_client_manager_android.h"
#include "content/browser/renderer_host/input/web_input_event_builders_android.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
#include "content/browser/renderer_host/ui_events_helper.h"
#include "content/browser/renderer_host/visible_time_request_trigger.h"
#include "content/common/content_switches_internal.h"
#include "content/public/android/content_jni_headers/RenderWidgetHostViewImpl_jni.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/android/synchronous_compositor_client.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/use_zoom_for_dsf_policy.h"
#include "third_party/blink/public/mojom/input/input_handler.mojom-blink.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "ui/android/view_android_observer.h"
#include "ui/android/window_android.h"
#include "ui/android/window_android_compositor.h"
#include "ui/base/layout.h"
#include "ui/base/ui_base_types.h"
#include "ui/display/display_util.h"
#include "ui/events/android/gesture_event_android.h"
#include "ui/events/android/gesture_event_type.h"
#include "ui/events/android/motion_event_android.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/blink/blink_features.h"
#include "ui/events/blink/did_overscroll_params.h"
#include "ui/events/blink/web_input_event_traits.h"
#include "ui/events/event_utils.h"
#include "ui/events/gesture_detection/gesture_provider_config_helper.h"
#include "ui/gfx/android/view_configuration.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/touch_selection/selection_event_type.h"
#include "ui/touch_selection/touch_selection_controller.h"
namespace content {
namespace {
static const char kAsyncReadBackString[] = "Compositing.CopyFromSurfaceTime";
static const base::TimeDelta kClickCountInterval = base::Seconds(0.5);
static const float kClickCountRadiusSquaredDIP = 25;
std::unique_ptr<ui::TouchSelectionController> CreateSelectionController(
ui::TouchSelectionControllerClient* client,
bool has_view_tree) {
DCHECK(client);
DCHECK(has_view_tree);
ui::TouchSelectionController::Config config;
config.max_tap_duration =
base::Milliseconds(gfx::ViewConfiguration::GetLongPressTimeoutInMs());
config.tap_slop = gfx::ViewConfiguration::GetTouchSlopInDips();
config.enable_adaptive_handle_orientation =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableAdaptiveSelectionHandleOrientation);
config.enable_longpress_drag_selection =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableLongpressDragSelection);
config.hide_active_handle =
base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_P;
return std::make_unique<ui::TouchSelectionController>(client, config);
}
gfx::RectF GetSelectionRect(const ui::TouchSelectionController& controller) {
// When the touch handles are on the same line, the rect may become simply a
// one-dimensional rect, and still need to union the handle rect to avoid the
// context menu covering the touch handle. See detailed comments in
// TouchSelectionController::GetRectBetweenBounds(). Ensure that the |rect| is
// not empty by adding a pixel width or height to avoid the wrong menu
// position.
gfx::RectF rect = controller.GetVisibleRectBetweenBounds();
if (rect.IsEmpty()) {
gfx::SizeF size = rect.size();
size.SetToMax(gfx::SizeF(1.0f, 1.0f));
rect.set_size(size);
}
rect.Union(controller.GetStartHandleRect());
rect.Union(controller.GetEndHandleRect());
return rect;
}
void RecordToolTypeForActionDown(const ui::MotionEventAndroid& event) {
ui::MotionEventAndroid::Action action = event.GetAction();
if (action == ui::MotionEventAndroid::Action::DOWN ||
action == ui::MotionEventAndroid::Action::POINTER_DOWN ||
action == ui::MotionEventAndroid::Action::BUTTON_PRESS) {
UMA_HISTOGRAM_ENUMERATION(
"Event.AndroidActionDown.ToolType",
static_cast<int>(event.GetToolType(0)),
static_cast<int>(ui::MotionEventAndroid::ToolType::LAST) + 1);
}
}
void WakeUpGpu(GpuProcessHost* host) {
if (host && host->gpu_host()->wake_up_gpu_before_drawing()) {
host->gpu_service()->WakeUpGpu();
}
}
std::string CompressAndSaveBitmap(const std::string& dir,
const SkBitmap& bitmap) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
std::vector<unsigned char> data;
if (!gfx::JPEGCodec::Encode(bitmap, 85, &data)) {
LOG(ERROR) << "Failed to encode bitmap to JPEG";
return std::string();
}
base::FilePath screenshot_dir(dir);
if (!base::DirectoryExists(screenshot_dir)) {
if (!base::CreateDirectory(screenshot_dir)) {
LOG(ERROR) << "Failed to create screenshot directory";
return std::string();
}
}
base::FilePath screenshot_path;
base::ScopedFILE out_file(base::CreateAndOpenTemporaryStreamInDir(
screenshot_dir, &screenshot_path));
if (!out_file) {
LOG(ERROR) << "Failed to create temporary screenshot file";
return std::string();
}
unsigned int bytes_written =
fwrite(reinterpret_cast<const char*>(data.data()), 1, data.size(),
out_file.get());
out_file.reset(); // Explicitly close before a possible Delete below.
// If there were errors, don't leave a partial file around.
if (bytes_written != data.size()) {
base::DeleteFile(screenshot_path);
LOG(ERROR) << "Error writing screenshot file to disk";
return std::string();
}
return screenshot_path.value();
}
} // namespace
RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
gfx::NativeView parent_native_view)
: RenderWidgetHostViewBase(widget_host),
is_showing_(!widget_host->is_hidden()),
is_window_visible_(true),
is_window_activity_started_(true),
is_in_vr_(false),
ime_adapter_android_(nullptr),
selection_popup_controller_(nullptr),
text_suggestion_host_(nullptr),
gesture_listener_manager_(nullptr),
view_(ui::ViewAndroid::LayoutType::MATCH_PARENT),
gesture_provider_(
ui::GetGestureProviderConfig(
ui::GestureProviderConfigType::CURRENT_PLATFORM,
content::GetUIThreadTaskRunner({BrowserTaskType::kUserInput})),
this),
stylus_text_selector_(this),
using_browser_compositor_(CompositorImpl::IsInitialized()),
synchronous_compositor_client_(nullptr),
observing_root_window_(false),
prev_top_shown_pix_(0.f),
prev_top_controls_pix_(0.f),
prev_top_controls_translate_(0.f),
prev_top_controls_min_height_offset_pix_(0.f),
prev_bottom_shown_pix_(0.f),
prev_bottom_controls_translate_(0.f),
prev_bottom_controls_min_height_offset_pix_(0.f),
page_scale_(1.f),
min_page_scale_(1.f),
max_page_scale_(1.f),
mouse_wheel_phase_handler_(this),
is_surface_sync_throttling_(features::IsSurfaceSyncThrottling()) {
// Set the layer which will hold the content layer for this view. The content
// layer is managed by the DelegatedFrameHost.
view_.SetLayer(cc::Layer::Create());
view_.set_event_handler(this);
// If we're showing at creation time, we won't get a visibility change, so
// generate our initial LocalSurfaceId here.
if (is_showing_)
local_surface_id_allocator_.GenerateId();
delegated_frame_host_client_ =
std::make_unique<DelegatedFrameHostClientAndroid>(this);
delegated_frame_host_ = std::make_unique<ui::DelegatedFrameHostAndroid>(
&view_, GetHostFrameSinkManager(), delegated_frame_host_client_.get(),
host()->GetFrameSinkId());
if (is_showing_) {
delegated_frame_host_->WasShown(
local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
GetCompositorViewportPixelSize(), host()->delegate()->IsFullscreen());
}
// Let the page-level input event router know about our frame sink ID
// for surface-based hit testing.
if (ShouldRouteEvents()) {
host()->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
host()->SetView(this);
touch_selection_controller_client_manager_ =
std::make_unique<TouchSelectionControllerClientManagerAndroid>(
this, GetHostFrameSinkManager());
UpdateNativeViewTree(parent_native_view);
// This RWHVA may have been created speculatively. We should give any
// existing RWHVAs priority for receiving input events, otherwise a
// speculative RWHVA could be sent input events intended for the currently
// showing RWHVA.
if (parent_native_view)
parent_native_view->MoveToBack(&view_);
CreateOverscrollControllerIfPossible();
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
host()->render_frame_metadata_provider()->AddObserver(this);
}
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
UpdateNativeViewTree(nullptr);
view_.set_event_handler(nullptr);
DCHECK(!ime_adapter_android_);
DCHECK(!delegated_frame_host_);
if (obj_) {
Java_RenderWidgetHostViewImpl_clearNativePtr(
base::android::AttachCurrentThread(), obj_);
obj_.Reset();
}
}
void RenderWidgetHostViewAndroid::AddDestructionObserver(
DestructionObserver* observer) {
destruction_observers_.AddObserver(observer);
}
void RenderWidgetHostViewAndroid::RemoveDestructionObserver(
DestructionObserver* observer) {
destruction_observers_.RemoveObserver(observer);
}
base::CallbackListSubscription
RenderWidgetHostViewAndroid::SubscribeToSurfaceIdChanges(
const SurfaceIdChangedCallback& callback) {
return surface_id_changed_callbacks_.Add(callback);
}
void RenderWidgetHostViewAndroid::OnSurfaceIdChanged() {
surface_id_changed_callbacks_.Notify(GetCurrentSurfaceId());
}
void RenderWidgetHostViewAndroid::InitAsChild(gfx::NativeView parent_view) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::InitAsPopup(
RenderWidgetHostView* parent_host_view,
const gfx::Rect& pos,
const gfx::Rect& anchor_rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewAndroid::NotifyVirtualKeyboardOverlayRect(
const gfx::Rect& keyboard_rect) {
RenderFrameHostImpl* frame_host = host()->frame_tree()->GetMainFrame();
if (!frame_host || !frame_host->GetPage().virtual_keyboard_overlays_content())
return;
gfx::Rect keyboard_rect_with_scale;
if (!keyboard_rect.IsEmpty()) {
float scale = IsUseZoomForDSFEnabled() ? 1 / view_.GetDipScale() : 1.f;
keyboard_rect_with_scale = ScaleToEnclosedRect(keyboard_rect, scale);
// Intersect the keyboard rect with the `this` bounds which will be sent
// to the renderer.
keyboard_rect_with_scale.Intersect(GetViewBounds());
}
frame_host->NotifyVirtualKeyboardOverlayRect(keyboard_rect_with_scale);
}
bool RenderWidgetHostViewAndroid::ShouldVirtualKeyboardOverlayContent() {
RenderFrameHostImpl* frame_host = host()->frame_tree()->GetMainFrame();
return frame_host &&
frame_host->GetPage().virtual_keyboard_overlays_content();
}
bool RenderWidgetHostViewAndroid::SynchronizeVisualProperties(
const cc::DeadlinePolicy& deadline_policy,
const absl::optional<viz::LocalSurfaceId>& child_local_surface_id) {
if (!CanSynchronizeVisualProperties())
return false;
if (child_local_surface_id)
local_surface_id_allocator_.UpdateFromChild(*child_local_surface_id);
else
local_surface_id_allocator_.GenerateId();
// If we still have an invalid viz::LocalSurfaceId, then we are hidden and
// evicted. This will have been triggered by a child acknowledging a previous
// synchronization message via DidUpdateVisualProperties. The child has not
// prompted any further property changes, so we do not need to continue
// syncrhonization. Nor do we want to embed an invalid surface.
if (!local_surface_id_allocator_.HasValidLocalSurfaceId())
return false;
if (delegated_frame_host_) {
delegated_frame_host_->EmbedSurface(
local_surface_id_allocator_.GetCurrentLocalSurfaceId(),
GetCompositorViewportPixelSize(), deadline_policy,
host()->delegate()->IsFullscreen());
}
return host()->SynchronizeVisualProperties();
}
void RenderWidgetHostViewAndroid::SetSize(const gfx::Size& size) {
// Ignore the given size as only the Java code has the power to
// resize the view on Android.
default_bounds_ = gfx::Rect(default_bounds_.origin(), size);
}
void RenderWidgetHostViewAndroid::SetBounds(const gfx::Rect& rect) {
default_bounds_ = rect;
}
bool RenderWidgetHostViewAndroid::HasValidFrame() const {
if (!delegated_frame_host_)
return false;
if (!view_.parent())
return false;
if (current_surface_size_.IsEmpty())
return false;
return delegated_frame_host_->HasSavedFrame();
}
gfx::NativeView RenderWidgetHostViewAndroid::GetNativeView() {
return &view_;
}
gfx::NativeViewAccessible
RenderWidgetHostViewAndroid::GetNativeViewAccessible() {
NOTIMPLEMENTED();
return NULL;
}
void RenderWidgetHostViewAndroid::GotFocus() {
host()->GotFocus();
OnFocusInternal();
}
void RenderWidgetHostViewAndroid::LostFocus() {
host()->LostFocus();
LostFocusInternal();
}
void RenderWidgetHostViewAndroid::OnRenderFrameMetadataChangedBeforeActivation(
const cc::RenderFrameMetadata& metadata) {
bool is_transparent = metadata.has_transparent_background;
SkColor root_background_color = metadata.root_background_color;
if (!using_browser_compositor_) {
// DevTools ScreenCast support for Android WebView.
last_render_frame_metadata_ = metadata;
// Android WebView ignores transparent background.
is_transparent = false;
}
gesture_provider_.SetDoubleTapSupportForPageEnabled(
!metadata.is_mobile_optimized);
float dip_scale = view_.GetDipScale();
gfx::SizeF root_layer_size_dip = metadata.root_layer_size;
gfx::SizeF scrollable_viewport_size_dip = metadata.scrollable_viewport_size;
gfx::PointF root_scroll_offset_dip =
metadata.root_scroll_offset.value_or(gfx::PointF());
if (IsUseZoomForDSFEnabled()) {
float pix_to_dip = 1 / dip_scale;
root_layer_size_dip.Scale(pix_to_dip);
scrollable_viewport_size_dip.Scale(pix_to_dip);
root_scroll_offset_dip.Scale(pix_to_dip);
}
float to_pix = IsUseZoomForDSFEnabled() ? 1.f : dip_scale;
// Note that the height of browser control is not affected by page scale
// factor. Thus, |top_content_offset| in CSS pixels is also in DIPs.
float top_content_offset =
metadata.top_controls_height * metadata.top_controls_shown_ratio;
float top_shown_pix = top_content_offset * to_pix;
if (ime_adapter_android_) {
ime_adapter_android_->UpdateFrameInfo(metadata.selection.start, dip_scale,
top_shown_pix);
}
if (!gesture_listener_manager_)
return;
UpdateTouchSelectionController(metadata.selection, metadata.page_scale_factor,
metadata.top_controls_height,
metadata.top_controls_shown_ratio,
scrollable_viewport_size_dip);
// ViewAndroid::content_offset() must be in dip.
float top_content_offset_dip = IsUseZoomForDSFEnabled()
? top_content_offset / dip_scale
: top_content_offset;
view_.UpdateFrameInfo({scrollable_viewport_size_dip, top_content_offset_dip});
bool controls_changed = UpdateControls(
view_.GetDipScale(), metadata.top_controls_height,
metadata.top_controls_shown_ratio,
metadata.top_controls_min_height_offset, metadata.bottom_controls_height,
metadata.bottom_controls_shown_ratio,
metadata.bottom_controls_min_height_offset);
SetContentBackgroundColor(is_transparent ? SK_ColorTRANSPARENT
: root_background_color);
if (overscroll_controller_) {
overscroll_controller_->OnFrameMetadataUpdated(
metadata.page_scale_factor, metadata.device_scale_factor,
metadata.scrollable_viewport_size, metadata.root_layer_size,
metadata.root_scroll_offset.value_or(gfx::PointF()),
metadata.root_overflow_y_hidden);
}
// All offsets and sizes except |top_shown_pix| are in dip.
gesture_listener_manager_->UpdateScrollInfo(
root_scroll_offset_dip, metadata.page_scale_factor,
metadata.min_page_scale_factor, metadata.max_page_scale_factor,
root_layer_size_dip, scrollable_viewport_size_dip, top_content_offset_dip,
top_shown_pix, controls_changed);
// This needs to be called after GestureListenerManager::UpdateScrollInfo, as
// it depends on frame info being updated during the UpdateScrollInfo call.
auto* wcax = GetWebContentsAccessibilityAndroid();
if (wcax)
wcax->UpdateFrameInfo(metadata.page_scale_factor);
page_scale_ = metadata.page_scale_factor;
min_page_scale_ = metadata.min_page_scale_factor;
max_page_scale_ = metadata.max_page_scale_factor;
current_surface_size_ = metadata.viewport_size_in_pixels;
// With SurfaceSync we no longer call evict frame on every metadata change. We
// must still call UpdateWebViewBackgroundColorIfNecessary to maintain the
// associated background color changes.
UpdateWebViewBackgroundColorIfNecessary();
if (metadata.new_vertical_scroll_direction !=
viz::VerticalScrollDirection::kNull) {
bool can_scroll = metadata.root_layer_size.height() -
metadata.viewport_size_in_pixels.height() >
std::numeric_limits<float>::epsilon();
float scroll_ratio = 0.f;
if (can_scroll && metadata.root_scroll_offset) {
scroll_ratio = metadata.root_scroll_offset.value().y() /
(metadata.root_layer_size.height() -
metadata.viewport_size_in_pixels.height());
}
view_.OnVerticalScrollDirectionChanged(
metadata.new_vertical_scroll_direction ==
viz::VerticalScrollDirection::kUp,
scroll_ratio);
}
}
base::android::ScopedJavaLocalRef<jobject>
RenderWidgetHostViewAndroid::GetJavaObject() {
if (!obj_) {
JNIEnv* env = base::android::AttachCurrentThread();
obj_.Reset(env, Java_RenderWidgetHostViewImpl_create(
env, reinterpret_cast<intptr_t>(this))
.obj());
}
return base::android::ScopedJavaLocalRef<jobject>(obj_);
}
bool RenderWidgetHostViewAndroid::IsReady(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
return HasValidFrame();
}
void RenderWidgetHostViewAndroid::DismissTextHandles(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
DismissTextHandles();
}
jint RenderWidgetHostViewAndroid::GetBackgroundColor(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
absl::optional<SkColor> color =
RenderWidgetHostViewAndroid::GetCachedBackgroundColor();
if (!color)
return SK_ColorTRANSPARENT;
return *color;
}
void RenderWidgetHostViewAndroid::ShowContextMenuAtTouchHandle(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint x,
jint y) {
if (GetTouchSelectionControllerClientManager()) {
GetTouchSelectionControllerClientManager()->ShowContextMenu(
gfx::Point(x, y));
}
}
void RenderWidgetHostViewAndroid::OnViewportInsetBottomChanged(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) {
SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(),
absl::nullopt);
}
void RenderWidgetHostViewAndroid::WriteContentBitmapToDiskAsync(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jint width,
jint height,
const base::android::JavaParamRef<jstring>& jpath,
const base::android::JavaParamRef<jobject>& jcallback) {
base::OnceCallback<void(const SkBitmap&)> result_callback = base::BindOnce(
&RenderWidgetHostViewAndroid::OnFinishGetContentBitmap,
weak_ptr_factory_.GetWeakPtr(),
base::android::ScopedJavaGlobalRef<jobject>(env, obj),
base::android::ScopedJavaGlobalRef<jobject>(env, jcallback),
base::android::ConvertJavaStringToUTF8(env, jpath));
CopyFromSurface(gfx::Rect(), gfx::Size(width, height),
std::move(result_callback));
}
void RenderWidgetHostViewAndroid::OnRenderFrameMetadataChangedAfterActivation(
base::TimeTicks activation_time) {
const cc::RenderFrameMetadata& metadata =
host()->render_frame_metadata_provider()->LastRenderFrameMetadata();
auto activated_local_surface_id =
metadata.local_surface_id.value_or(viz::LocalSurfaceId());
if (activated_local_surface_id.is_valid()) {
// We have received content, ensure that any subsequent navigation allocates
// a new surface.
pre_navigation_content_ = true;
while (!rotation_metrics_.empty()) {
auto rotation_target = rotation_metrics_.front();
// Activation from a previous surface before the new rotation has set a
// viz::LocalSurfaceId.
if (!rotation_target.second.is_valid())
break;
// In most cases the viz::LocalSurfaceId will be the same.
//
// However, if there are two cases where this does not occur.
//
// Firstly the Renderer may increment the |child_sequence_number| if it
// needs to also alter visual properties. If so the newer surface would
// denote the first visual update of the rotation. So its activation time
// is correct.
//
// Otherwise there may be two rotations in close proximity, and one takes
// too long to present. When this occurs the initial rotation does not
// display. This newer surface will be the first displayed. Use its
// activation time for the rotation, as the user would have been blocked
// on visual updates for that long.
//
// We want to know of these long tail rotation times.
if (activated_local_surface_id.IsSameOrNewerThan(
rotation_target.second)) {
// The duration for a rotation encompasses two separate spans of time,
// depending on whether or not we were `is_showing_` at the start of
// rotation.
//
// For a visible rotation `rotation_target.first` denotes the start of
// the rotation event handled in BeginRotationBatching.
//
// For a hidden rotation we ignore this initial event, as the Renderer
// can continue to be hidden for a long time. In these cases the
// `rotation_target.first` denotes when ShowInternal is called.
//
// From these, until `activation_time`, we can determine the length of
// time that the Renderer is visible, until the post rotation surface is
// first displayed.
auto duration = activation_time - rotation_target.first;
TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP1(
"viz", "RenderWidgetHostViewAndroid::RotationEmbed",
TRACE_ID_LOCAL(rotation_target.second.hash()), activation_time,
"duration(ms)", duration.InMillisecondsF());
// Report the total time from the first notification of rotation
// beginning, until the Renderer has submitted and activated a
// corresponding surface.
UMA_HISTOGRAM_TIMES("Android.Rotation.BeginToRendererFrameActivation",
duration);
rotation_metrics_.pop_front();
} else {
// The embedded surface may have updated the
// LocalSurfaceId::child_sequence_number while we were updating the
// parent_sequence_number for `rotation_target`. For example starting
// from (6, 2) the child advances to (6, 3), and the parent advances to
// (7, 2). viz::LocalSurfaceId::IsNewerThan will return false in these
// mixed sequence advancements.
//
// Subsequently we would merge the two into (7, 3) which will become the
// actually submitted surface to Viz.
//
// As such we have now received a surface that is not for our target, so
// we break here and await the next frame from the child.
break;
}
}
if (rotation_metrics_.empty())
in_rotation_ = false;
}
if (ime_adapter_android_) {
// We need to first wait for Blink's viewport size to change such that we
// can correctly scroll to the currently focused input.
// On Clank, only visible viewport size changes and device viewport size or
// viewport_size_in_pixels do not change according to the window/view size
/// change. Only scrollable viewport size changes both for Chrome and
// WebView.
ime_adapter_android_->OnRenderFrameMetadataChangedAfterActivation(
metadata.scrollable_viewport_size);
}
}
void RenderWidgetHostViewAndroid::OnRootScrollOffsetChanged(
const gfx::PointF& root_scroll_offset) {
if (!gesture_listener_manager_)
return;
gfx::PointF root_scroll_offset_dip = root_scroll_offset;
if (IsUseZoomForDSFEnabled())
root_scroll_offset_dip.Scale(1 / view_.GetDipScale());
gesture_listener_manager_->OnRootScrollOffsetChanged(root_scroll_offset_dip);
}
void RenderWidgetHostViewAndroid::Focus() {
if (view_.HasFocus())
GotFocus();
else
view_.RequestFocus();
}
void RenderWidgetHostViewAndroid::OnFocusInternal() {
if (overscroll_controller_)
overscroll_controller_->Enable();
}
void RenderWidgetHostViewAndroid::LostFocusInternal() {
if (overscroll_controller_)
overscroll_controller_->Disable();
}
bool RenderWidgetHostViewAndroid::HasFocus() {
return view_.HasFocus();
}
bool RenderWidgetHostViewAndroid::IsSurfaceAvailableForCopy() {
return !using_browser_compositor_ ||
(delegated_frame_host_ &&
delegated_frame_host_->CanCopyFromCompositingSurface());
}
void RenderWidgetHostViewAndroid::ShowWithVisibility(
PageVisibilityState /*page_visibility*/) {
if (is_showing_)
return;
is_showing_ = true;
ShowInternal();
}
void RenderWidgetHostViewAndroid::Hide() {
if (!is_showing_)
return;
is_showing_ = false;
HideInternal();
}
bool RenderWidgetHostViewAndroid::IsShowing() {
// |view_.parent()| being NULL means that it is not attached
// to the View system yet, so we treat this RWHVA as hidden.
return is_showing_ && view_.parent();
}
void RenderWidgetHostViewAndroid::SelectAroundCaretAck(
blink::mojom::SelectAroundCaretResultPtr result) {
if (!selection_popup_controller_)
return;
selection_popup_controller_->OnSelectAroundCaretAck(std::move(result));
}
gfx::Rect RenderWidgetHostViewAndroid::GetViewBounds() {
if (!view_.parent())
return default_bounds_;
gfx::Size size(view_.GetSize());
return gfx::Rect(size);
}
gfx::Size RenderWidgetHostViewAndroid::GetVisibleViewportSize() {
int pinned_bottom_adjust_dps =
std::max(0, (int)(view_.GetViewportInsetBottom() / view_.GetDipScale()));
gfx::Rect requested_rect(GetRequestedRendererSize());
requested_rect.Inset(gfx::Insets(0, 0, pinned_bottom_adjust_dps, 0));
return requested_rect.size();
}
void RenderWidgetHostViewAndroid::SetInsets(const gfx::Insets& insets) {
NOTREACHED();
}
gfx::Size RenderWidgetHostViewAndroid::GetCompositorViewportPixelSize() {
if (!view_.parent()) {
if (default_bounds_.IsEmpty()) return gfx::Size();
float scale_factor = view_.GetDipScale();
return gfx::Size(default_bounds_.right() * scale_factor,
default_bounds_.bottom() * scale_factor);
}
return view_.GetPhysicalBackingSize();
}
int RenderWidgetHostViewAndroid::GetMouseWheelMinimumGranularity() const {
auto* window = view_.GetWindowAndroid();
if (!window)
return 0;
// On Android, mouse wheel MotionEvents specify the number of ticks and how
// many pixels each tick scrolls. This multiplier is specified by device
// metrics (See WindowAndroid.getMouseWheelScrollFactor) so the minimum
// granularity will be the size of this tick multiplier.
return window->mouse_wheel_scroll_factor() / view_.GetDipScale();
}
void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& webcursor) {
view_.OnCursorChanged(webcursor.cursor());
}
void RenderWidgetHostViewAndroid::SetIsLoading(bool is_loading) {
// Do nothing. The UI notification is handled through ContentViewClient which
// is TabContentsDelegate.
}
// -----------------------------------------------------------------------------
// TextInputManager::Observer implementations.
void RenderWidgetHostViewAndroid::OnUpdateTextInputStateCalled(
TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view,
bool did_change_state) {
if (!ime_adapter_android_)
return;
DCHECK_EQ(text_input_manager_, text_input_manager);
if (GetTextInputManager()->GetActiveWidget()) {
ime_adapter_android_->UpdateState(
*GetTextInputManager()->GetTextInputState());
} else {
// If there are no active widgets, the TextInputState.type should be
// reported as none.
ime_adapter_android_->UpdateState(ui::mojom::TextInputState());
}
}
void RenderWidgetHostViewAndroid::OnImeCompositionRangeChanged(
TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view) {
DCHECK_EQ(text_input_manager_, text_input_manager);
const TextInputManager::CompositionRangeInfo* info =
text_input_manager_->GetCompositionRangeInfo();
if (!info)
return;
std::vector<gfx::RectF> character_bounds;
for (const gfx::Rect& rect : info->character_bounds)
character_bounds.emplace_back(rect);
if (ime_adapter_android_)
ime_adapter_android_->SetCharacterBounds(character_bounds);
}
void RenderWidgetHostViewAndroid::OnImeCancelComposition(
TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view) {
DCHECK_EQ(text_input_manager_, text_input_manager);
if (ime_adapter_android_)
ime_adapter_android_->CancelComposition();
}
void RenderWidgetHostViewAndroid::OnTextSelectionChanged(
TextInputManager* text_input_manager,
RenderWidgetHostViewBase* updated_view) {
DCHECK_EQ(text_input_manager_, text_input_manager);
if (!selection_popup_controller_)
return;
RenderWidgetHostImpl* focused_widget = GetFocusedWidget();
if (!focused_widget || !focused_widget->GetView())
return;
const TextInputManager::TextSelection& selection =
*text_input_manager_->GetTextSelection(focused_widget->GetView());
selection_popup_controller_->OnSelectionChanged(
base::UTF16ToUTF8(selection.selected_text()));
}
viz::FrameSinkId RenderWidgetHostViewAndroid::GetRootFrameSinkId() {
if (sync_compositor_)
return sync_compositor_->GetFrameSinkId();
if (view_.GetWindowAndroid() && view_.GetWindowAndroid()->GetCompositor())
return view_.GetWindowAndroid()->GetCompositor()->GetFrameSinkId();
return viz::FrameSinkId();
}
viz::SurfaceId RenderWidgetHostViewAndroid::GetCurrentSurfaceId() const {
if (sync_compositor_)
return sync_compositor_->GetSurfaceId();
return delegated_frame_host_ ? delegated_frame_host_->SurfaceId()
: viz::SurfaceId();
}
bool RenderWidgetHostViewAndroid::TransformPointToCoordSpaceForView(
const gfx::PointF& point,
RenderWidgetHostViewBase* target_view,
gfx::PointF* transformed_point) {
if (target_view == this) {
*transformed_point = point;
return true;
}
viz::SurfaceId surface_id = GetCurrentSurfaceId();
if (!surface_id.is_valid())
return false;
// In TransformPointToLocalCoordSpace() there is a Point-to-Pixel conversion,
// but it is not necessary here because the final target view is responsible
// for converting before computing the final transform.
return target_view->TransformPointToLocalCoordSpace(point, surface_id,
transformed_point);
}
void RenderWidgetHostViewAndroid::SetGestureListenerManager(
GestureListenerManager* manager) {
gesture_listener_manager_ = manager;
UpdateReportAllRootScrolls();
}
void RenderWidgetHostViewAndroid::UpdateReportAllRootScrolls() {
if (!host())
return;
host()->render_frame_metadata_provider()->ReportAllRootScrolls(
ShouldReportAllRootScrolls());
}
base::WeakPtr<RenderWidgetHostViewAndroid>
RenderWidgetHostViewAndroid::GetWeakPtrAndroid() {
return weak_ptr_factory_.GetWeakPtr();
}
bool RenderWidgetHostViewAndroid::OnGestureEvent(
const ui::GestureEventAndroid& event) {
std::unique_ptr<blink::WebGestureEvent> web_event;
if (event.scale() < 0.f) {
// Negative scale indicates zoom reset.
float delta = min_page_scale_ / page_scale_;
web_event = ui::CreateWebGestureEventFromGestureEventAndroid(
ui::GestureEventAndroid(event.type(), event.location(),
event.screen_location(), event.time(), delta, 0,
0, 0, 0, /*target_viewport*/ false,
/*synthetic_scroll*/ false,
/*prevent_boosting*/ false));
} else {
web_event = ui::CreateWebGestureEventFromGestureEventAndroid(event);
}
if (!web_event)
return false;
SendGestureEvent(*web_event);
return true;
}
bool RenderWidgetHostViewAndroid::OnTouchEvent(
const ui::MotionEventAndroid& event) {
RecordToolTypeForActionDown(event);
if (event.GetAction() == ui::MotionEventAndroid::Action::DOWN) {
if (ime_adapter_android_)
ime_adapter_android_->UpdateOnTouchDown();
if (gesture_listener_manager_)
gesture_listener_manager_->UpdateOnTouchDown();
}
if (event.for_touch_handle())
return OnTouchHandleEvent(event);
if (!host() || !host()->delegate())
return false;
ComputeEventLatencyOSTouchHistograms(event);
// Receiving any other touch event before the double-tap timeout expires
// cancels opening the spellcheck menu.
if (text_suggestion_host_)
text_suggestion_host_->StopSuggestionMenuTimer();
// If a browser-based widget consumes the touch event, it's critical that
// touch event interception be disabled. This avoids issues with
// double-handling for embedder-detected gestures like side swipe.
if (OnTouchHandleEvent(event)) {
RequestDisallowInterceptTouchEvent();
return true;
}
if (stylus_text_selector_.OnTouchEvent(event)) {
RequestDisallowInterceptTouchEvent();
return true;