-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
CompositorViewHolder.java
1840 lines (1596 loc) · 73 KB
/
CompositorViewHolder.java
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 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityEventCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.customview.widget.ExploreByTouchHelper;
import org.chromium.base.Callback;
import org.chromium.base.ObserverList;
import org.chromium.base.SysUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.compat.ApiHelperForN;
import org.chromium.base.compat.ApiHelperForO;
import org.chromium.base.supplier.ObservableSupplier;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider;
import org.chromium.chrome.browser.browser_controls.BrowserControlsUtils;
import org.chromium.chrome.browser.compositor.layouts.LayoutManagerHost;
import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.content.ContentOffsetProvider;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.fullscreen.BrowserControlsManager;
import org.chromium.chrome.browser.fullscreen.FullscreenManager;
import org.chromium.chrome.browser.layouts.components.VirtualView;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabCreationState;
import org.chromium.chrome.browser.tab.TabObscuringHandler;
import org.chromium.chrome.browser.tab.TabObserver;
import org.chromium.chrome.browser.tab.TabUtils.LoadIfNeededCaller;
import org.chromium.chrome.browser.tabmodel.TabCreatorManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorObserver;
import org.chromium.chrome.browser.theme.TopUiThemeColorProvider;
import org.chromium.chrome.browser.toolbar.ControlContainer;
import org.chromium.chrome.browser.util.ChromeAccessibilityUtil;
import org.chromium.chrome.features.start_surface.StartSurfaceUserData;
import org.chromium.components.browser_ui.widget.InsetObserverView;
import org.chromium.components.browser_ui.widget.TouchEventObserver;
import org.chromium.components.content_capture.OnscreenContentProvider;
import org.chromium.components.embedder_support.view.ContentView;
import org.chromium.content_public.browser.NavigationHandle;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.KeyboardVisibilityDelegate;
import org.chromium.ui.UiUtils;
import org.chromium.ui.base.ApplicationViewportInsetSupplier;
import org.chromium.ui.base.EventForwarder;
import org.chromium.ui.base.EventOffsetHandler;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.mojom.VirtualKeyboardMode;
import org.chromium.ui.resources.ResourceManager;
import org.chromium.ui.resources.dynamics.DynamicResourceLoader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class holds a {@link CompositorView}. This level of indirection is needed to benefit from
* the {@link android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)} capability on
* available on {@link android.view.ViewGroup}s.
* This class also holds the {@link LayoutManagerImpl} responsible to describe the items to be
* drawn by the UI compositor on the native side.
*/
public class CompositorViewHolder extends FrameLayout
implements ContentOffsetProvider, LayoutManagerHost, LayoutRenderHost, Invalidator.Host,
BrowserControlsStateProvider.Observer, InsetObserverView.WindowInsetObserver,
ChromeAccessibilityUtil.Observer, TabObscuringHandler.Observer,
ViewGroup.OnHierarchyChangeListener {
private static final long SYSTEM_UI_VIEWPORT_UPDATE_DELAY_MS = 500;
private Runnable mSetBackgroundRunnable;
/**
* Initializer interface used to decouple initialization from the class that owns
* the CompositorViewHolder.
*/
public interface Initializer {
/**
* Initializes the {@link CompositorViewHolder} with the relevant content it needs to
* properly show content on the screen.
* @param layoutManager A {@link LayoutManagerImpl} instance. This class is
* responsible for driving all high level screen content
* and determines which {@link Layout} is shown when.
* @param urlBar The {@link View} representing the URL bar (must be
* focusable) or {@code null} if none exists.
* @param contentContainer A {@link ViewGroup} that can have content attached by
* {@link Layout}s.
* @param controlContainer A {@link ControlContainer} instance to draw.
*/
void initializeCompositorContent(LayoutManagerImpl layoutManager, View urlBar,
ViewGroup contentContainer, ControlContainer controlContainer);
}
private final ObserverList<TouchEventObserver> mTouchEventObservers = new ObserverList<>();
private EventOffsetHandler mEventOffsetHandler;
private boolean mIsKeyboardShowing;
private boolean mNativeInitialized;
private final Invalidator mInvalidator = new Invalidator();
private LayoutManagerImpl mLayoutManager;
private CompositorView mCompositorView;
private boolean mContentOverlayVisiblity = true;
private boolean mCanBeFocusable;
private int mPendingFrameCount;
private final ArrayList<Runnable> mPendingInvalidations = new ArrayList<>();
private boolean mSkipInvalidation;
/**
* A task to be performed after a resize event.
*/
private Runnable mPostHideKeyboardTask;
private TabModelSelector mTabModelSelector;
private @Nullable BrowserControlsManager mBrowserControlsManager;
private View mAccessibilityView;
private CompositorAccessibilityProvider mNodeProvider;
/** The toolbar control container. **/
private @Nullable ControlContainer mControlContainer;
private InsetObserverView mInsetObserverView;
private ObservableSupplier<Integer> mAutofillUiBottomInsetSupplier;
private boolean mShowingFullscreen;
private Runnable mSystemUiFullscreenResizeRunnable;
/** The currently visible Tab. */
@VisibleForTesting
Tab mTabVisible;
/** The currently attached View. */
private View mView;
/**
* Current ContentView. Updates when active tab is switched or WebContents is swapped
* in the current Tab.
*/
private ContentView mContentView;
private TabObserver mTabObserver;
// Cache objects that should not be created frequently.
private final Rect mCacheRect = new Rect();
private final Point mCachePoint = new Point();
private boolean mHasDrawnOnce;
private boolean mIsInVr;
private boolean mControlsResizeView;
private boolean mInGesture;
private boolean mContentViewScrolling;
private ApplicationViewportInsetSupplier mApplicationBottomInsetSupplier;
private final Callback<Integer> mBottomInsetObserver = (inset) -> bottomInsetChanged();
/**
* Tracks whether geometrychange event is fired for the active tab when the keyboard
* is shown/hidden. When active tab changes, this flag is reset so we can fire
* geometrychange event for the new tab when the keyboard shows.
*/
private boolean mHasKeyboardGeometryChangeFired;
@VirtualKeyboardMode.EnumType
private int mVirtualKeyboardMode =
ChromeFeatureList.sOSKResizesVisualViewportByDefault.isEnabled()
? VirtualKeyboardMode.RESIZES_VISUAL
: VirtualKeyboardMode.RESIZES_CONTENT;
private OnscreenContentProvider mOnscreenContentProvider;
private final Set<Runnable> mOnCompositorLayoutCallbacks = new HashSet<>();
private final Set<Runnable> mDidSwapFrameCallbacks = new HashSet<>();
private final Set<Runnable> mDidSwapBuffersCallbacks = new HashSet<>();
/**
* Last MotionEvent dispatched to this object for a currently active gesture. If there is no
* active gesture, this is null.
*/
private @Nullable MotionEvent mLastActiveTouchEvent;
private TopUiThemeColorProvider mTopUiThemeColorProvider;
/**
* This view is created on demand to display debugging information.
*/
private static class DebugOverlay extends View {
private final List<Pair<Rect, Integer>> mRectangles = new ArrayList<>();
private final Paint mPaint = new Paint();
private boolean mFirstPush = true;
/**
* @param context The current Android's context.
*/
public DebugOverlay(Context context) {
super(context);
}
/**
* Pushes a rectangle to be drawn on the screen on top of everything.
*
* @param rect The rectangle to be drawn on screen
* @param color The color of the rectangle
*/
public void pushRect(Rect rect, int color) {
if (mFirstPush) {
mRectangles.clear();
mFirstPush = false;
}
mRectangles.add(new Pair<>(rect, color));
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < mRectangles.size(); i++) {
mPaint.setColor(mRectangles.get(i).second);
canvas.drawRect(mRectangles.get(i).first, mPaint);
}
mFirstPush = true;
}
}
private DebugOverlay mDebugOverlay;
private View mUrlBar;
private ApplicationViewportInsetSupplier mApplicationViewportInsetSupplier;
/**
* Creates a {@link CompositorView}.
* @param c The Context to create this {@link CompositorView} in.
*/
public CompositorViewHolder(Context c) {
super(c);
internalInit();
}
@Override
public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return null;
View activeView = getContentView();
if (activeView == null || !ViewCompat.isAttachedToWindow(activeView)) return null;
return ApiHelperForN.onResolvePointerIcon(activeView, event, pointerIndex);
}
/**
* Creates a {@link CompositorView}.
* @param c The Context to create this {@link CompositorView} in.
* @param attrs The AttributeSet used to create this {@link CompositorView}.
*/
public CompositorViewHolder(Context c, AttributeSet attrs) {
super(c, attrs);
internalInit();
}
private void internalInit() {
mEventOffsetHandler =
new EventOffsetHandler(new EventOffsetHandler.EventOffsetHandlerDelegate() {
// Cache objects that should not be created frequently.
private final RectF mCacheViewport = new RectF();
@Override
public float getTop() {
if (mLayoutManager != null) mLayoutManager.getViewportPixel(mCacheViewport);
return mCacheViewport.top;
}
@Override
public void setCurrentTouchEventOffsets(float top) {
if (mTabVisible == null) return;
WebContents webContents = mTabVisible.getWebContents();
if (webContents == null) return;
EventForwarder forwarder = webContents.getEventForwarder();
forwarder.setCurrentTouchEventOffsets(0, top);
}
});
mTabObserver = new EmptyTabObserver() {
@Override
public void onContentChanged(Tab tab) {
CompositorViewHolder.this.onContentChanged();
}
@Override
public void onContentViewScrollingStateChanged(boolean scrolling) {
mContentViewScrolling = scrolling;
if (!scrolling) updateContentViewChildrenDimension();
}
@Override
public void onWebContentsSwapped(Tab tab, boolean didStartLoad, boolean didFinishLoad) {
/**
* After swapping web contents, any gesture active in the old ContentView is
* cancelled. We still want to continue a previously running gesture in the new
* ContentView, so we synthetically dispatch a new ACTION_DOWN MotionEvent with the
* coordinates of where we estimate the pointer currently is (the coordinates of
* the last ACTION_MOVE MotionEvent received before the swap).
*
* We wait for layout to happen as the newly created ContentView currently has a
* width and height of zero, which would result in the event not being dispatched.
*/
mView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
v.removeOnLayoutChangeListener(this);
if (mLastActiveTouchEvent == null) return;
MotionEvent touchEvent = MotionEvent.obtain(mLastActiveTouchEvent);
touchEvent.setAction(MotionEvent.ACTION_DOWN);
CompositorViewHolder.this.dispatchTouchEvent(touchEvent);
for (int i = 1; i < mLastActiveTouchEvent.getPointerCount(); i++) {
MotionEvent pointerDownEvent =
MotionEvent.obtain(mLastActiveTouchEvent);
pointerDownEvent.setAction(MotionEvent.ACTION_POINTER_DOWN
| (i << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
CompositorViewHolder.this.dispatchTouchEvent(pointerDownEvent);
}
}
});
}
@Override
public void onVirtualKeyboardModeChanged(
Tab tab, @VirtualKeyboardMode.EnumType int mode) {
updateVirtualKeyboardMode(mode);
}
@Override
public void onDidFinishNavigationInPrimaryMainFrame(
Tab tab, NavigationHandle navigation) {
if (!navigation.isSameDocument() && navigation.hasCommitted()) {
assert getWebContents() == tab.getWebContents();
assert getWebContents() != null;
updateVirtualKeyboardMode(getWebContents().getVirtualKeyboardMode());
}
}
@Override
public void onDidFinishNavigationNoop(Tab tab, NavigationHandle navigation) {
if (!navigation.isInPrimaryMainFrame()) return;
}
};
addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight,
oldBottom) -> {
Tab tab = getCurrentTab();
// Set the size of NTP if we're in the attached state as it may have not been sized
// properly when initializing tab. See the comment in #initializeTab() for why.
if (tab != null && tab.isNativePage() && isAttachedToWindow(tab.getView())) {
Point viewportSize = getViewportSize();
setSize(tab.getWebContents(), tab.getView(), viewportSize.x, viewportSize.y);
}
onViewportChanged();
// If there's an event that needs to occur after the keyboard is hidden, post
// it as a delayed event. Otherwise this happens in the midst of the
// ContentView's relayout, which causes the ContentView to relayout on top of the
// stack view. The 30ms is arbitrary, hoping to let the view get one repaint
// in so the full page is shown.
if (mPostHideKeyboardTask != null) {
new Handler().postDelayed(mPostHideKeyboardTask, 30);
mPostHideKeyboardTask = null;
}
});
mCompositorView = new CompositorView(getContext(), this);
// mCompositorView should always be the first child.
addView(mCompositorView, 0,
new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
setOnSystemUiVisibilityChangeListener(visibility -> handleSystemUiVisibilityChange());
handleSystemUiVisibilityChange();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ApiHelperForO.setDefaultFocusHighlightEnabled(this, false);
}
}
private Point getViewportSize() {
// When in fullscreen mode, the window does not get resized when showing the onscreen
// keyboard[1]. To work around this, we monitor the visible display frame to mimic the
// resize state to ensure the web contents has the correct width and height.
//
// This path should not be used in the non-fullscreen case as it would negate the
// performance benefits of the app setting SOFT_INPUT_ADJUST_PAN. This would force the
// app into a constant SOFT_INPUT_ADJUST_RESIZE mode, which causes more churn on the page
// layout than required in cases that you're editing in Chrome UI outside of the web
// contents.
//
// [1] - https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_FULLSCREEN
if (mShowingFullscreen
&& (!ChromeFeatureList.sOSKResizesVisualViewportByDefault.isEnabled())
&& KeyboardVisibilityDelegate.getInstance().isKeyboardShowing(getContext(), this)) {
getWindowVisibleDisplayFrame(mCacheRect);
// On certain devices, getWindowVisibleDisplayFrame is larger than the screen size, so
// this ensures we never draw beyond the underlying dimensions of the view.
// https://crbug.com/854109
mCachePoint.set(Math.min(mCacheRect.width(), getWidth()),
Math.min(mCacheRect.height(), getHeight()));
} else {
mCachePoint.set(getWidth(), getHeight());
}
return mCachePoint;
}
private void handleSystemUiVisibilityChange() {
View view = getContentView();
if (view == null || !ViewCompat.isAttachedToWindow(view)) view = this;
int uiVisibility = 0;
while (view != null) {
uiVisibility |= view.getSystemUiVisibility();
if (!(view.getParent() instanceof View)) break;
view = (View) view.getParent();
}
// SYSTEM_UI_FLAG_FULLSCREEN is cleared when showing the soft keyboard in older version of
// Android (prior to P). The immersive mode flags are not cleared, so use those in
// combination to detect this state.
boolean isInFullscreen = (uiVisibility & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0
|| (uiVisibility & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0
|| (uiVisibility & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
boolean layoutFullscreen = (uiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0;
if (mShowingFullscreen == isInFullscreen) return;
mShowingFullscreen = isInFullscreen;
if (mSystemUiFullscreenResizeRunnable == null) {
mSystemUiFullscreenResizeRunnable = this::handleWindowInsetChanged;
} else {
getHandler().removeCallbacks(mSystemUiFullscreenResizeRunnable);
}
// If SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN is set, defer updating the viewport to allow
// Android's animations to complete. The getWindowVisibleDisplayFrame values do not get
// updated until a fair amount after onSystemUiVisibilityChange is broadcast.
//
// SYSTEM_UI_VIEWPORT_UPDATE_DELAY_MS was chosen by increasing the time until the UI did
// not reliably jump from updating the viewport too early.
long delay = layoutFullscreen ? SYSTEM_UI_VIEWPORT_UPDATE_DELAY_MS : 0;
postDelayed(mSystemUiFullscreenResizeRunnable, delay);
}
/**
* @param layoutManager The {@link LayoutManagerImpl} instance that will be driving what
* shows in this {@link CompositorViewHolder}.
*/
public void setLayoutManager(LayoutManagerImpl layoutManager) {
mLayoutManager = layoutManager;
onViewportChanged();
}
/**
* @param view The root view of the hierarchy.
*/
public void setRootView(View view) {
mCompositorView.setRootView(view);
}
/**
* @param controlContainer The ControlContainer.
*/
public void setControlContainer(@Nullable ControlContainer controlContainer) {
DynamicResourceLoader loader = mCompositorView.getResourceManager() != null
? mCompositorView.getResourceManager().getDynamicResourceLoader()
: null;
if (loader != null && mControlContainer != null) {
loader.unregisterResource(R.id.control_container);
}
mControlContainer = controlContainer;
if (loader != null && mControlContainer != null) {
loader.registerResource(
R.id.control_container, mControlContainer.getToolbarResourceAdapter());
}
mSetBackgroundRunnable = () -> {
// Wait until the second frame to turn off the placeholder background for the
// CompositorView and the tab strip, to ensure the compositor frame has been drawn.
final ViewGroup controlContainerVG = (ViewGroup) mControlContainer;
mCompositorView.setBackgroundResource(0);
if (controlContainerVG != null) {
controlContainerVG.setBackgroundResource(0);
}
mSetBackgroundRunnable = null;
};
}
/**
* @param themeColorProvider {@link ThemeColorProvider} for top UI part.
*/
public void setTopUiThemeColorProvider(TopUiThemeColorProvider themeColorProvider) {
mTopUiThemeColorProvider = themeColorProvider;
}
/**
* Set the InsetObserverView that can be monitored for changes to the window insets from Android
* system UI.
*/
public void setInsetObserverView(InsetObserverView view) {
if (mInsetObserverView != null) {
mInsetObserverView.removeObserver(this);
}
mInsetObserverView = view;
if (mInsetObserverView != null) {
mInsetObserverView.addObserver(this);
handleWindowInsetChanged();
}
updateApplicationViewportInsetSuppliers();
}
/**
* A supplier providing an inset that resizes the page in addition or instead of the keyboard.
* This is inset is used by autofill UI as addition to bottom controls.
* @param autofillUiBottomInsetSupplier A {@link ObservableSupplier<Integer>}.
*/
public void setAutofillUiBottomInsetSupplier(
ObservableSupplier<Integer> autofillUiBottomInsetSupplier) {
mAutofillUiBottomInsetSupplier = autofillUiBottomInsetSupplier;
mAutofillUiBottomInsetSupplier.addObserver(mBottomInsetObserver);
updateApplicationViewportInsetSuppliers();
}
/**
* Sets the ApplicationViewportInsetSupplier.
* This object manages inset suppliers that should inset the visual viewport
* of the current page (i.e. allow scrolling but don't affect layout). This
* class manages adding and removing observers from this object as needed.
*/
public void setApplicationViewportInsetSupplier(ApplicationViewportInsetSupplier supplier) {
assert mApplicationViewportInsetSupplier == null;
mApplicationViewportInsetSupplier = supplier;
updateApplicationViewportInsetSuppliers();
}
// Ensures the keyboard-related inset suppliers are either registered or unregistered with the
// ApplicationViewportInsetSupplier. The ApplicationViewportInsetSupplier is responsible for
// insetting the visual viewport so the keyboard insets should only be applied to it if the
// keyboard resizes only the visual viewport (otherwise the visual viewport and web contents
// size are resized together).
private void updateApplicationViewportInsetSuppliers() {
if (mApplicationViewportInsetSupplier == null) return;
if (oskResizesVisualViewport()) {
if (mAutofillUiBottomInsetSupplier != null) {
mApplicationViewportInsetSupplier.addStackingSupplier(
mAutofillUiBottomInsetSupplier);
}
if (mInsetObserverView != null) {
mApplicationViewportInsetSupplier.addStackingSupplier(
mInsetObserverView.getSupplierForBottomInset());
}
} else {
if (mAutofillUiBottomInsetSupplier != null) {
mApplicationViewportInsetSupplier.removeSupplier(mAutofillUiBottomInsetSupplier);
}
if (mInsetObserverView != null) {
mApplicationViewportInsetSupplier.removeSupplier(
mInsetObserverView.getSupplierForBottomInset());
}
}
}
@Override
public void onInsetChanged(int left, int top, int right, int bottom) {
if (mShowingFullscreen) handleWindowInsetChanged();
}
private void handleWindowInsetChanged() {
// The InsetObserverView is used to monitor keyboard resizes while
// fullscreened to simulate a view resize. This is unneeded when the
// OSK resizes only the visual viewport.
if (oskResizesVisualViewport()) {
return;
}
// Notify the WebContents that the size has changed.
View contentView = getContentView();
if (contentView != null) {
Point viewportSize = getViewportSize();
setSize(getWebContents(), contentView, viewportSize.x, viewportSize.y);
}
// Notify the compositor layout that the size has changed. The layout does not drive
// the WebContents sizing, so this needs to be done in addition to the above size update.
onViewportChanged();
}
@Override
public void onSafeAreaChanged(Rect area) {}
/**
* Should be called for cleanup when the CompositorView instance is no longer used.
*/
public void shutDown() {
setTab(null);
if (mApplicationBottomInsetSupplier != null && mBottomInsetObserver != null) {
mApplicationBottomInsetSupplier.removeObserver(mBottomInsetObserver);
}
if (mAutofillUiBottomInsetSupplier != null && mBottomInsetObserver != null) {
mAutofillUiBottomInsetSupplier.removeObserver(mBottomInsetObserver);
}
mCompositorView.shutDown();
if (mLayoutManager != null) mLayoutManager.destroy();
if (mInsetObserverView != null) {
mInsetObserverView.removeObserver(this);
mInsetObserverView = null;
}
if (mOnscreenContentProvider != null) mOnscreenContentProvider.destroy();
if (mContentView != null) {
mContentView.removeOnHierarchyChangeListener(this);
}
}
/**
* This is called when the native library are ready.
*/
public void onNativeLibraryReady(
WindowAndroid windowAndroid, TabContentManager tabContentManager) {
mCompositorView.initNativeCompositor(
SysUtils.isLowEndDevice(), windowAndroid, tabContentManager);
if (mControlContainer != null) {
mCompositorView.getResourceManager().getDynamicResourceLoader().registerResource(
R.id.control_container, mControlContainer.getToolbarResourceAdapter());
}
mApplicationBottomInsetSupplier = windowAndroid.getApplicationBottomInsetProvider();
mApplicationBottomInsetSupplier.addObserver(mBottomInsetObserver);
}
/**
* Perform any initialization necessary for showing a reparented tab.
*/
public void prepareForTabReparenting() {
if (mHasDrawnOnce) return;
// Set the background to white while we wait for the first swap of buffers. This gets
// corrected inside the view.
mCompositorView.setBackgroundColor(Color.WHITE);
}
@Override
public ResourceManager getResourceManager() {
return mCompositorView.getResourceManager();
}
/**
* @return The {@link DynamicResourceLoader} for registering resources.
*/
public DynamicResourceLoader getDynamicResourceLoader() {
return mCompositorView.getResourceManager().getDynamicResourceLoader();
}
/**
* @return The {@link Invalidator} instance that is driven by this {@link CompositorViewHolder}.
*/
public Invalidator getInvalidator() {
return mInvalidator;
}
/**
* Add observer that needs to listen and process touch events.
* @param o {@link TouchEventObserver} object.
*/
public void addTouchEventObserver(TouchEventObserver o) {
mTouchEventObservers.addObserver(o);
}
/**
* Remove observer that needs to listen and process touch events.
* @param o {@link TouchEventObserver} object.
*/
public void removeTouchEventObserver(TouchEventObserver o) {
mTouchEventObservers.removeObserver(o);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
super.onInterceptTouchEvent(e);
for (TouchEventObserver o : mTouchEventObservers) {
if (o.shouldInterceptTouchEvent(e)) return true;
}
updateIsInGesture(e);
if (mLayoutManager == null) return false;
mEventOffsetHandler.onInterceptTouchEvent(e);
return mLayoutManager.onInterceptTouchEvent(e, mIsKeyboardShowing);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
super.onTouchEvent(e);
updateIsInGesture(e);
boolean consumed = mLayoutManager != null && mLayoutManager.onTouchEvent(e);
mEventOffsetHandler.onTouchEvent(e);
return consumed;
}
private void updateIsInGesture(MotionEvent e) {
int eventAction = e.getActionMasked();
if (eventAction == MotionEvent.ACTION_DOWN
|| eventAction == MotionEvent.ACTION_POINTER_DOWN) {
mInGesture = true;
} else if (eventAction == MotionEvent.ACTION_CANCEL
|| eventAction == MotionEvent.ACTION_UP) {
mInGesture = false;
updateViewportSize();
}
}
@Override
public boolean onInterceptHoverEvent(MotionEvent e) {
mEventOffsetHandler.onInterceptHoverEvent(e);
return super.onInterceptHoverEvent(e);
}
@Override
public boolean dispatchHoverEvent(MotionEvent e) {
if (mNodeProvider != null) {
if (mNodeProvider.dispatchHoverEvent(e)) {
return true;
}
}
return super.dispatchHoverEvent(e);
}
@Override
public boolean dispatchDragEvent(DragEvent e) {
mEventOffsetHandler.onPreDispatchDragEvent(e.getAction());
boolean ret = super.dispatchDragEvent(e);
mEventOffsetHandler.onPostDispatchDragEvent(e.getAction());
return ret;
}
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
updateLastActiveTouchEvent(e);
for (TouchEventObserver o : mTouchEventObservers) o.handleTouchEvent(e);
return super.dispatchTouchEvent(e);
}
private void updateLastActiveTouchEvent(MotionEvent e) {
if (e.getActionMasked() == MotionEvent.ACTION_MOVE
|| e.getActionMasked() == MotionEvent.ACTION_DOWN
|| e.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN
|| e.getActionMasked() == MotionEvent.ACTION_POINTER_UP) {
mLastActiveTouchEvent = e;
}
if (e.getActionMasked() == MotionEvent.ACTION_CANCEL
|| e.getActionMasked() == MotionEvent.ACTION_UP) {
mLastActiveTouchEvent = null;
}
}
/**
* @return The {@link LayoutManagerImpl} associated with this view.
*/
public LayoutManagerImpl getLayoutManager() {
return mLayoutManager;
}
/**
* @return The SurfaceView proxy used by the Compositor.
*/
public CompositorView getCompositorView() {
return mCompositorView;
}
/**
* @return The active {@link android.view.SurfaceView} of the Compositor.
*/
public View getActiveSurfaceView() {
return mCompositorView.getActiveSurfaceView();
}
private Tab getCurrentTab() {
if (mLayoutManager == null || mTabModelSelector == null) return null;
Tab currentTab = mTabModelSelector.getCurrentTab();
// If the tab model selector doesn't know of a current tab, use the last visible one.
if (currentTab == null) currentTab = mTabVisible;
return currentTab;
}
@VisibleForTesting
ViewGroup getContentView() {
Tab tab = getCurrentTab();
return tab != null ? tab.getContentView() : null;
}
protected WebContents getWebContents() {
Tab tab = getCurrentTab();
return tab != null ? tab.getWebContents() : null;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mTabModelSelector == null) return;
Point viewportSize = getViewportSize();
for (TabModel tabModel : mTabModelSelector.getModels()) {
for (int i = 0; i < tabModel.getCount(); ++i) {
Tab tab = tabModel.getTabAt(i);
if (tab == null) continue;
setSize(tab.getWebContents(), tab.getContentView(), viewportSize.x, viewportSize.y);
}
}
}
/**
* Set tab-backed content view size.
*
* @param webContents {@link WebContents} for which the size of the view is set.
* @param view {@link View} of the content.
* @param w Width of the view.
* @param h Height of the view.
*/
@VisibleForTesting
void setSize(WebContents webContents, View view, int w, int h) {
if (webContents == null || view == null) return;
// When in VR, the CompositorView doesn't control the size of the WebContents.
if (mIsInVr) return;
// The view size takes into account of the browser controls whose height
// should be subtracted from the view if they are visible, therefore shrink
// Blink-side view size.
// TODO(https://crbug.com/1211066): Centralize the logic for calculating bottom insets.
final int totalMinHeight = getKeyboardBottomInsetForControlsPixels()
+ (mBrowserControlsManager != null
? mBrowserControlsManager.getTopControlsMinHeight()
+ mBrowserControlsManager.getBottomControlsMinHeight()
: 0);
int controlsHeight = mControlsResizeView
? getTopControlsHeightPixels() + getBottomControlsHeightPixels()
: totalMinHeight;
if (isAttachedToWindow(view)) {
// If overlay content flag is set and the keyboard is shown or hidden then resize the
// visual/layout viewports in WebContents to match the previous size so there
// isn't a change in size after the keyboard is raised or hidden.
// Also the geometrychange event should only fire to the foreground tab.
int keyboardHeight = 0;
boolean vkModePreservesWebContentsHeight =
mVirtualKeyboardMode == VirtualKeyboardMode.OVERLAYS_CONTENT
|| oskResizesVisualViewport();
// In fullscreen, the keyboard doesn't resize the view so there's no need to adjust the
// layout height by the keyboard height to keep it from changing in response.
if (!mShowingFullscreen && vkModePreservesWebContentsHeight) {
// During orientation changes, width of the |WebContents| changes to match the width
// of the screen and so does the keyboard. We fire geometrychange with the updated
// keyboard size as well as resize the viewport so the height resize doesn't affect
// the |WebContents|.
keyboardHeight = KeyboardVisibilityDelegate.getInstance().calculateKeyboardHeight(
this.getRootView());
h += keyboardHeight;
}
webContents.setSize(w, h - controlsHeight);
if (mVirtualKeyboardMode == VirtualKeyboardMode.OVERLAYS_CONTENT) {
notifyVirtualKeyboardOverlayGeometryChangeEvent(w, keyboardHeight, webContents);
}
} else {
setSizeOfUnattachedView(view, webContents, controlsHeight);
requestRender();
}
}
private static boolean isAttachedToWindow(View view) {
return view != null && view.getWindowToken() != null;
}
private boolean oskResizesVisualViewport() {
// UNSET means the author hasn't explicitly set a preference but the mode should have been
// set to the default in that case.
assert mVirtualKeyboardMode != VirtualKeyboardMode.UNSET;
return mVirtualKeyboardMode == VirtualKeyboardMode.RESIZES_VISUAL;
}
/**
* Notifies geometrychange event to JS.
* @param w Width of the view.
* @param keyboardHeight Height of the keyboard.
* @param webContents Active WebContent for which this event needs to be fired.
*/
private void notifyVirtualKeyboardOverlayGeometryChangeEvent(
int w, int keyboardHeight, WebContents webContents) {
assert mVirtualKeyboardMode == VirtualKeyboardMode.OVERLAYS_CONTENT;
boolean keyboardVisible = keyboardHeight > 0;
if (!keyboardVisible && !mHasKeyboardGeometryChangeFired) {
return;
}
mHasKeyboardGeometryChangeFired = keyboardVisible;
Rect appRect = new Rect();
getRootView().getWindowVisibleDisplayFrame(appRect);
if (keyboardVisible) {
// Fire geometrychange event to JS.
// The assumption here is that the keyboard is docked at the bottom so we use the
// root visible window frame's origin to calculate the position of the keyboard.
notifyVirtualKeyboardOverlayRect(
webContents, appRect.left, appRect.top, w, keyboardHeight);
} else {
// Keyboard has hidden.
notifyVirtualKeyboardOverlayRect(webContents, 0, 0, 0, 0);
}
}
@Override
public void onSurfaceResized(int width, int height) {
View view = getContentView();
WebContents webContents = getWebContents();
if (view == null || webContents == null) return;
onPhysicalBackingSizeChanged(webContents, width, height);
}
private void onPhysicalBackingSizeChanged(WebContents webContents, int width, int height) {
if (mCompositorView != null) {
mCompositorView.onPhysicalBackingSizeChanged(webContents, width, height);
}
}
private void onControlsResizeViewChanged(WebContents webContents, boolean controlsResizeView) {
if (webContents != null && mCompositorView != null) {
mCompositorView.onControlsResizeViewChanged(webContents, controlsResizeView);
}
}
/**
* Fires geometrychange event to JS with the keyboard size.
* @param webContents Active WebContent for which this event needs to be fired.
* @param x When the keyboard is shown, it has the left position of the app's rect, else, 0.
* @param y When the keyboard is shown, it has the top position of the app's rect, else, 0.
* @param width When the keyboard is shown, it has the width of the view, else, 0.
* @param height The height of the keyboard.
*/
@VisibleForTesting
void notifyVirtualKeyboardOverlayRect(
WebContents webContents, int x, int y, int width, int height) {
if (mCompositorView != null) {
mCompositorView.notifyVirtualKeyboardOverlayRect(webContents, x, y, width, height);
}
}
/**
* Called whenever the host activity is started.
*/
public void onStart() {
if (mBrowserControlsManager != null) mBrowserControlsManager.addObserver(this);
requestRender();
}
/**
* Called whenever the host activity is stopped.
*/