Debian Codegraph @

core/java/android/view/ViewRootImpl.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.view;
18
19 import static android.graphics.HardwareRenderer.SYNC_CONTEXT_IS_STOPPED;
20 import static android.graphics.HardwareRenderer.SYNC_LOST_SURFACE_REWARD_IF_FOUND;
21 import static android.os.IInputConstants.INVALID_INPUT_EVENT_ID;
22 import static android.view.Display.DEFAULT_DISPLAY;
23 import static android.view.Display.INVALID_DISPLAY;
24 import static android.view.InputDevice.SOURCE_CLASS_NONE;
25 import static android.view.InsetsState.ITYPE_IME;
26 import static android.view.InsetsState.SIZE;
27 import static android.view.View.PFLAG_DRAW_ANIMATION;
28 import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
29 import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
30 import static android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
31 import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
32 import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
33 import static android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
34 import static android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
35 import static android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE;
36 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
37 import static android.view.ViewRootImplProto.ADDED;
38 import static android.view.ViewRootImplProto.APP_VISIBLE;
39 import static android.view.ViewRootImplProto.CUR_SCROLL_Y;
40 import static android.view.ViewRootImplProto.DISPLAY_ID;
41 import static android.view.ViewRootImplProto.HEIGHT;
42 import static android.view.ViewRootImplProto.IS_ANIMATING;
43 import static android.view.ViewRootImplProto.IS_DRAWING;
44 import static android.view.ViewRootImplProto.LAST_WINDOW_INSETS;
45 import static android.view.ViewRootImplProto.REMOVED;
46 import static android.view.ViewRootImplProto.SCROLL_Y;
47 import static android.view.ViewRootImplProto.SOFT_INPUT_MODE;
48 import static android.view.ViewRootImplProto.VIEW;
49 import static android.view.ViewRootImplProto.VISIBLE_RECT;
50 import static android.view.ViewRootImplProto.WIDTH;
51 import static android.view.ViewRootImplProto.WINDOW_ATTRIBUTES;
52 import static android.view.ViewRootImplProto.WIN_FRAME;
53 import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
54 import static android.view.WindowCallbacks.RESIZE_MODE_FREEFORM;
55 import static android.view.WindowCallbacks.RESIZE_MODE_INVALID;
56 import static android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS;
57 import static android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS;
58 import static android.view.WindowInsetsController.APPEARANCE_LOW_PROFILE_BARS;
59 import static android.view.WindowInsetsController.BEHAVIOR_DEFAULT;
60 import static android.view.WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
61 import static android.view.WindowLayout.UNSPECIFIED_LENGTH;
62 import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
63 import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
64 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
65 import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
66 import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
67 import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
68 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
69 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
70 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_APPEARANCE_CONTROLLED;
71 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_BEHAVIOR_CONTROLLED;
72 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
73 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
74 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_INSET_PARENT_FRAME_BY_IME;
75 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT;
76 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
77 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
78 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
79 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
80 import static android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE;
81 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_ADDITIONAL;
82 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
83 import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
84 import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
85 import static android.view.WindowManagerGlobal.RELAYOUT_RES_CANCEL_AND_REDRAW;
86 import static android.view.WindowManagerGlobal.RELAYOUT_RES_CONSUME_ALWAYS_SYSTEM_BARS;
87 import static android.view.WindowManagerGlobal.RELAYOUT_RES_SURFACE_CHANGED;
88 import static android.view.inputmethod.InputMethodEditorTraceProto.InputMethodClientsTraceProto.ClientSideProto.IME_FOCUS_CONTROLLER;
89 import static android.view.inputmethod.InputMethodEditorTraceProto.InputMethodClientsTraceProto.ClientSideProto.INSETS_CONTROLLER;
90
91 import android.Manifest;
92 import android.animation.AnimationHandler;
93 import android.animation.LayoutTransition;
94 import android.annotation.AnyThread;
95 import android.annotation.NonNull;
96 import android.annotation.Nullable;
97 import android.annotation.UiContext;
98 import android.app.ActivityManager;
99 import android.app.ActivityThread;
100 import android.app.ICompatCameraControlCallback;
101 import android.app.ResourcesManager;
102 import android.app.WindowConfiguration;
103 import android.compat.annotation.UnsupportedAppUsage;
104 import android.content.ClipData;
105 import android.content.ClipDescription;
106 import android.content.Context;
107 import android.content.pm.ActivityInfo;
108 import android.content.pm.PackageManager;
109 import android.content.res.CompatibilityInfo;
110 import android.content.res.Configuration;
111 import android.content.res.Resources;
112 import android.content.res.TypedArray;
113 import android.graphics.BLASTBufferQueue;
114 import android.graphics.Canvas;
115 import android.graphics.Color;
116 import android.graphics.FrameInfo;
117 import android.graphics.HardwareRenderer;
118 import android.graphics.HardwareRenderer.FrameDrawingCallback;
119 import android.graphics.HardwareRendererObserver;
120 import android.graphics.Insets;
121 import android.graphics.Matrix;
122 import android.graphics.PixelFormat;
123 import android.graphics.Point;
124 import android.graphics.PointF;
125 import android.graphics.PorterDuff;
126 import android.graphics.RecordingCanvas;
127 import android.graphics.Rect;
128 import android.graphics.Region;
129 import android.graphics.RenderNode;
130 import android.graphics.drawable.Drawable;
131 import android.graphics.drawable.GradientDrawable;
132 import android.hardware.display.DisplayManager;
133 import android.hardware.display.DisplayManager.DisplayListener;
134 import android.hardware.input.InputManager;
135 import android.media.AudioManager;
136 import android.os.Binder;
137 import android.os.Build;
138 import android.os.Bundle;
139 import android.os.Debug;
140 import android.os.Handler;
141 import android.os.IBinder;
142 import android.os.Looper;
143 import android.os.Message;
144 import android.os.ParcelFileDescriptor;
145 import android.os.Process;
146 import android.os.RemoteException;
147 import android.os.SystemClock;
148 import android.os.SystemProperties;
149 import android.os.Trace;
150 import android.os.UserHandle;
151 import android.sysprop.DisplayProperties;
152 import android.text.TextUtils;
153 import android.util.AndroidRuntimeException;
154 import android.util.DisplayMetrics;
155 import android.util.EventLog;
156 import android.util.IndentingPrintWriter;
157 import android.util.Log;
158 import android.util.LongArray;
159 import android.util.MergedConfiguration;
160 import android.util.Slog;
161 import android.util.SparseArray;
162 import android.util.TimeUtils;
163 import android.util.TypedValue;
164 import android.util.proto.ProtoOutputStream;
165 import android.view.InputDevice.InputSourceClass;
166 import android.view.InsetsState.InternalInsetsType;
167 import android.view.Surface.OutOfResourcesException;
168 import android.view.SurfaceControl.Transaction;
169 import android.view.View.AttachInfo;
170 import android.view.View.FocusDirection;
171 import android.view.View.MeasureSpec;
172 import android.view.Window.OnContentApplyWindowInsetsListener;
173 import android.view.WindowInsets.Type;
174 import android.view.WindowInsets.Type.InsetsType;
175 import android.view.WindowManager.LayoutParams.SoftInputModeFlags;
176 import android.view.accessibility.AccessibilityEvent;
177 import android.view.accessibility.AccessibilityManager;
178 import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
179 import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
180 import android.view.accessibility.AccessibilityNodeIdManager;
181 import android.view.accessibility.AccessibilityNodeInfo;
182 import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
183 import android.view.accessibility.AccessibilityNodeProvider;
184 import android.view.accessibility.AccessibilityWindowInfo;
185 import android.view.accessibility.IAccessibilityEmbeddedConnection;
186 import android.view.accessibility.IAccessibilityInteractionConnection;
187 import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
188 import android.view.animation.AccelerateDecelerateInterpolator;
189 import android.view.animation.Interpolator;
190 import android.view.autofill.AutofillId;
191 import android.view.autofill.AutofillManager;
192 import android.view.contentcapture.ContentCaptureManager;
193 import android.view.contentcapture.ContentCaptureSession;
194 import android.view.contentcapture.MainContentCaptureSession;
195 import android.view.inputmethod.InputMethodManager;
196 import android.widget.Scroller;
197 import android.window.ClientWindowFrames;
198 import android.window.CompatOnBackInvokedCallback;
199 import android.window.OnBackInvokedCallback;
200 import android.window.OnBackInvokedDispatcher;
201 import android.window.SurfaceSyncer;
202 import android.window.WindowOnBackInvokedDispatcher;
203
204 import com.android.internal.R;
205 import com.android.internal.annotations.GuardedBy;
206 import com.android.internal.annotations.VisibleForTesting;
207 import com.android.internal.graphics.drawable.BackgroundBlurDrawable;
208 import com.android.internal.inputmethod.ImeTracing;
209 import com.android.internal.inputmethod.InputMethodDebug;
210 import com.android.internal.os.IResultReceiver;
211 import com.android.internal.os.SomeArgs;
212 import com.android.internal.policy.DecorView;
213 import com.android.internal.policy.PhoneFallbackEventHandler;
214 import com.android.internal.util.Preconditions;
215 import com.android.internal.view.BaseSurfaceHolder;
216 import com.android.internal.view.RootViewSurfaceTaker;
217 import com.android.internal.view.SurfaceCallbackHelper;
218
219 import java.io.IOException;
220 import java.io.OutputStream;
221 import java.io.PrintWriter;
222 import java.io.StringWriter;
223 import java.lang.ref.WeakReference;
224 import java.util.ArrayDeque;
225 import java.util.ArrayList;
226 import java.util.HashSet;
227 import java.util.List;
228 import java.util.Objects;
229 import java.util.Queue;
230 import java.util.concurrent.CountDownLatch;
231
232 /**
233 * The top of a view hierarchy, implementing the needed protocol between View
234 * and the WindowManager. This is for the most part an internal implementation
235 * detail of {@link WindowManagerGlobal}.
236 *
237 * {@hide}
238 */
239 @SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
240 public final class ViewRootImpl implements ViewParent,
241 View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks,
242 AttachedSurfaceControl {
243 private static final String TAG = "ViewRootImpl";
244 private static final boolean DBG = false;
245 private static final boolean LOCAL_LOGV = false;
246 /** @noinspection PointlessBooleanExpression*/
247 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
248 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
249 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
250 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
251 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
252 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
253 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
254 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
255 private static final boolean DEBUG_FPS = false;
256 private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
257 private static final boolean DEBUG_KEEP_SCREEN_ON = false || LOCAL_LOGV;
258 private static final boolean DEBUG_CONTENT_CAPTURE = false || LOCAL_LOGV;
259 private static final boolean DEBUG_SCROLL_CAPTURE = false || LOCAL_LOGV;
260 private static final boolean DEBUG_BLAST = false || LOCAL_LOGV;
261 private static final int LOGTAG_INPUT_FOCUS = 62001;
262
263 /**
264 * Set to false if we do not want to use the multi threaded renderer even though
265 * threaded renderer (aka hardware renderering) is used. Note that by disabling
266 * this, WindowCallbacks will not fire.
267 */
268 private static final boolean MT_RENDERER_AVAILABLE = true;
269
270 /**
271 * Whether or not to report end-to-end input latency. Can be disabled temporarily as a
272 * risk mitigation against potential jank caused by acquiring a weak reference
273 * per frame.
274 */
275 private static final boolean ENABLE_INPUT_LATENCY_TRACKING = true;
276
277 /**
278 * Whether the caption is drawn by the shell.
279 * @hide
280 */
281 public static final boolean CAPTION_ON_SHELL =
282 SystemProperties.getBoolean("persist.wm.debug.caption_on_shell", false);
283
284 /**
285 * Whether the client should compute the window frame on its own.
286 * @hide
287 */
288 public static final boolean LOCAL_LAYOUT =
289 SystemProperties.getBoolean("persist.debug.local_layout", true);
290
291 /**
292 * Set this system property to true to force the view hierarchy to render
293 * at 60 Hz. This can be used to measure the potential framerate.
294 */
295 private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
296
297 /**
298 * Maximum time we allow the user to roll the trackball enough to generate
299 * a key event, before resetting the counters.
300 */
301 static final int MAX_TRACKBALL_DELAY = 250;
302
303 /**
304 * Initial value for {@link #mContentCaptureEnabled}.
305 */
306 private static final int CONTENT_CAPTURE_ENABLED_NOT_CHECKED = 0;
307
308 /**
309 * Value for {@link #mContentCaptureEnabled} when it was checked and set to {@code true}.
310 */
311 private static final int CONTENT_CAPTURE_ENABLED_TRUE = 1;
312
313 /**
314 * Value for {@link #mContentCaptureEnabled} when it was checked and set to {@code false}.
315 */
316 private static final int CONTENT_CAPTURE_ENABLED_FALSE = 2;
317
318 /**
319 * Maximum time to wait for {@link View#dispatchScrollCaptureSearch} to complete.
320 */
321 private static final int SCROLL_CAPTURE_REQUEST_TIMEOUT_MILLIS = 2500;
322
323 private static final int UNSET_SYNC_ID = -1;
324
325 /**
326 * Minimum time to wait before reporting changes to keep clear areas.
327 */
328 private static final int KEEP_CLEAR_AREA_REPORT_RATE_MILLIS = 100;
329
330 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
331 static final ThreadLocal<HandlerActionQueue> sRunQueues = new ThreadLocal<HandlerActionQueue>();
332
333 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList<>();
334 static boolean sFirstDrawComplete = false;
335
336 private ArrayList<OnBufferTransformHintChangedListener> mTransformHintListeners =
337 new ArrayList<>();
338 private @SurfaceControl.BufferTransform
339 int mPreviousTransformHint = SurfaceControl.BUFFER_TRANSFORM_IDENTITY;
340 /**
341 * The top level {@link OnBackInvokedDispatcher}.
342 */
343 private final WindowOnBackInvokedDispatcher mOnBackInvokedDispatcher;
344 /**
345 * Compatibility {@link OnBackInvokedCallback} that dispatches KEYCODE_BACK events
346 * to view root for apps using legacy back behavior.
347 */
348 private CompatOnBackInvokedCallback mCompatOnBackInvokedCallback;
349
350 /**
351 * Callback for notifying about global configuration changes.
352 */
353 public interface ConfigChangedCallback {
354
355 /** Notifies about global config change. */
356 void onConfigurationChanged(Configuration globalConfig);
357 }
358
359 private static final ArrayList<ConfigChangedCallback> sConfigCallbacks = new ArrayList<>();
360
361 /**
362 * Callback for notifying activities.
363 */
364 public interface ActivityConfigCallback {
365
366 /**
367 * Notifies about override config change and/or move to different display.
368 * @param overrideConfig New override config to apply to activity.
369 * @param newDisplayId New display id, {@link Display#INVALID_DISPLAY} if not changed.
370 */
371 void onConfigurationChanged(Configuration overrideConfig, int newDisplayId);
372
373 /**
374 * Notify the corresponding activity about the request to show or hide a camera compat
375 * control for stretched issues in the viewfinder.
376 *
377 * @param showControl Whether the control should be shown or hidden.
378 * @param transformationApplied Whether the treatment is already applied.
379 * @param callback The callback executed when the user clicks on a control.
380 */
381 void requestCompatCameraControl(boolean showControl, boolean transformationApplied,
382 ICompatCameraControlCallback callback);
383 }
384
385 /**
386 * Callback used to notify corresponding activity about camera compat control changes, override
387 * configuration change and make sure that all resources are set correctly before updating the
388 * ViewRootImpl's internal state.
389 */
390 private ActivityConfigCallback mActivityConfigCallback;
391
392 /**
393 * Used when configuration change first updates the config of corresponding activity.
394 * In that case we receive a call back from {@link ActivityThread} and this flag is used to
395 * preserve the initial value.
396 *
397 * @see #performConfigurationChange(MergedConfiguration, boolean, int)
398 */
399 private boolean mForceNextConfigUpdate;
400
401 private boolean mUseBLASTAdapter;
402 private boolean mForceDisableBLAST;
403
404 private boolean mFastScrollSoundEffectsEnabled;
405
406 /**
407 * Signals that compatibility booleans have been initialized according to
408 * target SDK versions.
409 */
410 private static boolean sCompatibilityDone = false;
411
412 /**
413 * Always assign focus if a focusable View is available.
414 */
415 private static boolean sAlwaysAssignFocus;
416
417 /**
418 * This list must only be modified by the main thread.
419 */
420 final ArrayList<WindowCallbacks> mWindowCallbacks = new ArrayList<>();
421 @UnsupportedAppUsage
422 @UiContext
423 public final Context mContext;
424
425 @UnsupportedAppUsage
426 final IWindowSession mWindowSession;
427 @NonNull Display mDisplay;
428 final DisplayManager mDisplayManager;
429 final String mBasePackageName;
430
431 private @Surface.Rotation int mDisplayInstallOrientation;
432
433 final int[] mTmpLocation = new int[2];
434
435 final TypedValue mTmpValue = new TypedValue();
436
437 final Thread mThread;
438
439 final WindowLeaked mLocation;
440
441 public final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
442
443 final W mWindow;
444
445 final IBinder mLeashToken;
446
447 final int mTargetSdkVersion;
448
449 @UnsupportedAppUsage
450 View mView;
451
452 View mAccessibilityFocusedHost;
453 // Accessibility-focused virtual view. The bounds and sourceNodeId of
454 // mAccessibilityFocusedVirtualView is up-to-date while other fields may be stale.
455 AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
456
457 // True if the window currently has pointer capture enabled.
458 boolean mPointerCapture;
459
460 int mViewVisibility;
461 boolean mAppVisible = true;
462 // For recents to freeform transition we need to keep drawing after the app receives information
463 // that it became invisible. This will ignore that information and depend on the decor view
464 // visibility to control drawing. The decor view visibility will get adjusted when the app get
465 // stopped and that's when the app will stop drawing further frames.
466 private boolean mForceDecorViewVisibility = false;
467 // Used for tracking app visibility updates separately in case we get double change. This will
468 // make sure that we always call relayout for the corresponding window.
469 private boolean mAppVisibilityChanged;
470 int mOrigWindowType = -1;
471
472 /** Whether the window had focus during the most recent traversal. */
473 boolean mHadWindowFocus;
474
475 /**
476 * Whether the window lost focus during a previous traversal and has not
477 * yet gained it back. Used to determine whether a WINDOW_STATE_CHANGE
478 * accessibility events should be sent during traversal.
479 */
480 boolean mLostWindowFocus;
481
482 // Set to true if the owner of this window is in the stopped state,
483 // so the window should no longer be active.
484 @UnsupportedAppUsage
485 boolean mStopped = false;
486
487 // Set to true if the owner of this window is in ambient mode,
488 // which means it won't receive input events.
489 boolean mIsAmbientMode = false;
490
491 // Set to true to stop input during an Activity Transition.
492 boolean mPausedForTransition = false;
493
494 boolean mLastInCompatMode = false;
495
496 SurfaceHolder.Callback2 mSurfaceHolderCallback;
497 BaseSurfaceHolder mSurfaceHolder;
498 boolean mIsCreating;
499 boolean mDrawingAllowed;
500
501 final Region mTransparentRegion;
502 final Region mPreviousTransparentRegion;
503
504 Region mTouchableRegion;
505 Region mPreviousTouchableRegion;
506
507 private int mMeasuredWidth;
508 private int mMeasuredHeight;
509
510 // This indicates that we've already known the window size but without measuring the views.
511 // If this is true, we must measure the views before laying out them.
512 private boolean mViewMeasureDeferred;
513
514 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
515 int mWidth;
516 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
517 int mHeight;
518 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
519 private Rect mDirty;
520 public boolean mIsAnimating;
521
522 private boolean mUseMTRenderer;
523 private boolean mPendingDragResizing;
524 private boolean mDragResizing;
525 private boolean mInvalidateRootRequested;
526 private int mResizeMode = RESIZE_MODE_INVALID;
527 private int mCanvasOffsetX;
528 private int mCanvasOffsetY;
529 private boolean mActivityRelaunched;
530
531 CompatibilityInfo.Translator mTranslator;
532
533 @UnsupportedAppUsage
534 final View.AttachInfo mAttachInfo;
535 final SystemUiVisibilityInfo mCompatibleVisibilityInfo;
536 int mDispatchedSystemUiVisibility;
537 int mDispatchedSystemBarAppearance;
538 InputQueue.Callback mInputQueueCallback;
539 InputQueue mInputQueue;
540 @UnsupportedAppUsage
541 FallbackEventHandler mFallbackEventHandler;
542 final Choreographer mChoreographer;
543 protected final ViewFrameInfo mViewFrameInfo = new ViewFrameInfo();
544 private final InputEventAssigner mInputEventAssigner = new InputEventAssigner();
545
546 // Whether to draw this surface as DISPLAY_DECORATION.
547 boolean mDisplayDecorationCached = false;
548
549 /**
550 * Update the Choreographer's FrameInfo object with the timing information for the current
551 * ViewRootImpl instance. Erase the data in the current ViewFrameInfo to prepare for the next
552 * frame.
553 * @return the updated FrameInfo object
554 */
555 protected @NonNull FrameInfo getUpdatedFrameInfo() {
556 // Since Choreographer is a thread-local singleton while we can have multiple
557 // ViewRootImpl's, populate the frame information from the current viewRootImpl before
558 // starting the draw
559 FrameInfo frameInfo = mChoreographer.mFrameInfo;
560 mViewFrameInfo.populateFrameInfo(frameInfo);
561 mViewFrameInfo.reset();
562 mInputEventAssigner.notifyFrameProcessed();
563 return frameInfo;
564 }
565
566 // used in relayout to get SurfaceControl size
567 // for BLAST adapter surface setup
568 private final Point mSurfaceSize = new Point();
569 private final Point mLastSurfaceSize = new Point();
570
571 private final Rect mVisRect = new Rect(); // used to retrieve visible rect of focused view.
572 private final Rect mTempRect = new Rect();
573
574 private final WindowLayout mWindowLayout;
575
576 // This is used to reduce the race between window focus changes being dispatched from
577 // the window manager and input events coming through the input system.
578 @GuardedBy("this")
579 boolean mWindowFocusChanged;
580 @GuardedBy("this")
581 boolean mUpcomingWindowFocus;
582 @GuardedBy("this")
583 boolean mUpcomingInTouchMode;
584
585 public boolean mTraversalScheduled;
586 int mTraversalBarrier;
587 boolean mWillDrawSoon;
588 /** Set to true while in performTraversals for detecting when die(true) is called from internal
589 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
590 boolean mIsInTraversal;
591 boolean mApplyInsetsRequested;
592 boolean mLayoutRequested;
593 boolean mFirst;
594
595 @Nullable
596 int mContentCaptureEnabled = CONTENT_CAPTURE_ENABLED_NOT_CHECKED;
597 boolean mPerformContentCapture;
598
599 boolean mReportNextDraw;
600 /** Set only while mReportNextDraw=true, indicating the last reason that was triggered */
601 String mLastReportNextDrawReason;
602 /** The reaason the last call to performDraw() returned false */
603 String mLastPerformDrawSkippedReason;
604 /** The reason the last call to performTraversals() returned without drawing */
605 String mLastPerformTraversalsSkipDrawReason;
606 /** The state of the local sync, if one is in progress. Can be one of the states below. */
607 int mLocalSyncState;
608
609 // The possible states of the local sync, see createSyncIfNeeded()
610 private final int LOCAL_SYNC_NONE = 0;
611 private final int LOCAL_SYNC_PENDING = 1;
612 private final int LOCAL_SYNC_RETURNED = 2;
613 private final int LOCAL_SYNC_MERGED = 3;
614
615 /**
616 * Set whether the draw should send the buffer to system server. When set to true, VRI will
617 * create a sync transaction with BBQ and send the resulting buffer to system server. If false,
618 * VRI will not try to sync a buffer in BBQ, but still report when a draw occurred.
619 */
620 private boolean mSyncBuffer = false;
621
622 /**
623 * Flag to determine whether the client needs to check with WMS if it can draw. WMS will notify
624 * the client that it can't draw if we're still in the middle of a sync set that includes this
625 * window. Once the sync is complete, the window can resume drawing. This is to ensure we don't
626 * deadlock the client by trying to request draws when there may not be any buffers available.
627 */
628 private boolean mCheckIfCanDraw = false;
629
630 private boolean mDrewOnceForSync = false;
631
632 int mSyncSeqId = 0;
633 int mLastSyncSeqId = 0;
634
635 private boolean mUpdateSurfaceNeeded;
636 boolean mFullRedrawNeeded;
637 boolean mNewSurfaceNeeded;
638 boolean mForceNextWindowRelayout;
639 CountDownLatch mWindowDrawCountDown;
640
641 // Whether we have used applyTransactionOnDraw to schedule an RT
642 // frame callback consuming a passed in transaction. In this case
643 // we also need to schedule a commit callback so we can observe
644 // if the draw was skipped, and the BBQ pending transactions.
645 boolean mHasPendingTransactions;
646
647 boolean mIsDrawing;
648 int mLastSystemUiVisibility;
649 int mClientWindowLayoutFlags;
650
651 // Pool of queued input events.
652 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
653 private QueuedInputEvent mQueuedInputEventPool;
654 private int mQueuedInputEventPoolSize;
655
656 /* Input event queue.
657 * Pending input events are input events waiting to be delivered to the input stages
658 * and handled by the application.
659 */
660 QueuedInputEvent mPendingInputEventHead;
661 QueuedInputEvent mPendingInputEventTail;
662 int mPendingInputEventCount;
663 boolean mProcessInputEventsScheduled;
664 boolean mUnbufferedInputDispatch;
665 @InputSourceClass
666 int mUnbufferedInputSource = SOURCE_CLASS_NONE;
667
668 String mPendingInputEventQueueLengthCounterName = "pq";
669
670 InputStage mFirstInputStage;
671 InputStage mFirstPostImeInputStage;
672 InputStage mSyntheticInputStage;
673
674 private final UnhandledKeyManager mUnhandledKeyManager = new UnhandledKeyManager();
675
676 boolean mWindowAttributesChanged = false;
677
678 // These can be accessed by any thread, must be protected with a lock.
679 // Surface can never be reassigned or cleared (use Surface.clear()).
680 @UnsupportedAppUsage
681 public final Surface mSurface = new Surface();
682 private final SurfaceControl mSurfaceControl = new SurfaceControl();
683
684 private BLASTBufferQueue mBlastBufferQueue;
685
686 /**
687 * Transaction object that can be used to synchronize child SurfaceControl changes with
688 * ViewRootImpl SurfaceControl changes by the server. The object is passed along with
689 * the SurfaceChangedCallback.
690 */
691 private final Transaction mSurfaceChangedTransaction = new Transaction();
692 /**
693 * Child container layer of {@code mSurface} with the same bounds as its parent, and cropped to
694 * the surface insets. This surface is created only if a client requests it via {@link
695 * #getBoundsLayer()}. By parenting to this bounds surface, child surfaces can ensure they do
696 * not draw into the surface inset region set by the parent window.
697 */
698 private SurfaceControl mBoundsLayer;
699 private final SurfaceSession mSurfaceSession = new SurfaceSession();
700 private final Transaction mTransaction = new Transaction();
701
702 @UnsupportedAppUsage
703 boolean mAdded;
704 boolean mAddedTouchMode;
705
706 /**
707 * It usually keeps the latest layout result from {@link IWindow#resized} or
708 * {@link IWindowSession#relayout}.
709 */
710 private final ClientWindowFrames mTmpFrames = new ClientWindowFrames();
711
712 // These are accessed by multiple threads.
713 final Rect mWinFrame; // frame given by window manager.
714 Rect mOverrideInsetsFrame;
715
716 final Rect mPendingBackDropFrame = new Rect();
717
718 boolean mPendingAlwaysConsumeSystemBars;
719 private int mRelayoutSeq;
720 private final Rect mWinFrameInScreen = new Rect();
721 private final InsetsState mTempInsets = new InsetsState();
722 private final InsetsSourceControl[] mTempControls = new InsetsSourceControl[SIZE];
723 private final WindowConfiguration mTempWinConfig = new WindowConfiguration();
724 private float mInvCompatScale = 1f;
725 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
726 = new ViewTreeObserver.InternalInsetsInfo();
727
728 private WindowInsets mLastWindowInsets;
729
730 // Insets types hidden by legacy window flags or system UI flags.
731 private @InsetsType int mTypesHiddenByFlags = 0;
732
733 /** Last applied configuration obtained from resources. */
734 private final Configuration mLastConfigurationFromResources = new Configuration();
735 /** Last configuration reported from WM or via {@link #MSG_UPDATE_CONFIGURATION}. */
736 private final MergedConfiguration mLastReportedMergedConfiguration = new MergedConfiguration();
737 /** Configurations waiting to be applied. */
738 private final MergedConfiguration mPendingMergedConfiguration = new MergedConfiguration();
739
740 boolean mScrollMayChange;
741 @SoftInputModeFlags
742 int mSoftInputMode;
743 @UnsupportedAppUsage
744 WeakReference<View> mLastScrolledFocus;
745 int mScrollY;
746 int mCurScrollY;
747 Scroller mScroller;
748 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
749 private ArrayList<LayoutTransition> mPendingTransitions;
750
751 final ViewConfiguration mViewConfiguration;
752
753 /* Drag/drop */
754 ClipDescription mDragDescription;
755 View mCurrentDragView;
756 View mStartedDragViewForA11y;
757 volatile Object mLocalDragState;
758 final PointF mDragPoint = new PointF();
759 final PointF mLastTouchPoint = new PointF();
760 int mLastTouchSource;
761
762 private boolean mProfileRendering;
763 private Choreographer.FrameCallback mRenderProfiler;
764 private boolean mRenderProfilingEnabled;
765
766 // Variables to track frames per second, enabled via DEBUG_FPS flag
767 private long mFpsStartTime = -1;
768 private long mFpsPrevTime = -1;
769 private int mFpsNumFrames;
770
771 private int mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
772 private PointerIcon mCustomPointerIcon = null;
773
774 /**
775 * see {@link #playSoundEffect(int)}
776 */
777 AudioManager mAudioManager;
778
779 final AccessibilityManager mAccessibilityManager;
780
781 AccessibilityInteractionController mAccessibilityInteractionController;
782
783 final AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager =
784 new AccessibilityInteractionConnectionManager();
785 final HighContrastTextManager mHighContrastTextManager;
786
787 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
788
789 HashSet<View> mTempHashSet;
790
791 private final int mDensity;
792 private final int mNoncompatDensity;
793
794 private boolean mInLayout = false;
795 ArrayList<View> mLayoutRequesters = new ArrayList<View>();
796 boolean mHandlingLayoutInLayoutRequest = false;
797
798 private int mViewLayoutDirectionInitial;
799
800 /** Set to true once doDie() has been called. */
801 private boolean mRemoved;
802
803 private boolean mNeedsRendererSetup;
804
805 private final InputEventCompatProcessor mInputCompatProcessor;
806
807 /**
808 * Consistency verifier for debugging purposes.
809 */
810 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
811 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
812 new InputEventConsistencyVerifier(this, 0) : null;
813
814 private final InsetsController mInsetsController;
815 private final ImeFocusController mImeFocusController;
816
817 private boolean mIsSurfaceOpaque;
818
819 private final BackgroundBlurDrawable.Aggregator mBlurRegionAggregator =
820 new BackgroundBlurDrawable.Aggregator(this);
821
822 /**
823 * @return {@link ImeFocusController} for this instance.
824 */
825 @NonNull
826 public ImeFocusController getImeFocusController() {
827 return mImeFocusController;
828 }
829
830 private final ViewRootRectTracker mGestureExclusionTracker =
831 new ViewRootRectTracker(v -> v.getSystemGestureExclusionRects());
832 private final ViewRootRectTracker mKeepClearRectsTracker =
833 new ViewRootRectTracker(v -> v.collectPreferKeepClearRects());
834 private final ViewRootRectTracker mUnrestrictedKeepClearRectsTracker =
835 new ViewRootRectTracker(v -> v.collectUnrestrictedPreferKeepClearRects());
836 private boolean mHasPendingKeepClearAreaChange;
837
838 private IAccessibilityEmbeddedConnection mAccessibilityEmbeddedConnection;
839
840 static final class SystemUiVisibilityInfo {
841 int globalVisibility;
842 int localValue;
843 int localChanges;
844 }
845
846 private final HandwritingInitiator mHandwritingInitiator;
847
848 /**
849 * Used by InputMethodManager.
850 * @hide
851 */
852 @NonNull
853 public HandwritingInitiator getHandwritingInitiator() {
854 return mHandwritingInitiator;
855 }
856
857 private final SurfaceSyncer mSurfaceSyncer = new SurfaceSyncer();
858 private int mSyncId = UNSET_SYNC_ID;
859 private SurfaceSyncer.SyncBufferCallback mSyncBufferCallback;
860 private int mNumSyncsInProgress = 0;
861
862 private HashSet<ScrollCaptureCallback> mRootScrollCaptureCallbacks;
863
864 private long mScrollCaptureRequestTimeout = SCROLL_CAPTURE_REQUEST_TIMEOUT_MILLIS;
865
866 /**
867 * Increment this value when the surface has been replaced.
868 */
869 private int mSurfaceSequenceId = 0;
870
871 private boolean mRelayoutRequested;
872
873 private int mLastTransformHint = Integer.MIN_VALUE;
874
875 /**
876 * A temporary object used so relayoutWindow can return the latest SyncSeqId
877 * system. The SyncSeqId system was designed to work without synchronous relayout
878 * window, and actually synchronous relayout window presents a problem. We could have
879 * a sequence like this:
880 * 1. We send MSG_RESIZED to the client with a new syncSeqId to begin a new sync
881 * 2. Due to scheduling the client executes performTraversals before calling MSG_RESIZED
882 * 3. Coincidentally for some random reason it also calls relayout
883 * 4. It observes the new state from relayout, and so the next frame will contain the state
884 * However it hasn't received the seqId yet, and so under the designed operation of
885 * seqId flowing through MSG_RESIZED, the next frame wouldn't be synced. Since it
886 * contains our target sync state, we need to sync it! This problem won't come up once
887 * we get rid of synchronous relayout, until then, we use this bundle to channel the
888 * integer back over relayout.
889 */
890 private Bundle mRelayoutBundle = new Bundle();
891
892 private static volatile boolean sAnrReported = false;
893 static BLASTBufferQueue.TransactionHangCallback sTransactionHangCallback =
894 new BLASTBufferQueue.TransactionHangCallback() {
895 @Override
896 public void onTransactionHang(boolean isGPUHang) {
897 if (isGPUHang && !sAnrReported) {
898 sAnrReported = true;
899 try {
900 ActivityManager.getService().appNotResponding(
901 "Buffer processing hung up due to stuck fence. Indicates GPU hang");
902 } catch (RemoteException e) {
903 // We asked the system to crash us, but the system
904 // already crashed. Unfortunately things may be
905 // out of control.
906 }
907 } else {
908 // TODO: Do something with this later. For now we just ANR
909 // in dequeue buffer later like we always have.
910 }
911 }
912 };
913
914 private String mTag = TAG;
915
916 public ViewRootImpl(Context context, Display display) {
917 this(context, display, WindowManagerGlobal.getWindowSession(), new WindowLayout());
918 }
919
920 public ViewRootImpl(@UiContext Context context, Display display, IWindowSession session,
921 WindowLayout windowLayout) {
922 mContext = context;
923 mWindowSession = session;
924 mWindowLayout = windowLayout;
925 mDisplay = display;
926 mBasePackageName = context.getBasePackageName();
927 mThread = Thread.currentThread();
928 mLocation = new WindowLeaked(null);
929 mLocation.fillInStackTrace();
930 mWidth = -1;
931 mHeight = -1;
932 mDirty = new Rect();
933 mWinFrame = new Rect();
934 mWindow = new W(this);
935 mLeashToken = new Binder();
936 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
937 mViewVisibility = View.GONE;
938 mTransparentRegion = new Region();
939 mPreviousTransparentRegion = new Region();
940 mFirst = true; // true for the first time the view is added
941 mPerformContentCapture = true; // also true for the first time the view is added
942 mAdded = false;
943 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this,
944 context);
945 mCompatibleVisibilityInfo = new SystemUiVisibilityInfo();
946 mAccessibilityManager = AccessibilityManager.getInstance(context);
947 mHighContrastTextManager = new HighContrastTextManager();
948 mViewConfiguration = ViewConfiguration.get(context);
949 mDensity = context.getResources().getDisplayMetrics().densityDpi;
950 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
951 mFallbackEventHandler = new PhoneFallbackEventHandler(context);
952 // TODO(b/222696368): remove getSfInstance usage and use vsyncId for transactions
953 mChoreographer = Choreographer.getInstance();
954 mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
955 mInsetsController = new InsetsController(new ViewRootInsetsControllerHost(this));
956 mHandwritingInitiator = new HandwritingInitiator(mViewConfiguration,
957 mContext.getSystemService(InputMethodManager.class));
958
959 String processorOverrideName = context.getResources().getString(
960 R.string.config_inputEventCompatProcessorOverrideClassName);
961 if (processorOverrideName.isEmpty()) {
962 // No compatibility processor override, using default.
963 mInputCompatProcessor = new InputEventCompatProcessor(context);
964 } else {
965 InputEventCompatProcessor compatProcessor = null;
966 try {
967 final Class<? extends InputEventCompatProcessor> klass =
968 (Class<? extends InputEventCompatProcessor>) Class.forName(
969 processorOverrideName);
970 compatProcessor = klass.getConstructor(Context.class).newInstance(context);
971 } catch (Exception e) {
972 Log.e(TAG, "Unable to create the InputEventCompatProcessor. ", e);
973 } finally {
974 mInputCompatProcessor = compatProcessor;
975 }
976 }
977
978 if (!sCompatibilityDone) {
979 sAlwaysAssignFocus = mTargetSdkVersion < Build.VERSION_CODES.P;
980
981 sCompatibilityDone = true;
982 }
983
984 loadSystemProperties();
985 mImeFocusController = new ImeFocusController(this);
986 AudioManager audioManager = mContext.getSystemService(AudioManager.class);
987 mFastScrollSoundEffectsEnabled = audioManager.areNavigationRepeatSoundEffectsEnabled();
988
989 mScrollCaptureRequestTimeout = SCROLL_CAPTURE_REQUEST_TIMEOUT_MILLIS;
990 mOnBackInvokedDispatcher = new WindowOnBackInvokedDispatcher(
991 context.getApplicationInfo().isOnBackInvokedCallbackEnabled());
992 }
993
994 public static void addFirstDrawHandler(Runnable callback) {
995 synchronized (sFirstDrawHandlers) {
996 if (!sFirstDrawComplete) {
997 sFirstDrawHandlers.add(callback);
998 }
999 }
1000 }
1001
1002 /** Add static config callback to be notified about global config changes. */
1003 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1004 public static void addConfigCallback(ConfigChangedCallback callback) {
1005 synchronized (sConfigCallbacks) {
1006 sConfigCallbacks.add(callback);
1007 }
1008 }
1009
1010 /** Remove a static config callback. */
1011 public static void removeConfigCallback(ConfigChangedCallback callback) {
1012 synchronized (sConfigCallbacks) {
1013 sConfigCallbacks.remove(callback);
1014 }
1015 }
1016
1017 /**
1018 * Add activity config callback to be notified about override config changes and camera
1019 * compat control state updates.
1020 */
1021 public void setActivityConfigCallback(ActivityConfigCallback callback) {
1022 mActivityConfigCallback = callback;
1023 }
1024
1025 public void setOnContentApplyWindowInsetsListener(OnContentApplyWindowInsetsListener listener) {
1026 mAttachInfo.mContentOnApplyWindowInsetsListener = listener;
1027
1028 // System windows will be fitted on first traversal, so no reason to request additional
1029 // (possibly getting executed after the first traversal).
1030 if (!mFirst) {
1031 requestFitSystemWindows();
1032 }
1033 }
1034
1035 public void addWindowCallbacks(WindowCallbacks callback) {
1036 mWindowCallbacks.add(callback);
1037 }
1038
1039 public void removeWindowCallbacks(WindowCallbacks callback) {
1040 mWindowCallbacks.remove(callback);
1041 }
1042
1043 public void reportDrawFinish() {
1044 if (mWindowDrawCountDown != null) {
1045 mWindowDrawCountDown.countDown();
1046 }
1047 }
1048
1049 // FIXME for perf testing only
1050 private boolean mProfile = false;
1051
1052 /**
1053 * Call this to profile the next traversal call.
1054 * FIXME for perf testing only. Remove eventually
1055 */
1056 public void profile() {
1057 mProfile = true;
1058 }
1059
1060 /**
1061 * Indicates whether we are in touch mode. Calling this method triggers an IPC
1062 * call and should be avoided whenever possible.
1063 *
1064 * @return True, if the device is in touch mode, false otherwise.
1065 *
1066 * @hide
1067 */
1068 static boolean isInTouchMode() {
1069 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
1070 if (windowSession != null) {
1071 try {
1072 return windowSession.getInTouchMode();
1073 } catch (RemoteException e) {
1074 }
1075 }
1076 return false;
1077 }
1078
1079 /**
1080 * Notifies us that our child has been rebuilt, following
1081 * a window preservation operation. In these cases we
1082 * keep the same DecorView, but the activity controlling it
1083 * is a different instance, and we need to update our
1084 * callbacks.
1085 *
1086 * @hide
1087 */
1088 public void notifyChildRebuilt() {
1089 if (mView instanceof RootViewSurfaceTaker) {
1090 if (mSurfaceHolderCallback != null) {
1091 mSurfaceHolder.removeCallback(mSurfaceHolderCallback);
1092 }
1093
1094 mSurfaceHolderCallback =
1095 ((RootViewSurfaceTaker)mView).willYouTakeTheSurface();
1096
1097 if (mSurfaceHolderCallback != null) {
1098 mSurfaceHolder = new TakenSurfaceHolder();
1099 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
1100 mSurfaceHolder.addCallback(mSurfaceHolderCallback);
1101 } else {
1102 mSurfaceHolder = null;
1103 }
1104
1105 mInputQueueCallback =
1106 ((RootViewSurfaceTaker)mView).willYouTakeTheInputQueue();
1107 if (mInputQueueCallback != null) {
1108 mInputQueueCallback.onInputQueueCreated(mInputQueue);
1109 }
1110 }
1111
1112 // Update the last resource config in case the resource configuration was changed while
1113 // activity relaunched.
1114 updateLastConfigurationFromResources(getConfiguration());
1115 }
1116
1117 private Configuration getConfiguration() {
1118 return mContext.getResources().getConfiguration();
1119 }
1120
1121 private WindowConfiguration getCompatWindowConfiguration() {
1122 final WindowConfiguration winConfig = getConfiguration().windowConfiguration;
1123 if (mInvCompatScale == 1f) {
1124 return winConfig;
1125 }
1126 mTempWinConfig.setTo(winConfig);
1127 mTempWinConfig.scale(mInvCompatScale);
1128 return mTempWinConfig;
1129 }
1130
1131 /**
1132 * We have one child
1133 */
1134 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
1135 setView(view, attrs, panelParentView, UserHandle.myUserId());
1136 }
1137
1138 /**
1139 * We have one child
1140 */
1141 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
1142 int userId) {
1143 synchronized (this) {
1144 if (mView == null) {
1145 mView = view;
1146
1147 mDisplayInstallOrientation = mDisplay.getInstallOrientation();
1148 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
1149 mFallbackEventHandler.setView(view);
1150 mWindowAttributes.copyFrom(attrs);
1151 if (mWindowAttributes.packageName == null) {
1152 mWindowAttributes.packageName = mBasePackageName;
1153 }
1154 mWindowAttributes.privateFlags |=
1155 WindowManager.LayoutParams.PRIVATE_FLAG_USE_BLAST;
1156
1157 attrs = mWindowAttributes;
1158 setTag();
1159
1160 if (DEBUG_KEEP_SCREEN_ON && (mClientWindowLayoutFlags
1161 & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0
1162 && (attrs.flags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) == 0) {
1163 Slog.d(mTag, "setView: FLAG_KEEP_SCREEN_ON changed from true to false!");
1164 }
1165 // Keep track of the actual window flags supplied by the client.
1166 mClientWindowLayoutFlags = attrs.flags;
1167
1168 setAccessibilityFocus(null, null);
1169
1170 if (view instanceof RootViewSurfaceTaker) {
1171 mSurfaceHolderCallback =
1172 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
1173 if (mSurfaceHolderCallback != null) {
1174 mSurfaceHolder = new TakenSurfaceHolder();
1175 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
1176 mSurfaceHolder.addCallback(mSurfaceHolderCallback);
1177 }
1178 }
1179
1180 // Compute surface insets required to draw at specified Z value.
1181 // TODO: Use real shadow insets for a constant max Z.
1182 if (!attrs.hasManualSurfaceInsets) {
1183 attrs.setSurfaceInsets(view, false /*manual*/, true /*preservePrevious*/);
1184 }
1185
1186 CompatibilityInfo compatibilityInfo =
1187 mDisplay.getDisplayAdjustments().getCompatibilityInfo();
1188 mTranslator = compatibilityInfo.getTranslator();
1189
1190 // If the application owns the surface, don't enable hardware acceleration
1191 if (mSurfaceHolder == null) {
1192 // While this is supposed to enable only, it can effectively disable
1193 // the acceleration too.
1194 enableHardwareAcceleration(attrs);
1195 final boolean useMTRenderer = MT_RENDERER_AVAILABLE
1196 && mAttachInfo.mThreadedRenderer != null;
1197 if (mUseMTRenderer != useMTRenderer) {
1198 // Shouldn't be resizing, as it's done only in window setup,
1199 // but end just in case.
1200 endDragResizing();
1201 mUseMTRenderer = useMTRenderer;
1202 }
1203 }
1204
1205 boolean restore = false;
1206 if (mTranslator != null) {
1207 mSurface.setCompatibilityTranslator(mTranslator);
1208 restore = true;
1209 attrs.backup();
1210 mTranslator.translateWindowLayout(attrs);
1211 }
1212 if (DEBUG_LAYOUT) Log.d(mTag, "WindowLayout in setView:" + attrs);
1213
1214 if (!compatibilityInfo.supportsScreen()) {
1215 attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1216 mLastInCompatMode = true;
1217 }
1218
1219 mSoftInputMode = attrs.softInputMode;
1220 mWindowAttributesChanged = true;
1221 mAttachInfo.mRootView = view;
1222 mAttachInfo.mScalingRequired = mTranslator != null;
1223 mAttachInfo.mApplicationScale =
1224 mTranslator == null ? 1.0f : mTranslator.applicationScale;
1225 if (panelParentView != null) {
1226 mAttachInfo.mPanelParentWindowToken
1227 = panelParentView.getApplicationWindowToken();
1228 }
1229 mAdded = true;
1230 int res; /* = WindowManagerImpl.ADD_OKAY; */
1231
1232 // Schedule the first layout -before- adding to the window
1233 // manager, to make sure we do the relayout before receiving
1234 // any other events from the system.
1235 requestLayout();
1236 InputChannel inputChannel = null;
1237 if ((mWindowAttributes.inputFeatures
1238 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
1239 inputChannel = new InputChannel();
1240 }
1241 mForceDecorViewVisibility = (mWindowAttributes.privateFlags
1242 & PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY) != 0;
1243
1244 if (mView instanceof RootViewSurfaceTaker) {
1245 PendingInsetsController pendingInsetsController =
1246 ((RootViewSurfaceTaker) mView).providePendingInsetsController();
1247 if (pendingInsetsController != null) {
1248 pendingInsetsController.replayAndAttach(mInsetsController);
1249 }
1250 }
1251
1252 try {
1253 mOrigWindowType = mWindowAttributes.type;
1254 mAttachInfo.mRecomputeGlobalAttributes = true;
1255 collectViewAttributes();
1256 adjustLayoutParamsForCompatibility(mWindowAttributes);
1257 controlInsetsForCompatibility(mWindowAttributes);
1258
1259 Rect attachedFrame = new Rect();
1260 final float[] compatScale = { 1f };
1261 res = mWindowSession.addToDisplayAsUser(mWindow, mWindowAttributes,
1262 getHostVisibility(), mDisplay.getDisplayId(), userId,
1263 mInsetsController.getRequestedVisibilities(), inputChannel, mTempInsets,
1264 mTempControls, attachedFrame, compatScale);
1265 if (!attachedFrame.isValid()) {
1266 attachedFrame = null;
1267 }
1268 if (mTranslator != null) {
1269 mTranslator.translateInsetsStateInScreenToAppWindow(mTempInsets);
1270 mTranslator.translateSourceControlsInScreenToAppWindow(mTempControls);
1271 mTranslator.translateRectInScreenToAppWindow(attachedFrame);
1272 }
1273 mTmpFrames.attachedFrame = attachedFrame;
1274 mTmpFrames.compatScale = compatScale[0];
1275 mInvCompatScale = 1f / compatScale[0];
1276 } catch (RemoteException e) {
1277 mAdded = false;
1278 mView = null;
1279 mAttachInfo.mRootView = null;
1280 mFallbackEventHandler.setView(null);
1281 unscheduleTraversals();
1282 setAccessibilityFocus(null, null);
1283 throw new RuntimeException("Adding window failed", e);
1284 } finally {
1285 if (restore) {
1286 attrs.restore();
1287 }
1288 }
1289
1290 mAttachInfo.mAlwaysConsumeSystemBars =
1291 (res & WindowManagerGlobal.ADD_FLAG_ALWAYS_CONSUME_SYSTEM_BARS) != 0;
1292 mPendingAlwaysConsumeSystemBars = mAttachInfo.mAlwaysConsumeSystemBars;
1293 mInsetsController.onStateChanged(mTempInsets);
1294 mInsetsController.onControlsChanged(mTempControls);
1295 final InsetsState state = mInsetsController.getState();
1296 final Rect displayCutoutSafe = mTempRect;
1297 state.getDisplayCutoutSafe(displayCutoutSafe);
1298 final WindowConfiguration winConfig = getCompatWindowConfiguration();
1299 mWindowLayout.computeFrames(mWindowAttributes, state,
1300 displayCutoutSafe, winConfig.getBounds(), winConfig.getWindowingMode(),
1301 UNSPECIFIED_LENGTH, UNSPECIFIED_LENGTH,
1302 mInsetsController.getRequestedVisibilities(), 1f /* compactScale */,
1303 mTmpFrames);
1304 setFrame(mTmpFrames.frame);
1305 registerBackCallbackOnWindow();
1306 if (!WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
1307 // For apps requesting legacy back behavior, we add a compat callback that
1308 // dispatches {@link KeyEvent#KEYCODE_BACK} to their root views.
1309 // This way from system point of view, these apps are providing custom
1310 // {@link OnBackInvokedCallback}s, and will not play system back animations
1311 // for them.
1312 registerCompatOnBackInvokedCallback();
1313 }
1314 if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);
1315 if (res < WindowManagerGlobal.ADD_OKAY) {
1316 mAttachInfo.mRootView = null;
1317 mAdded = false;
1318 mFallbackEventHandler.setView(null);
1319 unscheduleTraversals();
1320 setAccessibilityFocus(null, null);
1321 switch (res) {
1322 case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
1323 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
1324 throw new WindowManager.BadTokenException(
1325 "Unable to add window -- token " + attrs.token
1326 + " is not valid; is your activity running?");
1327 case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
1328 throw new WindowManager.BadTokenException(
1329 "Unable to add window -- token " + attrs.token
1330 + " is not for an application");
1331 case WindowManagerGlobal.ADD_APP_EXITING:
1332 throw new WindowManager.BadTokenException(
1333 "Unable to add window -- app for token " + attrs.token
1334 + " is exiting");
1335 case WindowManagerGlobal.ADD_DUPLICATE_ADD:
1336 throw new WindowManager.BadTokenException(
1337 "Unable to add window -- window " + mWindow
1338 + " has already been added");
1339 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
1340 // Silently ignore -- we would have just removed it
1341 // right away, anyway.
1342 return;
1343 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
1344 throw new WindowManager.BadTokenException("Unable to add window "
1345 + mWindow + " -- another window of type "
1346 + mWindowAttributes.type + " already exists");
1347 case WindowManagerGlobal.ADD_PERMISSION_DENIED:
1348 throw new WindowManager.BadTokenException("Unable to add window "
1349 + mWindow + " -- permission denied for window type "
1350 + mWindowAttributes.type);
1351 case WindowManagerGlobal.ADD_INVALID_DISPLAY:
1352 throw new WindowManager.InvalidDisplayException("Unable to add window "
1353 + mWindow + " -- the specified display can not be found");
1354 case WindowManagerGlobal.ADD_INVALID_TYPE:
1355 throw new WindowManager.InvalidDisplayException("Unable to add window "
1356 + mWindow + " -- the specified window type "
1357 + mWindowAttributes.type + " is not valid");
1358 case WindowManagerGlobal.ADD_INVALID_USER:
1359 throw new WindowManager.BadTokenException("Unable to add Window "
1360 + mWindow + " -- requested userId is not valid");
1361 }
1362 throw new RuntimeException(
1363 "Unable to add window -- unknown error code " + res);
1364 }
1365
1366 registerListeners();
1367 // We should update mAttachInfo.mDisplayState after registerDisplayListener
1368 // because displayState might be changed before registerDisplayListener.
1369 mAttachInfo.mDisplayState = mDisplay.getState();
1370 if ((res & WindowManagerGlobal.ADD_FLAG_USE_BLAST) != 0) {
1371 mUseBLASTAdapter = true;
1372 }
1373
1374 if (view instanceof RootViewSurfaceTaker) {
1375 mInputQueueCallback =
1376 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
1377 }
1378 if (inputChannel != null) {
1379 if (mInputQueueCallback != null) {
1380 mInputQueue = new InputQueue();
1381 mInputQueueCallback.onInputQueueCreated(mInputQueue);
1382 }
1383 mInputEventReceiver = new WindowInputEventReceiver(inputChannel,
1384 Looper.myLooper());
1385
1386 if (ENABLE_INPUT_LATENCY_TRACKING && mAttachInfo.mThreadedRenderer != null) {
1387 InputMetricsListener listener = new InputMetricsListener();
1388 mHardwareRendererObserver = new HardwareRendererObserver(
1389 listener, listener.data, mHandler, true /*waitForPresentTime*/);
1390 mAttachInfo.mThreadedRenderer.addObserver(mHardwareRendererObserver);
1391 }
1392 }
1393
1394 view.assignParent(this);
1395 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
1396 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
1397
1398 if (mAccessibilityManager.isEnabled()) {
1399 mAccessibilityInteractionConnectionManager.ensureConnection();
1400 }
1401
1402 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
1403 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
1404 }
1405
1406 // Set up the input pipeline.
1407 CharSequence counterSuffix = attrs.getTitle();
1408 mSyntheticInputStage = new SyntheticInputStage();
1409 InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
1410 InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
1411 "aq:native-post-ime:" + counterSuffix);
1412 InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
1413 InputStage imeStage = new ImeInputStage(earlyPostImeStage,
1414 "aq:ime:" + counterSuffix);
1415 InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
1416 InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
1417 "aq:native-pre-ime:" + counterSuffix);
1418
1419 mFirstInputStage = nativePreImeStage;
1420 mFirstPostImeInputStage = earlyPostImeStage;
1421 mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
1422
1423 if (!mRemoved || !mAppVisible) {
1424 AnimationHandler.requestAnimatorsEnabled(mAppVisible, this);
1425 } else if (LOCAL_LOGV) {
1426 Log.v(mTag, "setView() enabling visibility when removed");
1427 }
1428 }
1429 }
1430 }
1431
1432 /**
1433 * Register any kind of listeners if setView was success.
1434 */
1435 private void registerListeners() {
1436 mAccessibilityManager.addAccessibilityStateChangeListener(
1437 mAccessibilityInteractionConnectionManager, mHandler);
1438 mAccessibilityManager.addHighTextContrastStateChangeListener(
1439 mHighContrastTextManager, mHandler);
1440 mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
1441 }
1442
1443 /**
1444 * Unregister all listeners while detachedFromWindow.
1445 */
1446 private void unregisterListeners() {
1447 mAccessibilityManager.removeAccessibilityStateChangeListener(
1448 mAccessibilityInteractionConnectionManager);
1449 mAccessibilityManager.removeHighTextContrastStateChangeListener(
1450 mHighContrastTextManager);
1451 mDisplayManager.unregisterDisplayListener(mDisplayListener);
1452 }
1453
1454 private void setTag() {
1455 final String[] split = mWindowAttributes.getTitle().toString().split("\\.");
1456 if (split.length > 0) {
1457 mTag = "VRI[" + split[split.length - 1] + "]";
1458 }
1459 }
1460
1461 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1462 public int getWindowFlags() {
1463 return mWindowAttributes.flags;
1464 }
1465
1466 public int getDisplayId() {
1467 return mDisplay.getDisplayId();
1468 }
1469
1470 public CharSequence getTitle() {
1471 return mWindowAttributes.getTitle();
1472 }
1473
1474 /**
1475 * @return the width of the root view. Note that this will return {@code -1} until the first
1476 * layout traversal, when the width is set.
1477 *
1478 * @hide
1479 */
1480 public int getWidth() {
1481 return mWidth;
1482 }
1483
1484 /**
1485 * @return the height of the root view. Note that this will return {@code -1} until the first
1486 * layout traversal, when the height is set.
1487 *
1488 * @hide
1489 */
1490 public int getHeight() {
1491 return mHeight;
1492 }
1493
1494 /**
1495 * Destroys hardware rendering resources for this ViewRootImpl
1496 *
1497 * May be called on any thread
1498 */
1499 @AnyThread
1500 void destroyHardwareResources() {
1501 final ThreadedRenderer renderer = mAttachInfo.mThreadedRenderer;
1502 if (renderer != null) {
1503 // This is called by WindowManagerGlobal which may or may not be on the right thread
1504 if (Looper.myLooper() != mAttachInfo.mHandler.getLooper()) {
1505 mAttachInfo.mHandler.postAtFrontOfQueue(this::destroyHardwareResources);
1506 return;
1507 }
1508 renderer.destroyHardwareResources(mView);
1509 renderer.destroy();
1510 }
1511 }
1512
1513 /**
1514 * Does nothing; Here only because of @UnsupportedAppUsage
1515 */
1516 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R,
1517 publicAlternatives = "Use {@link android.webkit.WebView} instead")
1518 public void detachFunctor(long functor) { }
1519
1520 /**
1521 * Does nothing; Here only because of @UnsupportedAppUsage
1522 */
1523 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R,
1524 publicAlternatives = "Use {@link android.webkit.WebView} instead")
1525 public static void invokeFunctor(long functor, boolean waitForCompletion) { }
1526
1527 /**
1528 * @param animator animator to register with the hardware renderer
1529 */
1530 public void registerAnimatingRenderNode(RenderNode animator) {
1531 if (mAttachInfo.mThreadedRenderer != null) {
1532 mAttachInfo.mThreadedRenderer.registerAnimatingRenderNode(animator);
1533 } else {
1534 if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
1535 mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
1536 }
1537 mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
1538 }
1539 }
1540
1541 /**
1542 * @param animator animator to register with the hardware renderer
1543 */
1544 public void registerVectorDrawableAnimator(NativeVectorDrawableAnimator animator) {
1545 if (mAttachInfo.mThreadedRenderer != null) {
1546 mAttachInfo.mThreadedRenderer.registerVectorDrawableAnimator(animator);
1547 }
1548 }
1549
1550 /**
1551 * Registers a callback to be executed when the next frame is being drawn on RenderThread. This
1552 * callback will be executed on a RenderThread worker thread, and only used for the next frame
1553 * and thus it will only fire once.
1554 *
1555 * @param callback The callback to register.
1556 */
1557 public void registerRtFrameCallback(@NonNull FrameDrawingCallback callback) {
1558 if (mAttachInfo.mThreadedRenderer != null) {
1559 mAttachInfo.mThreadedRenderer.registerRtFrameCallback(new FrameDrawingCallback() {
1560 @Override
1561 public void onFrameDraw(long frame) {
1562 }
1563
1564 @Override
1565 public HardwareRenderer.FrameCommitCallback onFrameDraw(int syncResult,
1566 long frame) {
1567 try {
1568 return callback.onFrameDraw(syncResult, frame);
1569 } catch (Exception e) {
1570 Log.e(TAG, "Exception while executing onFrameDraw", e);
1571 }
1572 return null;
1573 }
1574 });
1575 }
1576 }
1577
1578 @UnsupportedAppUsage
1579 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
1580 mAttachInfo.mHardwareAccelerated = false;
1581 mAttachInfo.mHardwareAccelerationRequested = false;
1582
1583 // Don't enable hardware acceleration when the application is in compatibility mode
1584 if (mTranslator != null) return;
1585
1586 // Try to enable hardware acceleration if requested
1587 final boolean hardwareAccelerated =
1588 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
1589
1590 if (hardwareAccelerated) {
1591 // Persistent processes (including the system) should not do
1592 // accelerated rendering on low-end devices. In that case,
1593 // sRendererDisabled will be set. In addition, the system process
1594 // itself should never do accelerated rendering. In that case, both
1595 // sRendererDisabled and sSystemRendererDisabled are set. When
1596 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
1597 // can be used by code on the system process to escape that and enable
1598 // HW accelerated drawing. (This is basically for the lock screen.)
1599
1600 final boolean forceHwAccelerated = (attrs.privateFlags &
1601 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
1602
1603 if (ThreadedRenderer.sRendererEnabled || forceHwAccelerated) {
1604 if (mAttachInfo.mThreadedRenderer != null) {
1605 mAttachInfo.mThreadedRenderer.destroy();
1606 }
1607
1608 final Rect insets = attrs.surfaceInsets;
1609 final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
1610 || insets.top != 0 || insets.bottom != 0;
1611 final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
1612 mAttachInfo.mThreadedRenderer = ThreadedRenderer.create(mContext, translucent,
1613 attrs.getTitle().toString());
1614 updateColorModeIfNeeded(attrs.getColorMode());
1615 updateForceDarkMode();
1616 if (mAttachInfo.mThreadedRenderer != null) {
1617 mAttachInfo.mHardwareAccelerated =
1618 mAttachInfo.mHardwareAccelerationRequested = true;
1619 if (mHardwareRendererObserver != null) {
1620 mAttachInfo.mThreadedRenderer.addObserver(mHardwareRendererObserver);
1621 }
1622 mAttachInfo.mThreadedRenderer.setSurfaceControl(mSurfaceControl);
1623 mAttachInfo.mThreadedRenderer.setBlastBufferQueue(mBlastBufferQueue);
1624 }
1625 }
1626 }
1627 }
1628
1629 private int getNightMode() {
1630 return getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1631 }
1632
1633 private void updateForceDarkMode() {
1634 if (mAttachInfo.mThreadedRenderer == null) return;
1635
1636 boolean useAutoDark = getNightMode() == Configuration.UI_MODE_NIGHT_YES;
1637
1638 if (useAutoDark) {
1639 boolean forceDarkAllowedDefault =
1640 SystemProperties.getBoolean(ThreadedRenderer.DEBUG_FORCE_DARK, false);
1641 TypedArray a = mContext.obtainStyledAttributes(R.styleable.Theme);
1642 useAutoDark = a.getBoolean(R.styleable.Theme_isLightTheme, true)
1643 && a.getBoolean(R.styleable.Theme_forceDarkAllowed, forceDarkAllowedDefault);
1644 a.recycle();
1645 }
1646
1647 if (mAttachInfo.mThreadedRenderer.setForceDark(useAutoDark)) {
1648 // TODO: Don't require regenerating all display lists to apply this setting
1649 invalidateWorld(mView);
1650 }
1651 }
1652
1653 @UnsupportedAppUsage
1654 public View getView() {
1655 return mView;
1656 }
1657
1658 final WindowLeaked getLocation() {
1659 return mLocation;
1660 }
1661
1662 @VisibleForTesting
1663 public void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
1664 synchronized (this) {
1665 final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
1666 final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
1667 final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
1668 final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
1669 final int oldSoftInputMode = mWindowAttributes.softInputMode;
1670 final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
1671
1672 if (DEBUG_KEEP_SCREEN_ON && (mClientWindowLayoutFlags
1673 & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0
1674 && (attrs.flags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) == 0) {
1675 Slog.d(mTag, "setLayoutParams: FLAG_KEEP_SCREEN_ON from true to false!");
1676 }
1677
1678 // Keep track of the actual window flags supplied by the client.
1679 mClientWindowLayoutFlags = attrs.flags;
1680
1681 // Preserve compatible window flag if exists.
1682 final int compatibleWindowFlag = mWindowAttributes.privateFlags
1683 & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1684
1685 // Preserve system UI visibility.
1686 final int systemUiVisibility = mWindowAttributes.systemUiVisibility;
1687 final int subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
1688
1689 // Preserve appearance and behavior.
1690 final int appearance = mWindowAttributes.insetsFlags.appearance;
1691 final int behavior = mWindowAttributes.insetsFlags.behavior;
1692 final int appearanceAndBehaviorPrivateFlags = mWindowAttributes.privateFlags
1693 & (PRIVATE_FLAG_APPEARANCE_CONTROLLED | PRIVATE_FLAG_BEHAVIOR_CONTROLLED);
1694
1695 final int changes = mWindowAttributes.copyFrom(attrs);
1696 if ((changes & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
1697 // Recompute system ui visibility.
1698 mAttachInfo.mRecomputeGlobalAttributes = true;
1699 }
1700 if ((changes & WindowManager.LayoutParams.LAYOUT_CHANGED) != 0) {
1701 // Request to update light center.
1702 mAttachInfo.mNeedsUpdateLightCenter = true;
1703 }
1704 if (mWindowAttributes.packageName == null) {
1705 mWindowAttributes.packageName = mBasePackageName;
1706 }
1707
1708 // Restore preserved flags.
1709 mWindowAttributes.systemUiVisibility = systemUiVisibility;
1710 mWindowAttributes.subtreeSystemUiVisibility = subtreeSystemUiVisibility;
1711 mWindowAttributes.insetsFlags.appearance = appearance;
1712 mWindowAttributes.insetsFlags.behavior = behavior;
1713 mWindowAttributes.privateFlags |= compatibleWindowFlag
1714 | appearanceAndBehaviorPrivateFlags
1715 | WindowManager.LayoutParams.PRIVATE_FLAG_USE_BLAST;
1716
1717 if (mWindowAttributes.preservePreviousSurfaceInsets) {
1718 // Restore old surface insets.
1719 mWindowAttributes.surfaceInsets.set(
1720 oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
1721 mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
1722 } else if (mWindowAttributes.surfaceInsets.left != oldInsetLeft
1723 || mWindowAttributes.surfaceInsets.top != oldInsetTop
1724 || mWindowAttributes.surfaceInsets.right != oldInsetRight
1725 || mWindowAttributes.surfaceInsets.bottom != oldInsetBottom) {
1726 mNeedsRendererSetup = true;
1727 }
1728
1729 applyKeepScreenOnFlag(mWindowAttributes);
1730
1731 if (newView) {
1732 mSoftInputMode = attrs.softInputMode;
1733 requestLayout();
1734 }
1735
1736 // Don't lose the mode we last auto-computed.
1737 if ((attrs.softInputMode & SOFT_INPUT_MASK_ADJUST)
1738 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1739 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
1740 & ~SOFT_INPUT_MASK_ADJUST) | (oldSoftInputMode & SOFT_INPUT_MASK_ADJUST);
1741 }
1742
1743 if (mWindowAttributes.softInputMode != oldSoftInputMode) {
1744 requestFitSystemWindows();
1745 }
1746
1747 mWindowAttributesChanged = true;
1748 scheduleTraversals();
1749 }
1750 }
1751
1752 void handleAppVisibility(boolean visible) {
1753 if (mAppVisible != visible) {
1754 final boolean previousVisible = getHostVisibility() == View.VISIBLE;
1755 mAppVisible = visible;
1756 final boolean currentVisible = getHostVisibility() == View.VISIBLE;
1757 // Root view only cares about whether it is visible or not.
1758 if (previousVisible != currentVisible) {
1759 mAppVisibilityChanged = true;
1760 scheduleTraversals();
1761 }
1762 if (!mAppVisible) {
1763 WindowManagerGlobal.trimForeground();
1764 }
1765 // Only enable if the window is not already removed (via earlier call to doDie())
1766 if (!mRemoved || !mAppVisible) {
1767 AnimationHandler.requestAnimatorsEnabled(mAppVisible, this);
1768 } else if (LOCAL_LOGV) {
1769 Log.v(mTag, "handleAppVisibility() enabling visibility when removed");
1770 }
1771 }
1772 }
1773
1774 void handleGetNewSurface() {
1775 mNewSurfaceNeeded = true;
1776 mFullRedrawNeeded = true;
1777 scheduleTraversals();
1778 }
1779
1780 /** Handles messages {@link #MSG_RESIZED} and {@link #MSG_RESIZED_REPORT}. */
1781 private void handleResized(int msg, SomeArgs args) {
1782 if (!mAdded) {
1783 return;
1784 }
1785
1786 final ClientWindowFrames frames = (ClientWindowFrames) args.arg1;
1787 final MergedConfiguration mergedConfiguration = (MergedConfiguration) args.arg2;
1788 final boolean forceNextWindowRelayout = args.argi1 != 0;
1789 final int displayId = args.argi3;
1790 final int resizeMode = args.argi5;
1791
1792 final Rect frame = frames.frame;
1793 final Rect displayFrame = frames.displayFrame;
1794 final Rect attachedFrame = frames.attachedFrame;
1795 if (mTranslator != null) {
1796 mTranslator.translateRectInScreenToAppWindow(frame);
1797 mTranslator.translateRectInScreenToAppWindow(displayFrame);
1798 mTranslator.translateRectInScreenToAppWindow(attachedFrame);
1799 }
1800 final float compatScale = frames.compatScale;
1801 final boolean frameChanged = !mWinFrame.equals(frame);
1802 final boolean configChanged = !mLastReportedMergedConfiguration.equals(mergedConfiguration);
1803 final boolean attachedFrameChanged = LOCAL_LAYOUT
1804 && !Objects.equals(mTmpFrames.attachedFrame, attachedFrame);
1805 final boolean displayChanged = mDisplay.getDisplayId() != displayId;
1806 final boolean resizeModeChanged = mResizeMode != resizeMode;
1807 final boolean compatScaleChanged = mTmpFrames.compatScale != compatScale;
1808 if (msg == MSG_RESIZED && !frameChanged && !configChanged && !attachedFrameChanged
1809 && !displayChanged && !resizeModeChanged && !forceNextWindowRelayout
1810 && !compatScaleChanged) {
1811 return;
1812 }
1813
1814 mPendingDragResizing = resizeMode != RESIZE_MODE_INVALID;
1815 mResizeMode = resizeMode;
1816 mTmpFrames.compatScale = compatScale;
1817 mInvCompatScale = 1f / compatScale;
1818
1819 if (configChanged) {
1820 // If configuration changed - notify about that and, maybe, about move to display.
1821 performConfigurationChange(mergedConfiguration, false /* force */,
1822 displayChanged ? displayId : INVALID_DISPLAY /* same display */);
1823 } else if (displayChanged) {
1824 // Moved to display without config change - report last applied one.
1825 onMovedToDisplay(displayId, mLastConfigurationFromResources);
1826 }
1827
1828 setFrame(frame);
1829 mTmpFrames.displayFrame.set(displayFrame);
1830 if (mTmpFrames.attachedFrame != null && attachedFrame != null) {
1831 mTmpFrames.attachedFrame.set(attachedFrame);
1832 }
1833
1834 if (mDragResizing && mUseMTRenderer) {
1835 boolean fullscreen = frame.equals(mPendingBackDropFrame);
1836 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
1837 mWindowCallbacks.get(i).onWindowSizeIsChanging(mPendingBackDropFrame, fullscreen,
1838 mAttachInfo.mVisibleInsets, mAttachInfo.mStableInsets);
1839 }
1840 }
1841
1842 mForceNextWindowRelayout |= forceNextWindowRelayout;
1843 mPendingAlwaysConsumeSystemBars = args.argi2 != 0;
1844 mSyncSeqId = args.argi4 > mSyncSeqId ? args.argi4 : mSyncSeqId;
1845
1846 if (msg == MSG_RESIZED_REPORT) {
1847 reportNextDraw("resized");
1848 }
1849
1850 if (mView != null && (frameChanged || configChanged)) {
1851 forceLayout(mView);
1852 }
1853 requestLayout();
1854 }
1855
1856 private final DisplayListener mDisplayListener = new DisplayListener() {
1857 @Override
1858 public void onDisplayChanged(int displayId) {
1859 if (mView != null && mDisplay.getDisplayId() == displayId) {
1860 final int oldDisplayState = mAttachInfo.mDisplayState;
1861 final int newDisplayState = mDisplay.getState();
1862 if (oldDisplayState != newDisplayState) {
1863 mAttachInfo.mDisplayState = newDisplayState;
1864 pokeDrawLockIfNeeded();
1865 if (oldDisplayState != Display.STATE_UNKNOWN) {
1866 final int oldScreenState = toViewScreenState(oldDisplayState);
1867 final int newScreenState = toViewScreenState(newDisplayState);
1868 if (oldScreenState != newScreenState) {
1869 mView.dispatchScreenStateChanged(newScreenState);
1870 }
1871 if (oldDisplayState == Display.STATE_OFF) {
1872 // Draw was suppressed so we need to for it to happen here.
1873 mFullRedrawNeeded = true;
1874 scheduleTraversals();
1875 }
1876 }
1877 }
1878 }
1879 }
1880
1881 @Override
1882 public void onDisplayRemoved(int displayId) {
1883 }
1884
1885 @Override
1886 public void onDisplayAdded(int displayId) {
1887 }
1888
1889 private int toViewScreenState(int displayState) {
1890 return displayState == Display.STATE_OFF ?
1891 View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
1892 }
1893 };
1894
1895 /**
1896 * Notify about move to a different display.
1897 * @param displayId The id of the display where this view root is moved to.
1898 * @param config Configuration of the resources on new display after move.
1899 *
1900 * @hide
1901 */
1902 public void onMovedToDisplay(int displayId, Configuration config) {
1903 if (mDisplay.getDisplayId() == displayId) {
1904 return;
1905 }
1906
1907 // Get new instance of display based on current display adjustments. It may be updated later
1908 // if moving between the displays also involved a configuration change.
1909 updateInternalDisplay(displayId, mView.getResources());
1910 mImeFocusController.onMovedToDisplay();
1911 mAttachInfo.mDisplayState = mDisplay.getState();
1912 mDisplayInstallOrientation = mDisplay.getInstallOrientation();
1913 // Internal state updated, now notify the view hierarchy.
1914 mView.dispatchMovedToDisplay(mDisplay, config);
1915 }
1916
1917 /**
1918 * Updates {@link #mDisplay} to the display object corresponding to {@param displayId}.
1919 * Uses DEFAULT_DISPLAY if there isn't a display object in the system corresponding
1920 * to {@param displayId}.
1921 */
1922 private void updateInternalDisplay(int displayId, Resources resources) {
1923 final Display preferredDisplay =
1924 ResourcesManager.getInstance().getAdjustedDisplay(displayId, resources);
1925 if (preferredDisplay == null) {
1926 // Fallback to use default display.
1927 Slog.w(TAG, "Cannot get desired display with Id: " + displayId);
1928 mDisplay = ResourcesManager.getInstance()
1929 .getAdjustedDisplay(DEFAULT_DISPLAY, resources);
1930 } else {
1931 mDisplay = preferredDisplay;
1932 }
1933 mContext.updateDisplay(mDisplay.getDisplayId());
1934 }
1935
1936 void pokeDrawLockIfNeeded() {
1937 if (!Display.isDozeState(mAttachInfo.mDisplayState)) {
1938 // Only need to acquire wake lock for DOZE state.
1939 return;
1940 }
1941 if (mWindowAttributes.type != WindowManager.LayoutParams.TYPE_BASE_APPLICATION) {
1942 // Non-activity windows should be responsible to hold wake lock by themself, because
1943 // usually they are system windows.
1944 return;
1945 }
1946 if (mAdded && mTraversalScheduled && mAttachInfo.mHasWindowFocus) {
1947 try {
1948 mWindowSession.pokeDrawLock(mWindow);
1949 } catch (RemoteException ex) {
1950 // System server died, oh well.
1951 }
1952 }
1953 }
1954
1955 @Override
1956 public void requestFitSystemWindows() {
1957 checkThread();
1958 mApplyInsetsRequested = true;
1959 scheduleTraversals();
1960 }
1961
1962 void notifyInsetsChanged() {
1963 mApplyInsetsRequested = true;
1964 requestLayout();
1965
1966 // See comment for View.sForceLayoutWhenInsetsChanged
1967 if (View.sForceLayoutWhenInsetsChanged && mView != null
1968 && (mWindowAttributes.softInputMode & SOFT_INPUT_MASK_ADJUST)
1969 == SOFT_INPUT_ADJUST_RESIZE) {
1970 forceLayout(mView);
1971 }
1972
1973 // If this changes during traversal, no need to schedule another one as it will dispatch it
1974 // during the current traversal.
1975 if (!mIsInTraversal) {
1976 scheduleTraversals();
1977 }
1978 }
1979
1980 @Override
1981 public void requestLayout() {
1982 if (!mHandlingLayoutInLayoutRequest) {
1983 checkThread();
1984 mLayoutRequested = true;
1985 scheduleTraversals();
1986 }
1987 }
1988
1989 @Override
1990 public boolean isLayoutRequested() {
1991 return mLayoutRequested;
1992 }
1993
1994 @Override
1995 public void onDescendantInvalidated(@NonNull View child, @NonNull View descendant) {
1996 // TODO: Re-enable after camera is fixed or consider targetSdk checking this
1997 // checkThread();
1998 if ((descendant.mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) {
1999 mIsAnimating = true;
2000 }
2001 invalidate();
2002 }
2003
2004 @UnsupportedAppUsage
2005 void invalidate() {
2006 mDirty.set(0, 0, mWidth, mHeight);
2007 if (!mWillDrawSoon) {
2008 scheduleTraversals();
2009 }
2010 }
2011
2012 void invalidateWorld(View view) {
2013 view.invalidate();
2014 if (view instanceof ViewGroup) {
2015 ViewGroup parent = (ViewGroup) view;
2016 for (int i = 0; i < parent.getChildCount(); i++) {
2017 invalidateWorld(parent.getChildAt(i));
2018 }
2019 }
2020 }
2021
2022 @Override
2023 public void invalidateChild(View child, Rect dirty) {
2024 invalidateChildInParent(null, dirty);
2025 }
2026
2027 @Override
2028 public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
2029 checkThread();
2030 if (DEBUG_DRAW) Log.v(mTag, "Invalidate child: " + dirty);
2031
2032 if (dirty == null) {
2033 invalidate();
2034 return null;
2035 } else if (dirty.isEmpty() && !mIsAnimating) {
2036 return null;
2037 }
2038
2039 if (mCurScrollY != 0 || mTranslator != null) {
2040 mTempRect.set(dirty);
2041 dirty = mTempRect;
2042 if (mCurScrollY != 0) {
2043 dirty.offset(0, -mCurScrollY);
2044 }
2045 if (mTranslator != null) {
2046 mTranslator.translateRectInAppWindowToScreen(dirty);
2047 }
2048 if (mAttachInfo.mScalingRequired) {
2049 dirty.inset(-1, -1);
2050 }
2051 }
2052
2053 invalidateRectOnScreen(dirty);
2054
2055 return null;
2056 }
2057
2058 private void invalidateRectOnScreen(Rect dirty) {
2059 final Rect localDirty = mDirty;
2060
2061 // Add the new dirty rect to the current one
2062 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
2063 // Intersect with the bounds of the window to skip
2064 // updates that lie outside of the visible region
2065 final float appScale = mAttachInfo.mApplicationScale;
2066 final boolean intersected = localDirty.intersect(0, 0,
2067 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2068 if (!intersected) {
2069 localDirty.setEmpty();
2070 }
2071 if (!mWillDrawSoon && (intersected || mIsAnimating)) {
2072 scheduleTraversals();
2073 }
2074 }
2075
2076 public void setIsAmbientMode(boolean ambient) {
2077 mIsAmbientMode = ambient;
2078 }
2079
2080 void setWindowStopped(boolean stopped) {
2081 checkThread();
2082 if (mStopped != stopped) {
2083 mStopped = stopped;
2084 final ThreadedRenderer renderer = mAttachInfo.mThreadedRenderer;
2085 if (renderer != null) {
2086 if (DEBUG_DRAW) Log.d(mTag, "WindowStopped on " + getTitle() + " set to " + mStopped);
2087 renderer.setStopped(mStopped);
2088 }
2089 if (!mStopped) {
2090 // Make sure that relayoutWindow will be called to get valid surface because
2091 // the previous surface may have been released.
2092 mAppVisibilityChanged = true;
2093 scheduleTraversals();
2094 } else {
2095 if (renderer != null) {
2096 renderer.destroyHardwareResources(mView);
2097 }
2098
2099 if (mSurface.isValid()) {
2100 if (mSurfaceHolder != null) {
2101 notifyHolderSurfaceDestroyed();
2102 }
2103 notifySurfaceDestroyed();
2104 }
2105 destroySurface();
2106 }
2107 }
2108 }
2109
2110
2111 /** Register callbacks to be notified when the ViewRootImpl surface changes. */
2112 public interface SurfaceChangedCallback {
2113 void surfaceCreated(Transaction t);
2114 void surfaceReplaced(Transaction t);
2115 void surfaceDestroyed();
2116 default void surfaceSyncStarted() {};
2117 }
2118
2119 private final ArrayList<SurfaceChangedCallback> mSurfaceChangedCallbacks = new ArrayList<>();
2120 public void addSurfaceChangedCallback(SurfaceChangedCallback c) {
2121 mSurfaceChangedCallbacks.add(c);
2122 }
2123
2124 public void removeSurfaceChangedCallback(SurfaceChangedCallback c) {
2125 mSurfaceChangedCallbacks.remove(c);
2126 }
2127
2128 private void notifySurfaceCreated() {
2129 for (int i = 0; i < mSurfaceChangedCallbacks.size(); i++) {
2130 mSurfaceChangedCallbacks.get(i).surfaceCreated(mSurfaceChangedTransaction);
2131 }
2132 }
2133
2134 /**
2135 * Notify listeners when the ViewRootImpl surface has been replaced. This callback will not be
2136 * called if a new surface is created, only if the valid surface has been replaced with another
2137 * valid surface.
2138 */
2139 private void notifySurfaceReplaced() {
2140 for (int i = 0; i < mSurfaceChangedCallbacks.size(); i++) {
2141 mSurfaceChangedCallbacks.get(i).surfaceReplaced(mSurfaceChangedTransaction);
2142 }
2143 }
2144
2145 private void notifySurfaceDestroyed() {
2146 for (int i = 0; i < mSurfaceChangedCallbacks.size(); i++) {
2147 mSurfaceChangedCallbacks.get(i).surfaceDestroyed();
2148 }
2149 }
2150
2151 private void notifySurfaceSyncStarted() {
2152 for (int i = 0; i < mSurfaceChangedCallbacks.size(); i++) {
2153 mSurfaceChangedCallbacks.get(i).surfaceSyncStarted();
2154 }
2155 }
2156
2157 /**
2158 * @return child layer with the same bounds as its parent {@code mSurface} and cropped to the
2159 * surface insets. If the layer does not exist, it is created.
2160 *
2161 * <p>Parenting to this layer will ensure that its children are cropped by the view's surface
2162 * insets.
2163 */
2164 public SurfaceControl getBoundsLayer() {
2165 if (mBoundsLayer == null) {
2166 mBoundsLayer = new SurfaceControl.Builder(mSurfaceSession)
2167 .setContainerLayer()
2168 .setName("Bounds for - " + getTitle().toString())
2169 .setParent(getSurfaceControl())
2170 .setCallsite("ViewRootImpl.getBoundsLayer")
2171 .build();
2172 setBoundsLayerCrop(mTransaction);
2173 mTransaction.show(mBoundsLayer).apply();
2174 }
2175 return mBoundsLayer;
2176 }
2177
2178 void updateBlastSurfaceIfNeeded() {
2179 if (!mSurfaceControl.isValid()) {
2180 return;
2181 }
2182
2183 if (mBlastBufferQueue != null && mBlastBufferQueue.isSameSurfaceControl(mSurfaceControl)) {
2184 mBlastBufferQueue.update(mSurfaceControl,
2185 mSurfaceSize.x, mSurfaceSize.y,
2186 mWindowAttributes.format);
2187 return;
2188 }
2189
2190 // If the SurfaceControl has been updated, destroy and recreate the BBQ to reset the BQ and
2191 // BBQ states.
2192 if (mBlastBufferQueue != null) {
2193 mBlastBufferQueue.destroy();
2194 }
2195 mBlastBufferQueue = new BLASTBufferQueue(mTag, mSurfaceControl,
2196 mSurfaceSize.x, mSurfaceSize.y, mWindowAttributes.format);
2197 mBlastBufferQueue.setTransactionHangCallback(sTransactionHangCallback);
2198 Surface blastSurface = mBlastBufferQueue.createSurface();
2199 // Only call transferFrom if the surface has changed to prevent inc the generation ID and
2200 // causing EGL resources to be recreated.
2201 mSurface.transferFrom(blastSurface);
2202 }
2203
2204 private void setBoundsLayerCrop(Transaction t) {
2205 // Adjust of insets and update the bounds layer so child surfaces do not draw into
2206 // the surface inset region.
2207 mTempRect.set(0, 0, mSurfaceSize.x, mSurfaceSize.y);
2208 mTempRect.inset(mWindowAttributes.surfaceInsets.left,
2209 mWindowAttributes.surfaceInsets.top,
2210 mWindowAttributes.surfaceInsets.right, mWindowAttributes.surfaceInsets.bottom);
2211 t.setWindowCrop(mBoundsLayer, mTempRect);
2212 }
2213
2214 /**
2215 * Called after window layout to update the bounds surface. If the surface insets have changed
2216 * or the surface has resized, update the bounds surface.
2217 */
2218 private boolean updateBoundsLayer(SurfaceControl.Transaction t) {
2219 if (mBoundsLayer != null) {
2220 setBoundsLayerCrop(t);
2221 return true;
2222 }
2223 return false;
2224 }
2225
2226 private void prepareSurfaces() {
2227 final SurfaceControl.Transaction t = mTransaction;
2228 final SurfaceControl sc = getSurfaceControl();
2229 if (!sc.isValid()) return;
2230
2231 if (updateBoundsLayer(t)) {
2232 mergeWithNextTransaction(t, mSurface.getNextFrameNumber());
2233 }
2234 }
2235
2236 private void destroySurface() {
2237 if (mBoundsLayer != null) {
2238 mBoundsLayer.release();
2239 mBoundsLayer = null;
2240 }
2241 mSurface.release();
2242 mSurfaceControl.release();
2243
2244 if (mBlastBufferQueue != null) {
2245 mBlastBufferQueue.destroy();
2246 mBlastBufferQueue = null;
2247 }
2248
2249 if (mAttachInfo.mThreadedRenderer != null) {
2250 mAttachInfo.mThreadedRenderer.setSurfaceControl(null);
2251 mAttachInfo.mThreadedRenderer.setBlastBufferQueue(null);
2252 }
2253 }
2254
2255 /**
2256 * Block the input events during an Activity Transition. The KEYCODE_BACK event is allowed
2257 * through to allow quick reversal of the Activity Transition.
2258 *
2259 * @param paused true to pause, false to resume.
2260 */
2261 public void setPausedForTransition(boolean paused) {
2262 mPausedForTransition = paused;
2263 }
2264
2265 @Override
2266 public ViewParent getParent() {
2267 return null;
2268 }
2269
2270 @Override
2271 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
2272 if (child != mView) {
2273 throw new RuntimeException("child is not mine, honest!");
2274 }
2275 // Note: don't apply scroll offset, because we want to know its
2276 // visibility in the virtual canvas being given to the view hierarchy.
2277 return r.intersect(0, 0, mWidth, mHeight);
2278 }
2279
2280 @Override
2281 public void bringChildToFront(View child) {
2282 }
2283
2284 int getHostVisibility() {
2285 return mView != null && (mAppVisible || mForceDecorViewVisibility)
2286 ? mView.getVisibility() : View.GONE;
2287 }
2288
2289 /**
2290 * Add LayoutTransition to the list of transitions to be started in the next traversal.
2291 * This list will be cleared after the transitions on the list are start()'ed. These
2292 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
2293 * happens during the layout phase of traversal, which we want to complete before any of the
2294 * animations are started (because those animations may side-effect properties that layout
2295 * depends upon, like the bounding rectangles of the affected views). So we add the transition
2296 * to the list and it is started just prior to starting the drawing phase of traversal.
2297 *
2298 * @param transition The LayoutTransition to be started on the next traversal.
2299 *
2300 * @hide
2301 */
2302 public void requestTransitionStart(LayoutTransition transition) {
2303 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
2304 if (mPendingTransitions == null) {
2305 mPendingTransitions = new ArrayList<LayoutTransition>();
2306 }
2307 mPendingTransitions.add(transition);
2308 }
2309 }
2310
2311 /**
2312 * Notifies the HardwareRenderer that a new frame will be coming soon.
2313 * Currently only {@link ThreadedRenderer} cares about this, and uses
2314 * this knowledge to adjust the scheduling of off-thread animations
2315 */
2316 void notifyRendererOfFramePending() {
2317 if (mAttachInfo.mThreadedRenderer != null) {
2318 mAttachInfo.mThreadedRenderer.notifyFramePending();
2319 }
2320 }
2321
2322 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2323 void scheduleTraversals() {
2324 if (!mTraversalScheduled) {
2325 mTraversalScheduled = true;
2326 mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
2327 mChoreographer.postCallback(
2328 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
2329 notifyRendererOfFramePending();
2330 pokeDrawLockIfNeeded();
2331 }
2332 }
2333
2334 void unscheduleTraversals() {
2335 if (mTraversalScheduled) {
2336 mTraversalScheduled = false;
2337 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
2338 mChoreographer.removeCallbacks(
2339 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
2340 }
2341 }
2342
2343 void doTraversal() {
2344 if (mTraversalScheduled) {
2345 mTraversalScheduled = false;
2346 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
2347
2348 if (mProfile) {
2349 Debug.startMethodTracing("ViewAncestor");
2350 }
2351
2352 performTraversals();
2353
2354 if (mProfile) {
2355 Debug.stopMethodTracing();
2356 mProfile = false;
2357 }
2358 }
2359 }
2360
2361 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
2362 // Update window's global keep screen on flag: if a view has requested
2363 // that the screen be kept on, then it is always set; otherwise, it is
2364 // set to whatever the client last requested for the global state.
2365 if (mAttachInfo.mKeepScreenOn) {
2366 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
2367 } else {
2368 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
2369 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2370 }
2371 }
2372
2373 private boolean collectViewAttributes() {
2374 if (mAttachInfo.mRecomputeGlobalAttributes) {
2375 //Log.i(mTag, "Computing view hierarchy attributes!");
2376 mAttachInfo.mRecomputeGlobalAttributes = false;
2377 boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
2378 mAttachInfo.mKeepScreenOn = false;
2379 mAttachInfo.mSystemUiVisibility = 0;
2380 mAttachInfo.mHasSystemUiListeners = false;
2381 mView.dispatchCollectViewAttributes(mAttachInfo, 0);
2382 mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
2383 WindowManager.LayoutParams params = mWindowAttributes;
2384 mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
2385 mCompatibleVisibilityInfo.globalVisibility =
2386 (mCompatibleVisibilityInfo.globalVisibility & ~View.SYSTEM_UI_FLAG_LOW_PROFILE)
2387 | (mAttachInfo.mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
2388 dispatchDispatchSystemUiVisibilityChanged(mCompatibleVisibilityInfo);
2389 if (mAttachInfo.mKeepScreenOn != oldScreenOn
2390 || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
2391 || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
2392 applyKeepScreenOnFlag(params);
2393 params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
2394 params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
2395 mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
2396 return true;
2397 }
2398 }
2399 return false;
2400 }
2401
2402 private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
2403 int vis = 0;
2404 // Translucent decor window flags imply stable system ui visibility.
2405 if ((params.flags & FLAG_TRANSLUCENT_STATUS) != 0) {
2406 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2407 }
2408 if ((params.flags & FLAG_TRANSLUCENT_NAVIGATION) != 0) {
2409 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
2410 }
2411 return vis;
2412 }
2413
2414 /**
2415 * Update the compatible system UI visibility for dispatching it to the legacy app.
2416 *
2417 * @param type Indicates which type of the insets source we are handling.
2418 * @param visible True if the insets source is visible.
2419 * @param hasControl True if we can control the insets source.
2420 */
2421 void updateCompatSysUiVisibility(@InternalInsetsType int type, boolean visible,
2422 boolean hasControl) {
2423 @InsetsType final int publicType = InsetsState.toPublicType(type);
2424 if (publicType != Type.statusBars() && publicType != Type.navigationBars()) {
2425 return;
2426 }
2427 final SystemUiVisibilityInfo info = mCompatibleVisibilityInfo;
2428 final int systemUiFlag = publicType == Type.statusBars()
2429 ? View.SYSTEM_UI_FLAG_FULLSCREEN
2430 : View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2431 if (visible) {
2432 info.globalVisibility &= ~systemUiFlag;
2433 if (hasControl && (mAttachInfo.mSystemUiVisibility & systemUiFlag) != 0) {
2434 // The local system UI visibility can only be cleared while we have the control.
2435 info.localChanges |= systemUiFlag;
2436 }
2437 } else {
2438 info.globalVisibility |= systemUiFlag;
2439 info.localChanges &= ~systemUiFlag;
2440 }
2441 dispatchDispatchSystemUiVisibilityChanged(info);
2442 }
2443
2444 /**
2445 * If the system is forcing showing any system bar, the legacy low profile flag should be
2446 * cleared for compatibility.
2447 *
2448 * @param showTypes {@link InsetsType types} shown by the system.
2449 * @param fromIme {@code true} if the invocation is from IME.
2450 */
2451 private void clearLowProfileModeIfNeeded(@InsetsType int showTypes, boolean fromIme) {
2452 final SystemUiVisibilityInfo info = mCompatibleVisibilityInfo;
2453 if ((showTypes & Type.systemBars()) != 0 && !fromIme
2454 && (info.globalVisibility & SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
2455 info.globalVisibility &= ~SYSTEM_UI_FLAG_LOW_PROFILE;
2456 info.localChanges |= SYSTEM_UI_FLAG_LOW_PROFILE;
2457 dispatchDispatchSystemUiVisibilityChanged(info);
2458 }
2459 }
2460
2461 private void dispatchDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
2462 if (mDispatchedSystemUiVisibility != args.globalVisibility) {
2463 mHandler.removeMessages(MSG_DISPATCH_SYSTEM_UI_VISIBILITY);
2464 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
2465 }
2466 }
2467
2468 private void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
2469 if (mView == null) return;
2470 if (args.localChanges != 0) {
2471 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
2472 args.localChanges = 0;
2473 }
2474
2475 final int visibility = args.globalVisibility & View.SYSTEM_UI_CLEARABLE_FLAGS;
2476 if (mDispatchedSystemUiVisibility != visibility) {
2477 mDispatchedSystemUiVisibility = visibility;
2478 mView.dispatchSystemUiVisibilityChanged(visibility);
2479 }
2480 }
2481
2482 @VisibleForTesting
2483 public static void adjustLayoutParamsForCompatibility(WindowManager.LayoutParams inOutParams) {
2484 final int sysUiVis = inOutParams.systemUiVisibility | inOutParams.subtreeSystemUiVisibility;
2485 final int flags = inOutParams.flags;
2486 final int type = inOutParams.type;
2487 final int adjust = inOutParams.softInputMode & SOFT_INPUT_MASK_ADJUST;
2488
2489 if ((inOutParams.privateFlags & PRIVATE_FLAG_APPEARANCE_CONTROLLED) == 0) {
2490 inOutParams.insetsFlags.appearance = 0;
2491 if ((sysUiVis & SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
2492 inOutParams.insetsFlags.appearance |= APPEARANCE_LOW_PROFILE_BARS;
2493 }
2494 if ((sysUiVis & SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0) {
2495 inOutParams.insetsFlags.appearance |= APPEARANCE_LIGHT_STATUS_BARS;
2496 }
2497 if ((sysUiVis & SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) != 0) {
2498 inOutParams.insetsFlags.appearance |= APPEARANCE_LIGHT_NAVIGATION_BARS;
2499 }
2500 }
2501
2502 if ((inOutParams.privateFlags & PRIVATE_FLAG_BEHAVIOR_CONTROLLED) == 0) {
2503 if ((sysUiVis & SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0
2504 || (flags & FLAG_FULLSCREEN) != 0) {
2505 inOutParams.insetsFlags.behavior = BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE;
2506 } else {
2507 inOutParams.insetsFlags.behavior = BEHAVIOR_DEFAULT;
2508 }
2509 }
2510
2511 inOutParams.privateFlags &= ~PRIVATE_FLAG_INSET_PARENT_FRAME_BY_IME;
2512
2513 if ((inOutParams.privateFlags & PRIVATE_FLAG_FIT_INSETS_CONTROLLED) != 0) {
2514 return;
2515 }
2516
2517 int types = inOutParams.getFitInsetsTypes();
2518 boolean ignoreVis = inOutParams.isFitInsetsIgnoringVisibility();
2519
2520 if (((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0
2521 || (flags & FLAG_LAYOUT_IN_SCREEN) != 0)
2522 || (flags & FLAG_TRANSLUCENT_STATUS) != 0) {
2523 types &= ~Type.statusBars();
2524 }
2525 if ((sysUiVis & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2526 || (flags & FLAG_TRANSLUCENT_NAVIGATION) != 0) {
2527 types &= ~Type.systemBars();
2528 }
2529 if (type == TYPE_TOAST || type == TYPE_SYSTEM_ALERT) {
2530 ignoreVis = true;
2531 } else if ((types & Type.systemBars()) == Type.systemBars()) {
2532 if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
2533 types |= Type.ime();
2534 } else {
2535 inOutParams.privateFlags |= PRIVATE_FLAG_INSET_PARENT_FRAME_BY_IME;
2536 }
2537 }
2538 inOutParams.setFitInsetsTypes(types);
2539 inOutParams.setFitInsetsIgnoringVisibility(ignoreVis);
2540
2541 // The fitting of insets are not really controlled by the clients, so we remove the flag.
2542 inOutParams.privateFlags &= ~PRIVATE_FLAG_FIT_INSETS_CONTROLLED;
2543 }
2544
2545 private void controlInsetsForCompatibility(WindowManager.LayoutParams params) {
2546 final int sysUiVis = params.systemUiVisibility | params.subtreeSystemUiVisibility;
2547 final int flags = params.flags;
2548 final boolean matchParent = params.width == MATCH_PARENT && params.height == MATCH_PARENT;
2549 final boolean nonAttachedAppWindow = params.type >= FIRST_APPLICATION_WINDOW
2550 && params.type <= LAST_APPLICATION_WINDOW;
2551 final boolean statusWasHiddenByFlags = (mTypesHiddenByFlags & Type.statusBars()) != 0;
2552 final boolean statusIsHiddenByFlags = (sysUiVis & SYSTEM_UI_FLAG_FULLSCREEN) != 0
2553 || ((flags & FLAG_FULLSCREEN) != 0 && matchParent && nonAttachedAppWindow);
2554 final boolean navWasHiddenByFlags = (mTypesHiddenByFlags & Type.navigationBars()) != 0;
2555 final boolean navIsHiddenByFlags = (sysUiVis & SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
2556
2557 @InsetsType int typesToHide = 0;
2558 @InsetsType int typesToShow = 0;
2559 if (statusIsHiddenByFlags && !statusWasHiddenByFlags) {
2560 typesToHide |= Type.statusBars();
2561 } else if (!statusIsHiddenByFlags && statusWasHiddenByFlags) {
2562 typesToShow |= Type.statusBars();
2563 }
2564 if (navIsHiddenByFlags && !navWasHiddenByFlags) {
2565 typesToHide |= Type.navigationBars();
2566 } else if (!navIsHiddenByFlags && navWasHiddenByFlags) {
2567 typesToShow |= Type.navigationBars();
2568 }
2569 if (typesToHide != 0) {
2570 getInsetsController().hide(typesToHide);
2571 }
2572 if (typesToShow != 0) {
2573 getInsetsController().show(typesToShow);
2574 }
2575 mTypesHiddenByFlags |= typesToHide;
2576 mTypesHiddenByFlags &= ~typesToShow;
2577 }
2578
2579 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
2580 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight,
2581 boolean forRootSizeOnly) {
2582 int childWidthMeasureSpec;
2583 int childHeightMeasureSpec;
2584 boolean windowSizeMayChange = false;
2585
2586 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(mTag,
2587 "Measuring " + host + " in display " + desiredWindowWidth
2588 + "x" + desiredWindowHeight + "...");
2589
2590 boolean goodMeasure = false;
2591 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
2592 // On large screens, we don't want to allow dialogs to just
2593 // stretch to fill the entire width of the screen to display
2594 // one line of text. First try doing the layout at a smaller
2595 // size to see if it will fit.
2596 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
2597 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
2598 int baseSize = 0;
2599 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
2600 baseSize = (int)mTmpValue.getDimension(packageMetrics);
2601 }
2602 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": baseSize=" + baseSize
2603 + ", desiredWindowWidth=" + desiredWindowWidth);
2604 if (baseSize != 0 && desiredWindowWidth > baseSize) {
2605 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width, lp.privateFlags);
2606 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height,
2607 lp.privateFlags);
2608 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
2609 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
2610 + host.getMeasuredWidth() + "," + host.getMeasuredHeight()
2611 + ") from width spec: " + MeasureSpec.toString(childWidthMeasureSpec)
2612 + " and height spec: " + MeasureSpec.toString(childHeightMeasureSpec));
2613 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
2614 goodMeasure = true;
2615 } else {
2616 // Didn't fit in that size... try expanding a bit.
2617 baseSize = (baseSize+desiredWindowWidth)/2;
2618 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": next baseSize="
2619 + baseSize);
2620 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width, lp.privateFlags);
2621 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
2622 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
2623 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
2624 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
2625 if (DEBUG_DIALOG) Log.v(mTag, "Good!");
2626 goodMeasure = true;
2627 }
2628 }
2629 }
2630 }
2631
2632 if (!goodMeasure) {
2633 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width,
2634 lp.privateFlags);
2635 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height,
2636 lp.privateFlags);
2637 if (!forRootSizeOnly || !setMeasuredRootSizeFromSpec(
2638 childWidthMeasureSpec, childHeightMeasureSpec)) {
2639 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
2640 } else {
2641 // We already know how big the window should be before measuring the views.
2642 // We can measure the views before laying out them. This is to avoid unnecessary
2643 // measure.
2644 mViewMeasureDeferred = true;
2645 }
2646 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
2647 windowSizeMayChange = true;
2648 }
2649 }
2650
2651 if (DBG) {
2652 System.out.println("======================================");
2653 System.out.println("performTraversals -- after measure");
2654 host.debug();
2655 }
2656
2657 return windowSizeMayChange;
2658 }
2659
2660 /**
2661 * Sets the measured root size for requesting the window frame.
2662 *
2663 * @param widthMeasureSpec contains the size and the mode of the width.
2664 * @param heightMeasureSpec contains the size and the mode of the height.
2665 * @return {@code true} if we actually set the measured size; {@code false} otherwise.
2666 */
2667 private boolean setMeasuredRootSizeFromSpec(int widthMeasureSpec, int heightMeasureSpec) {
2668 final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
2669 final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
2670 if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
2671 // We don't know the exact size. We need to measure the hierarchy to know that.
2672 return false;
2673 }
2674 mMeasuredWidth = MeasureSpec.getSize(widthMeasureSpec);
2675 mMeasuredHeight = MeasureSpec.getSize(heightMeasureSpec);
2676 return true;
2677 }
2678
2679 /**
2680 * Modifies the input matrix such that it maps view-local coordinates to
2681 * on-screen coordinates.
2682 *
2683 * @param m input matrix to modify
2684 */
2685 void transformMatrixToGlobal(Matrix m) {
2686 m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
2687 }
2688
2689 /**
2690 * Modifies the input matrix such that it maps on-screen coordinates to
2691 * view-local coordinates.
2692 *
2693 * @param m input matrix to modify
2694 */
2695 void transformMatrixToLocal(Matrix m) {
2696 m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
2697 }
2698
2699 /* package */ WindowInsets getWindowInsets(boolean forceConstruct) {
2700 if (mLastWindowInsets == null || forceConstruct) {
2701 final Configuration config = getConfiguration();
2702 mLastWindowInsets = mInsetsController.calculateInsets(
2703 config.isScreenRound(), mAttachInfo.mAlwaysConsumeSystemBars,
2704 mWindowAttributes.type, config.windowConfiguration.getWindowingMode(),
2705 mWindowAttributes.softInputMode, mWindowAttributes.flags,
2706 (mWindowAttributes.systemUiVisibility
2707 | mWindowAttributes.subtreeSystemUiVisibility));
2708
2709 mAttachInfo.mContentInsets.set(mLastWindowInsets.getSystemWindowInsets().toRect());
2710 mAttachInfo.mStableInsets.set(mLastWindowInsets.getStableInsets().toRect());
2711 mAttachInfo.mVisibleInsets.set(mInsetsController.calculateVisibleInsets(
2712 mWindowAttributes.type, config.windowConfiguration.getWindowingMode(),
2713 mWindowAttributes.softInputMode, mWindowAttributes.flags).toRect());
2714 }
2715 return mLastWindowInsets;
2716 }
2717
2718 public void dispatchApplyInsets(View host) {
2719 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "dispatchApplyInsets");
2720 mApplyInsetsRequested = false;
2721 WindowInsets insets = getWindowInsets(true /* forceConstruct */);
2722 if (!shouldDispatchCutout()) {
2723 // Window is either not laid out in cutout or the status bar inset takes care of
2724 // clearing the cutout, so we don't need to dispatch the cutout to the hierarchy.
2725 insets = insets.consumeDisplayCutout();
2726 }
2727 host.dispatchApplyWindowInsets(insets);
2728 mAttachInfo.delayNotifyContentCaptureInsetsEvent(insets.getInsets(Type.all()));
2729 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2730 }
2731
2732 private boolean updateCaptionInsets() {
2733 if (CAPTION_ON_SHELL) {
2734 return false;
2735 }
2736 if (!(mView instanceof DecorView)) return false;
2737 final int captionInsetsHeight = ((DecorView) mView).getCaptionInsetsHeight();
2738 final Rect captionFrame = new Rect();
2739 if (captionInsetsHeight != 0) {
2740 captionFrame.set(mWinFrame.left, mWinFrame.top, mWinFrame.right,
2741 mWinFrame.top + captionInsetsHeight);
2742 }
2743 if (mAttachInfo.mCaptionInsets.equals(captionFrame)) return false;
2744 mAttachInfo.mCaptionInsets.set(captionFrame);
2745 return true;
2746 }
2747
2748 private boolean shouldDispatchCutout() {
2749 return mWindowAttributes.layoutInDisplayCutoutMode
2750 == LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
2751 || mWindowAttributes.layoutInDisplayCutoutMode
2752 == LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
2753 }
2754
2755 @VisibleForTesting
2756 public InsetsController getInsetsController() {
2757 return mInsetsController;
2758 }
2759
2760 private static boolean shouldUseDisplaySize(final WindowManager.LayoutParams lp) {
2761 return lp.type == TYPE_STATUS_BAR_ADDITIONAL
2762 || lp.type == TYPE_INPUT_METHOD
2763 || lp.type == TYPE_VOLUME_OVERLAY;
2764 }
2765
2766 /**
2767 * @return {@code true} if we should reduce unnecessary measure for the window.
2768 * TODO(b/260382739): Apply this to all windows.
2769 */
2770 private static boolean shouldOptimizeMeasure(final WindowManager.LayoutParams lp) {
2771 return lp.type == TYPE_NOTIFICATION_SHADE;
2772 }
2773
2774 private Rect getWindowBoundsInsetSystemBars() {
2775 final Rect bounds = new Rect(
2776 mContext.getResources().getConfiguration().windowConfiguration.getBounds());
2777 bounds.inset(mInsetsController.getState().calculateInsets(
2778 bounds, Type.systemBars(), false /* ignoreVisibility */));
2779 return bounds;
2780 }
2781
2782 int dipToPx(int dip) {
2783 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
2784 return (int) (displayMetrics.density * dip + 0.5f);
2785 }
2786
2787 private void performTraversals() {
2788 mLastPerformTraversalsSkipDrawReason = null;
2789
2790 // cache mView since it is used so much below...
2791 final View host = mView;
2792 if (DBG) {
2793 System.out.println("======================================");
2794 System.out.println("performTraversals");
2795 host.debug();
2796 }
2797
2798 if (host == null || !mAdded) {
2799 mLastPerformTraversalsSkipDrawReason = host == null ? "no_host" : "not_added";
2800 return;
2801 }
2802
2803 mIsInTraversal = true;
2804 mWillDrawSoon = true;
2805 boolean cancelDraw = false;
2806 String cancelReason = null;
2807 boolean isSyncRequest = false;
2808
2809 boolean windowSizeMayChange = false;
2810 WindowManager.LayoutParams lp = mWindowAttributes;
2811
2812 int desiredWindowWidth;
2813 int desiredWindowHeight;
2814
2815 final int viewVisibility = getHostVisibility();
2816 final boolean viewVisibilityChanged = !mFirst
2817 && (mViewVisibility != viewVisibility || mNewSurfaceNeeded
2818 // Also check for possible double visibility update, which will make current
2819 // viewVisibility value equal to mViewVisibility and we may miss it.
2820 || mAppVisibilityChanged);
2821 mAppVisibilityChanged = false;
2822 final boolean viewUserVisibilityChanged = !mFirst &&
2823 ((mViewVisibility == View.VISIBLE) != (viewVisibility == View.VISIBLE));
2824 final boolean shouldOptimizeMeasure = shouldOptimizeMeasure(lp);
2825
2826 WindowManager.LayoutParams params = null;
2827 CompatibilityInfo compatibilityInfo =
2828 mDisplay.getDisplayAdjustments().getCompatibilityInfo();
2829 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
2830 params = lp;
2831 mFullRedrawNeeded = true;
2832 mLayoutRequested = true;
2833 if (mLastInCompatMode) {
2834 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2835 mLastInCompatMode = false;
2836 } else {
2837 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2838 mLastInCompatMode = true;
2839 }
2840 }
2841
2842 Rect frame = mWinFrame;
2843 if (mFirst) {
2844 mFullRedrawNeeded = true;
2845 mLayoutRequested = true;
2846
2847 final Configuration config = getConfiguration();
2848 if (shouldUseDisplaySize(lp)) {
2849 // NOTE -- system code, won't try to do compat mode.
2850 Point size = new Point();
2851 mDisplay.getRealSize(size);
2852 desiredWindowWidth = size.x;
2853 desiredWindowHeight = size.y;
2854 } else if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
2855 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
2856 // For wrap content, we have to remeasure later on anyways. Use size consistent with
2857 // below so we get best use of the measure cache.
2858 final Rect bounds = getWindowBoundsInsetSystemBars();
2859 desiredWindowWidth = bounds.width();
2860 desiredWindowHeight = bounds.height();
2861 } else {
2862 // After addToDisplay, the frame contains the frameHint from window manager, which
2863 // for most windows is going to be the same size as the result of relayoutWindow.
2864 // Using this here allows us to avoid remeasuring after relayoutWindow
2865 desiredWindowWidth = frame.width();
2866 desiredWindowHeight = frame.height();
2867 }
2868
2869 // We used to use the following condition to choose 32 bits drawing caches:
2870 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
2871 // However, windows are now always 32 bits by default, so choose 32 bits
2872 mAttachInfo.mUse32BitDrawingCache = true;
2873 mAttachInfo.mWindowVisibility = viewVisibility;
2874 mAttachInfo.mRecomputeGlobalAttributes = false;
2875 mLastConfigurationFromResources.setTo(config);
2876 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
2877 // Set the layout direction if it has not been set before (inherit is the default)
2878 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
2879 host.setLayoutDirection(config.getLayoutDirection());
2880 }
2881 host.dispatchAttachedToWindow(mAttachInfo, 0);
2882 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
2883 dispatchApplyInsets(host);
2884 } else {
2885 desiredWindowWidth = frame.width();
2886 desiredWindowHeight = frame.height();
2887 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
2888 if (DEBUG_ORIENTATION) Log.v(mTag, "View " + host + " resized to: " + frame);
2889 mFullRedrawNeeded = true;
2890 mLayoutRequested = true;
2891 windowSizeMayChange = true;
2892 }
2893 }
2894
2895 if (viewVisibilityChanged) {
2896 mAttachInfo.mWindowVisibility = viewVisibility;
2897 host.dispatchWindowVisibilityChanged(viewVisibility);
2898 mAttachInfo.mTreeObserver.dispatchOnWindowVisibilityChange(viewVisibility);
2899 if (viewUserVisibilityChanged) {
2900 host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE);
2901 }
2902 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
2903 endDragResizing();
2904 destroyHardwareResources();
2905 }
2906 }
2907
2908 // Non-visible windows can't hold accessibility focus.
2909 if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
2910 host.clearAccessibilityFocus();
2911 }
2912
2913 // Execute enqueued actions on every traversal in case a detached view enqueued an action
2914 getRunQueue().executeActions(mAttachInfo.mHandler);
2915
2916 if (mFirst) {
2917 // make sure touch mode code executes by setting cached value
2918 // to opposite of the added touch mode.
2919 mAttachInfo.mInTouchMode = !mAddedTouchMode;
2920 ensureTouchModeLocally(mAddedTouchMode);
2921 }
2922
2923 boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
2924 if (layoutRequested) {
2925 if (!mFirst) {
2926 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
2927 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
2928 windowSizeMayChange = true;
2929
2930 if (shouldUseDisplaySize(lp)) {
2931 // NOTE -- system code, won't try to do compat mode.
2932 Point size = new Point();
2933 mDisplay.getRealSize(size);
2934 desiredWindowWidth = size.x;
2935 desiredWindowHeight = size.y;
2936 } else {
2937 final Rect bounds = getWindowBoundsInsetSystemBars();
2938 desiredWindowWidth = bounds.width();
2939 desiredWindowHeight = bounds.height();
2940 }
2941 }
2942 }
2943
2944 // Ask host how big it wants to be
2945 windowSizeMayChange |= measureHierarchy(host, lp, mView.getContext().getResources(),
2946 desiredWindowWidth, desiredWindowHeight, shouldOptimizeMeasure);
2947 }
2948
2949 if (collectViewAttributes()) {
2950 params = lp;
2951 }
2952 if (mAttachInfo.mForceReportNewAttributes) {
2953 mAttachInfo.mForceReportNewAttributes = false;
2954 params = lp;
2955 }
2956
2957 if (mFirst || mAttachInfo.mViewVisibilityChanged) {
2958 mAttachInfo.mViewVisibilityChanged = false;
2959 int resizeMode = mSoftInputMode & SOFT_INPUT_MASK_ADJUST;
2960 // If we are in auto resize mode, then we need to determine
2961 // what mode to use now.
2962 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
2963 final int N = mAttachInfo.mScrollContainers.size();
2964 for (int i=0; i<N; i++) {
2965 if (mAttachInfo.mScrollContainers.get(i).isShown()) {
2966 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
2967 }
2968 }
2969 if (resizeMode == 0) {
2970 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
2971 }
2972 if ((lp.softInputMode & SOFT_INPUT_MASK_ADJUST) != resizeMode) {
2973 lp.softInputMode = (lp.softInputMode & ~SOFT_INPUT_MASK_ADJUST) | resizeMode;
2974 params = lp;
2975 }
2976 }
2977 }
2978
2979 if (mApplyInsetsRequested) {
2980 dispatchApplyInsets(host);
2981 if (mLayoutRequested) {
2982 // Short-circuit catching a new layout request here, so
2983 // we don't need to go through two layout passes when things
2984 // change due to fitting system windows, which can happen a lot.
2985 windowSizeMayChange |= measureHierarchy(host, lp,
2986 mView.getContext().getResources(), desiredWindowWidth, desiredWindowHeight,
2987 shouldOptimizeMeasure);
2988 }
2989 }
2990
2991 if (layoutRequested) {
2992 // Clear this now, so that if anything requests a layout in the
2993 // rest of this function we will catch it and re-run a full
2994 // layout pass.
2995 mLayoutRequested = false;
2996 }
2997
2998 boolean windowShouldResize = layoutRequested && windowSizeMayChange
2999 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
3000 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
3001 frame.width() < desiredWindowWidth && frame.width() != mWidth)
3002 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
3003 frame.height() < desiredWindowHeight && frame.height() != mHeight));
3004 windowShouldResize |= mDragResizing && mResizeMode == RESIZE_MODE_FREEFORM;
3005
3006 // If the activity was just relaunched, it might have unfrozen the task bounds (while
3007 // relaunching), so we need to force a call into window manager to pick up the latest
3008 // bounds.
3009 windowShouldResize |= mActivityRelaunched;
3010
3011 // Determine whether to compute insets.
3012 // If there are no inset listeners remaining then we may still need to compute
3013 // insets in case the old insets were non-empty and must be reset.
3014 final boolean computesInternalInsets =
3015 mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners()
3016 || mAttachInfo.mHasNonEmptyGivenInternalInsets;
3017
3018 boolean insetsPending = false;
3019 int relayoutResult = 0;
3020 boolean updatedConfiguration = false;
3021
3022 final int surfaceGenerationId = mSurface.getGenerationId();
3023
3024 final boolean isViewVisible = viewVisibility == View.VISIBLE;
3025 boolean surfaceSizeChanged = false;
3026 boolean surfaceCreated = false;
3027 boolean surfaceDestroyed = false;
3028 // True if surface generation id changes or relayout result is RELAYOUT_RES_SURFACE_CHANGED.
3029 boolean surfaceReplaced = false;
3030
3031 final boolean windowAttributesChanged = mWindowAttributesChanged;
3032 if (windowAttributesChanged) {
3033 mWindowAttributesChanged = false;
3034 params = lp;
3035 }
3036
3037 if (params != null) {
3038 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0
3039 && !PixelFormat.formatHasAlpha(params.format)) {
3040 params.format = PixelFormat.TRANSLUCENT;
3041 }
3042 adjustLayoutParamsForCompatibility(params);
3043 controlInsetsForCompatibility(params);
3044 if (mDispatchedSystemBarAppearance != params.insetsFlags.appearance) {
3045 mDispatchedSystemBarAppearance = params.insetsFlags.appearance;
3046 mView.onSystemBarAppearanceChanged(mDispatchedSystemBarAppearance);
3047 }
3048 }
3049
3050 if (mFirst || windowShouldResize || viewVisibilityChanged || params != null
3051 || mForceNextWindowRelayout) {
3052 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
3053 Trace.traceBegin(Trace.TRACE_TAG_VIEW,
3054 TextUtils.formatSimple("relayoutWindow#"
3055 + "first=%b/resize=%b/vis=%b/params=%b/force=%b",
3056 mFirst, windowShouldResize, viewVisibilityChanged, params != null,
3057 mForceNextWindowRelayout));
3058 }
3059
3060 mForceNextWindowRelayout = false;
3061
3062 // If this window is giving internal insets to the window manager, then we want to first
3063 // make the provided insets unchanged during layout. This avoids it briefly causing
3064 // other windows to resize/move based on the raw frame of the window, waiting until we
3065 // can finish laying out this window and get back to the window manager with the
3066 // ultimately computed insets.
3067 insetsPending = computesInternalInsets;
3068
3069 if (mSurfaceHolder != null) {
3070 mSurfaceHolder.mSurfaceLock.lock();
3071 mDrawingAllowed = true;
3072 }
3073
3074 boolean hwInitialized = false;
3075 boolean dispatchApplyInsets = false;
3076 boolean hadSurface = mSurface.isValid();
3077
3078 try {
3079 if (DEBUG_LAYOUT) {
3080 Log.i(mTag, "host=w:" + host.getMeasuredWidth() + ", h:" +
3081 host.getMeasuredHeight() + ", params=" + params);
3082 }
3083
3084 if (mFirst || viewVisibilityChanged) {
3085 mViewFrameInfo.flags |= FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED;
3086 }
3087 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
3088 cancelDraw = (relayoutResult & RELAYOUT_RES_CANCEL_AND_REDRAW)
3089 == RELAYOUT_RES_CANCEL_AND_REDRAW;
3090 cancelReason = "relayout";
3091 final boolean dragResizing = mPendingDragResizing;
3092 if (mSyncSeqId > mLastSyncSeqId) {
3093 mLastSyncSeqId = mSyncSeqId;
3094 if (DEBUG_BLAST) {
3095 Log.d(mTag, "Relayout called with blastSync");
3096 }
3097 reportNextDraw("relayout");
3098 mSyncBuffer = true;
3099 isSyncRequest = true;
3100 if (!cancelDraw) {
3101 mDrewOnceForSync = false;
3102 }
3103 }
3104
3105 final boolean surfaceControlChanged =
3106 (relayoutResult & RELAYOUT_RES_SURFACE_CHANGED)
3107 == RELAYOUT_RES_SURFACE_CHANGED;
3108
3109 if (mSurfaceControl.isValid()) {
3110 updateOpacity(mWindowAttributes, dragResizing,
3111 surfaceControlChanged /*forceUpdate */);
3112 // No need to updateDisplayDecoration if it's a new SurfaceControl and
3113 // mDisplayDecorationCached is false, since that's the default for a new
3114 // SurfaceControl.
3115 if (surfaceControlChanged && mDisplayDecorationCached) {
3116 updateDisplayDecoration();
3117 }
3118 }
3119
3120 if (DEBUG_LAYOUT) Log.v(mTag, "relayout: frame=" + frame.toShortString()
3121 + " surface=" + mSurface);
3122
3123 // If the pending {@link MergedConfiguration} handed back from
3124 // {@link #relayoutWindow} does not match the one last reported,
3125 // WindowManagerService has reported back a frame from a configuration not yet
3126 // handled by the client. In this case, we need to accept the configuration so we
3127 // do not lay out and draw with the wrong configuration.
3128 if (mRelayoutRequested
3129 && !mPendingMergedConfiguration.equals(mLastReportedMergedConfiguration)) {
3130 if (DEBUG_CONFIGURATION) Log.v(mTag, "Visible with new config: "
3131 + mPendingMergedConfiguration.getMergedConfiguration());
3132 performConfigurationChange(new MergedConfiguration(mPendingMergedConfiguration),
3133 !mFirst, INVALID_DISPLAY /* same display */);
3134 updatedConfiguration = true;
3135 }
3136 final boolean updateSurfaceNeeded = mUpdateSurfaceNeeded;
3137 mUpdateSurfaceNeeded = false;
3138
3139 surfaceSizeChanged = false;
3140 if (!mLastSurfaceSize.equals(mSurfaceSize)) {
3141 surfaceSizeChanged = true;
3142 mLastSurfaceSize.set(mSurfaceSize.x, mSurfaceSize.y);
3143 }
3144 final boolean alwaysConsumeSystemBarsChanged =
3145 mPendingAlwaysConsumeSystemBars != mAttachInfo.mAlwaysConsumeSystemBars;
3146 updateColorModeIfNeeded(lp.getColorMode());
3147 surfaceCreated = !hadSurface && mSurface.isValid();
3148 surfaceDestroyed = hadSurface && !mSurface.isValid();
3149
3150 // When using Blast, the surface generation id may not change when there's a new
3151 // SurfaceControl. In that case, we also check relayout flag
3152 // RELAYOUT_RES_SURFACE_CHANGED since it should indicate that WMS created a new
3153 // SurfaceControl.
3154 surfaceReplaced = (surfaceGenerationId != mSurface.getGenerationId()
3155 || surfaceControlChanged) && mSurface.isValid();
3156 if (surfaceReplaced) {
3157 mSurfaceSequenceId++;
3158 }
3159
3160 if (alwaysConsumeSystemBarsChanged) {
3161 mAttachInfo.mAlwaysConsumeSystemBars = mPendingAlwaysConsumeSystemBars;
3162 dispatchApplyInsets = true;
3163 }
3164 if (updateCaptionInsets()) {
3165 dispatchApplyInsets = true;
3166 }
3167 if (dispatchApplyInsets || mLastSystemUiVisibility !=
3168 mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested) {
3169 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
3170 dispatchApplyInsets(host);
3171 // We applied insets so force contentInsetsChanged to ensure the
3172 // hierarchy is measured below.
3173 dispatchApplyInsets = true;
3174 }
3175
3176 if (surfaceCreated) {
3177 // If we are creating a new surface, then we need to
3178 // completely redraw it.
3179 mFullRedrawNeeded = true;
3180 mPreviousTransparentRegion.setEmpty();
3181
3182 // Only initialize up-front if transparent regions are not
3183 // requested, otherwise defer to see if the entire window
3184 // will be transparent
3185 if (mAttachInfo.mThreadedRenderer != null) {
3186 try {
3187 hwInitialized = mAttachInfo.mThreadedRenderer.initialize(mSurface);
3188 if (hwInitialized && (host.mPrivateFlags
3189 & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) {
3190 // Don't pre-allocate if transparent regions
3191 // are requested as they may not be needed
3192 mAttachInfo.mThreadedRenderer.allocateBuffers();
3193 }
3194 } catch (OutOfResourcesException e) {
3195 handleOutOfResourcesException(e);
3196 mLastPerformTraversalsSkipDrawReason = "oom_initialize_renderer";
3197 return;
3198 }
3199 }
3200 } else if (surfaceDestroyed) {
3201 // If the surface has been removed, then reset the scroll
3202 // positions.
3203 if (mLastScrolledFocus != null) {
3204 mLastScrolledFocus.clear();
3205 }
3206 mScrollY = mCurScrollY = 0;
3207 if (mView instanceof RootViewSurfaceTaker) {
3208 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
3209 }
3210 if (mScroller != null) {
3211 mScroller.abortAnimation();
3212 }
3213 // Our surface is gone
3214 if (isHardwareEnabled()) {
3215 mAttachInfo.mThreadedRenderer.destroy();
3216 }
3217 } else if ((surfaceReplaced || surfaceSizeChanged || updateSurfaceNeeded)
3218 && mSurfaceHolder == null
3219 && mAttachInfo.mThreadedRenderer != null
3220 && mSurface.isValid()) {
3221 mFullRedrawNeeded = true;
3222 try {
3223 // Need to do updateSurface (which leads to CanvasContext::setSurface and
3224 // re-create the EGLSurface) if either the Surface changed (as indicated by
3225 // generation id), or WindowManager changed the surface size. The latter is
3226 // because on some chips, changing the consumer side's BufferQueue size may
3227 // not take effect immediately unless we create a new EGLSurface.
3228 // Note that frame size change doesn't always imply surface size change (eg.
3229 // drag resizing uses fullscreen surface), need to check surfaceSizeChanged
3230 // flag from WindowManager.
3231 mAttachInfo.mThreadedRenderer.updateSurface(mSurface);
3232 } catch (OutOfResourcesException e) {
3233 handleOutOfResourcesException(e);
3234 mLastPerformTraversalsSkipDrawReason = "oom_update_surface";
3235 return;
3236 }
3237 }
3238
3239 if (mDragResizing != dragResizing) {
3240 if (dragResizing) {
3241 final boolean backdropSizeMatchesFrame =
3242 mWinFrame.width() == mPendingBackDropFrame.width()
3243 && mWinFrame.height() == mPendingBackDropFrame.height();
3244 // TODO: Need cutout?
3245 startDragResizing(mPendingBackDropFrame, !backdropSizeMatchesFrame,
3246 mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mResizeMode);
3247 } else {
3248 // We shouldn't come here, but if we come we should end the resize.
3249 endDragResizing();
3250 }
3251 }
3252 if (!mUseMTRenderer) {
3253 if (dragResizing) {
3254 mCanvasOffsetX = mWinFrame.left;
3255 mCanvasOffsetY = mWinFrame.top;
3256 } else {
3257 mCanvasOffsetX = mCanvasOffsetY = 0;
3258 }
3259 }
3260 } catch (RemoteException e) {
3261 } finally {
3262 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
3263 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3264 }
3265 }
3266
3267 if (DEBUG_ORIENTATION) Log.v(
3268 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
3269
3270 mAttachInfo.mWindowLeft = frame.left;
3271 mAttachInfo.mWindowTop = frame.top;
3272
3273 // !!FIXME!! This next section handles the case where we did not get the
3274 // window size we asked for. We should avoid this by getting a maximum size from
3275 // the window session beforehand.
3276 if (mWidth != frame.width() || mHeight != frame.height()) {
3277 mWidth = frame.width();
3278 mHeight = frame.height();
3279 }
3280
3281 if (mSurfaceHolder != null) {
3282 // The app owns the surface; tell it about what is going on.
3283 if (mSurface.isValid()) {
3284 // XXX .copyFrom() doesn't work!
3285 //mSurfaceHolder.mSurface.copyFrom(mSurface);
3286 mSurfaceHolder.mSurface = mSurface;
3287 }
3288 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
3289 mSurfaceHolder.mSurfaceLock.unlock();
3290 if (surfaceCreated) {
3291 mSurfaceHolder.ungetCallbacks();
3292
3293 mIsCreating = true;
3294 SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks();
3295 if (callbacks != null) {
3296 for (SurfaceHolder.Callback c : callbacks) {
3297 c.surfaceCreated(mSurfaceHolder);
3298 }
3299 }
3300 }
3301
3302 if ((surfaceCreated || surfaceReplaced || surfaceSizeChanged
3303 || windowAttributesChanged) && mSurface.isValid()) {
3304 SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks();
3305 if (callbacks != null) {
3306 for (SurfaceHolder.Callback c : callbacks) {
3307 c.surfaceChanged(mSurfaceHolder, lp.format,
3308 mWidth, mHeight);
3309 }
3310 }
3311 mIsCreating = false;
3312 }
3313
3314 if (surfaceDestroyed) {
3315 notifyHolderSurfaceDestroyed();
3316 mSurfaceHolder.mSurfaceLock.lock();
3317 try {
3318 mSurfaceHolder.mSurface = new Surface();
3319 } finally {
3320 mSurfaceHolder.mSurfaceLock.unlock();
3321 }
3322 }
3323 }
3324
3325 final ThreadedRenderer threadedRenderer = mAttachInfo.mThreadedRenderer;
3326 if (threadedRenderer != null && threadedRenderer.isEnabled()) {
3327 if (hwInitialized
3328 || mWidth != threadedRenderer.getWidth()
3329 || mHeight != threadedRenderer.getHeight()
3330 || mNeedsRendererSetup) {
3331 threadedRenderer.setup(mWidth, mHeight, mAttachInfo,
3332 mWindowAttributes.surfaceInsets);
3333 mNeedsRendererSetup = false;
3334 }
3335 }
3336
3337 // TODO: In the CL "ViewRootImpl: Fix issue with early draw report in
3338 // seamless rotation". We moved processing of RELAYOUT_RES_BLAST_SYNC
3339 // earlier in the function, potentially triggering a call to
3340 // reportNextDraw(). That same CL changed this and the next reference
3341 // to wasReportNextDraw, such that this logic would remain undisturbed
3342 // (it continues to operate as if the code was never moved). This was
3343 // done to achieve a more hermetic fix for S, but it's entirely
3344 // possible that checking the most recent value is actually more
3345 // correct here.
3346 if (!mStopped || mReportNextDraw) {
3347 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()
3348 || dispatchApplyInsets || updatedConfiguration) {
3349 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width,
3350 lp.privateFlags);
3351 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height,
3352 lp.privateFlags);
3353
3354 if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed! mWidth="
3355 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
3356 + " mHeight=" + mHeight
3357 + " measuredHeight=" + host.getMeasuredHeight()
3358 + " dispatchApplyInsets=" + dispatchApplyInsets);
3359
3360 // Ask host how big it wants to be
3361 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
3362
3363 // Implementation of weights from WindowManager.LayoutParams
3364 // We just grow the dimensions as needed and re-measure if
3365 // needs be
3366 int width = host.getMeasuredWidth();
3367 int height = host.getMeasuredHeight();
3368 boolean measureAgain = false;
3369
3370 if (lp.horizontalWeight > 0.0f) {
3371 width += (int) ((mWidth - width) * lp.horizontalWeight);
3372 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
3373 MeasureSpec.EXACTLY);
3374 measureAgain = true;
3375 }
3376 if (lp.verticalWeight > 0.0f) {
3377 height += (int) ((mHeight - height) * lp.verticalWeight);
3378 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
3379 MeasureSpec.EXACTLY);
3380 measureAgain = true;
3381 }
3382
3383 if (measureAgain) {
3384 if (DEBUG_LAYOUT) Log.v(mTag,
3385 "And hey let's measure once more: width=" + width
3386 + " height=" + height);
3387 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
3388 }
3389
3390 layoutRequested = true;
3391 }
3392 }
3393 } else {
3394 // Not the first pass and no window/insets/visibility change but the window
3395 // may have moved and we need check that and if so to update the left and right
3396 // in the attach info. We translate only the window frame since on window move
3397 // the window manager tells us only for the new frame but the insets are the
3398 // same and we do not want to translate them more than once.
3399 maybeHandleWindowMove(frame);
3400 }
3401
3402 if (mViewMeasureDeferred) {
3403 // It's time to measure the views since we are going to layout them.
3404 performMeasure(
3405 MeasureSpec.makeMeasureSpec(frame.width(), MeasureSpec.EXACTLY),
3406 MeasureSpec.makeMeasureSpec(frame.height(), MeasureSpec.EXACTLY));
3407 }
3408
3409 if (!mRelayoutRequested && mCheckIfCanDraw) {
3410 // We had a sync previously, but we didn't call IWindowSession#relayout in this
3411 // traversal. So we don't know if the sync is complete that we can continue to draw.
3412 // Here invokes cancelDraw to obtain the information.
3413 try {
3414 cancelDraw = mWindowSession.cancelDraw(mWindow);
3415 cancelReason = "wm_sync";
3416 if (DEBUG_BLAST) {
3417 Log.d(mTag, "cancelDraw returned " + cancelDraw);
3418 }
3419 } catch (RemoteException e) {
3420 }
3421 }
3422
3423 if (surfaceSizeChanged || surfaceReplaced || surfaceCreated || windowAttributesChanged) {
3424 // If the surface has been replaced, there's a chance the bounds layer is not parented
3425 // to the new layer. When updating bounds layer, also reparent to the main VRI
3426 // SurfaceControl to ensure it's correctly placed in the hierarchy.
3427 //
3428 // This needs to be done on the client side since WMS won't reparent the children to the
3429 // new surface if it thinks the app is closing. WMS gets the signal that the app is
3430 // stopping, but on the client side it doesn't get stopped since it's restarted quick
3431 // enough. WMS doesn't want to keep around old children since they will leak when the
3432 // client creates new children.
3433 prepareSurfaces();
3434 }
3435
3436 final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
3437 boolean triggerGlobalLayoutListener = didLayout
3438 || mAttachInfo.mRecomputeGlobalAttributes;
3439 if (didLayout) {
3440 performLayout(lp, mWidth, mHeight);
3441
3442 // By this point all views have been sized and positioned
3443 // We can compute the transparent area
3444
3445 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
3446 // start out transparent
3447 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
3448 host.getLocationInWindow(mTmpLocation);
3449 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
3450 mTmpLocation[0] + host.mRight - host.mLeft,
3451 mTmpLocation[1] + host.mBottom - host.mTop);
3452
3453 host.gatherTransparentRegion(mTransparentRegion);
3454 if (mTranslator != null) {
3455 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
3456 }
3457
3458 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
3459 mPreviousTransparentRegion.set(mTransparentRegion);
3460 mFullRedrawNeeded = true;
3461 // TODO: Ideally we would do this in prepareSurfaces,
3462 // but prepareSurfaces is currently working under
3463 // the assumption that we paused the render thread
3464 // via the WM relayout code path. We probably eventually
3465 // want to synchronize transparent region hint changes
3466 // with draws.
3467 SurfaceControl sc = getSurfaceControl();
3468 if (sc.isValid()) {
3469 mTransaction.setTransparentRegionHint(sc, mTransparentRegion).apply();
3470 }
3471 }
3472 }
3473
3474 if (DBG) {
3475 System.out.println("======================================");
3476 System.out.println("performTraversals -- after setFrame");
3477 host.debug();
3478 }
3479 }
3480
3481 // These callbacks will trigger SurfaceView SurfaceHolder.Callbacks and must be invoked
3482 // after the measure pass. If its invoked before the measure pass and the app modifies
3483 // the view hierarchy in the callbacks, we could leave the views in a broken state.
3484 if (surfaceCreated) {
3485 notifySurfaceCreated();
3486 } else if (surfaceReplaced) {
3487 notifySurfaceReplaced();
3488 } else if (surfaceDestroyed) {
3489 notifySurfaceDestroyed();
3490 }
3491
3492 if (triggerGlobalLayoutListener) {
3493 mAttachInfo.mRecomputeGlobalAttributes = false;
3494 mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
3495 }
3496
3497 Rect contentInsets = null;
3498 Rect visibleInsets = null;
3499 Region touchableRegion = null;
3500 int touchableInsetMode = TOUCHABLE_INSETS_REGION;
3501 boolean computedInternalInsets = false;
3502 if (computesInternalInsets) {
3503 final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
3504
3505 // Clear the original insets.
3506 insets.reset();
3507
3508 // Compute new insets in place.
3509 mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
3510 mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
3511
3512 // Tell the window manager.
3513 if (insetsPending || !mLastGivenInsets.equals(insets)) {
3514 mLastGivenInsets.set(insets);
3515
3516 // Translate insets to screen coordinates if needed.
3517 if (mTranslator != null) {
3518 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
3519 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
3520 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
3521 } else {
3522 contentInsets = insets.contentInsets;
3523 visibleInsets = insets.visibleInsets;
3524 touchableRegion = insets.touchableRegion;
3525 }
3526 computedInternalInsets = true;
3527 }
3528 touchableInsetMode = insets.mTouchableInsets;
3529 }
3530 boolean needsSetInsets = computedInternalInsets;
3531 needsSetInsets |= !Objects.equals(mPreviousTouchableRegion, mTouchableRegion) &&
3532 (mTouchableRegion != null);
3533 if (needsSetInsets) {
3534 if (mTouchableRegion != null) {
3535 if (mPreviousTouchableRegion == null) {
3536 mPreviousTouchableRegion = new Region();
3537 }
3538 mPreviousTouchableRegion.set(mTouchableRegion);
3539 if (touchableInsetMode != TOUCHABLE_INSETS_REGION) {
3540 Log.e(mTag, "Setting touchableInsetMode to non TOUCHABLE_INSETS_REGION" +
3541 " from OnComputeInternalInsets, while also using setTouchableRegion" +
3542 " causes setTouchableRegion to be ignored");
3543 }
3544 } else {
3545 mPreviousTouchableRegion = null;
3546 }
3547 if (contentInsets == null) contentInsets = new Rect(0,0,0,0);
3548 if (visibleInsets == null) visibleInsets = new Rect(0,0,0,0);
3549 if (touchableRegion == null) {
3550 touchableRegion = mTouchableRegion;
3551 } else if (touchableRegion != null && mTouchableRegion != null) {
3552 touchableRegion.op(touchableRegion, mTouchableRegion, Region.Op.UNION);
3553 }
3554 try {
3555 mWindowSession.setInsets(mWindow, touchableInsetMode,
3556 contentInsets, visibleInsets, touchableRegion);
3557 } catch (RemoteException e) {
3558 throw e.rethrowFromSystemServer();
3559 }
3560 } else if (mTouchableRegion == null && mPreviousTouchableRegion != null) {
3561 mPreviousTouchableRegion = null;
3562 try {
3563 mWindowSession.clearTouchableRegion(mWindow);
3564 } catch (RemoteException e) {
3565 throw e.rethrowFromSystemServer();
3566 }
3567 }
3568
3569 if (mFirst) {
3570 if (sAlwaysAssignFocus || !isInTouchMode()) {
3571 // handle first focus request
3572 if (DEBUG_INPUT_RESIZE) {
3573 Log.v(mTag, "First: mView.hasFocus()=" + mView.hasFocus());
3574 }
3575 if (mView != null) {
3576 if (!mView.hasFocus()) {
3577 mView.restoreDefaultFocus();
3578 if (DEBUG_INPUT_RESIZE) {
3579 Log.v(mTag, "First: requested focused view=" + mView.findFocus());
3580 }
3581 } else {
3582 if (DEBUG_INPUT_RESIZE) {
3583 Log.v(mTag, "First: existing focused view=" + mView.findFocus());
3584 }
3585 }
3586 }
3587 } else {
3588 // Some views (like ScrollView) won't hand focus to descendants that aren't within
3589 // their viewport. Before layout, there's a good change these views are size 0
3590 // which means no children can get focus. After layout, this view now has size, but
3591 // is not guaranteed to hand-off focus to a focusable child (specifically, the edge-
3592 // case where the child has a size prior to layout and thus won't trigger
3593 // focusableViewAvailable).
3594 View focused = mView.findFocus();
3595 if (focused instanceof ViewGroup
3596 && ((ViewGroup) focused).getDescendantFocusability()
3597 == ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3598 focused.restoreDefaultFocus();
3599 }
3600 }
3601 }
3602
3603 final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible;
3604 final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible;
3605 final boolean regainedFocus = hasWindowFocus && mLostWindowFocus;
3606 if (regainedFocus) {
3607 mLostWindowFocus = false;
3608 } else if (!hasWindowFocus && mHadWindowFocus) {
3609 mLostWindowFocus = true;
3610 }
3611
3612 if (changedVisibility || regainedFocus) {
3613 // Toasts are presented as notifications - don't present them as windows as well
3614 boolean isToast = mWindowAttributes.type == TYPE_TOAST;
3615 if (!isToast) {
3616 host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3617 }
3618 }
3619
3620 mFirst = false;
3621 mWillDrawSoon = false;
3622 mNewSurfaceNeeded = false;
3623 mActivityRelaunched = false;
3624 mViewVisibility = viewVisibility;
3625 mHadWindowFocus = hasWindowFocus;
3626
3627 mImeFocusController.onTraversal(hasWindowFocus, mWindowAttributes);
3628
3629 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
3630 reportNextDraw("first_relayout");
3631 }
3632
3633 mCheckIfCanDraw = isSyncRequest || cancelDraw;
3634
3635 boolean cancelDueToPreDrawListener = mAttachInfo.mTreeObserver.dispatchOnPreDraw();
3636 boolean cancelAndRedraw = cancelDueToPreDrawListener
3637 || (cancelDraw && mDrewOnceForSync);
3638 if (!cancelAndRedraw) {
3639 createSyncIfNeeded();
3640 mDrewOnceForSync = true;
3641 }
3642
3643 if (!isViewVisible) {
3644 mLastPerformTraversalsSkipDrawReason = "view_not_visible";
3645 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
3646 for (int i = 0; i < mPendingTransitions.size(); ++i) {
3647 mPendingTransitions.get(i).endChangingAnimations();
3648 }
3649 mPendingTransitions.clear();
3650 }
3651
3652 if (mSyncBufferCallback != null) {
3653 mSyncBufferCallback.onBufferReady(null);
3654 }
3655 } else if (cancelAndRedraw) {
3656 mLastPerformTraversalsSkipDrawReason = cancelDueToPreDrawListener
3657 ? "predraw_" + mAttachInfo.mTreeObserver.getLastDispatchOnPreDrawCanceledReason()
3658 : "cancel_" + cancelReason;
3659 // Try again
3660 scheduleTraversals();
3661 } else {
3662 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
3663 for (int i = 0; i < mPendingTransitions.size(); ++i) {
3664 mPendingTransitions.get(i).startChangingAnimations();
3665 }
3666 mPendingTransitions.clear();
3667 }
3668 if (!performDraw() && mSyncBufferCallback != null) {
3669 mSyncBufferCallback.onBufferReady(null);
3670 }
3671 }
3672
3673 if (mAttachInfo.mContentCaptureEvents != null) {
3674 notifyContentCatpureEvents();
3675 }
3676
3677 mIsInTraversal = false;
3678 mRelayoutRequested = false;
3679
3680 if (!cancelAndRedraw) {
3681 mReportNextDraw = false;
3682 mLastReportNextDrawReason = null;
3683 mSyncBufferCallback = null;
3684 mSyncBuffer = false;
3685 if (isInLocalSync()) {
3686 mSurfaceSyncer.markSyncReady(mSyncId);
3687 mSyncId = UNSET_SYNC_ID;
3688 mLocalSyncState = LOCAL_SYNC_NONE;
3689 }
3690 }
3691 }
3692
3693 private void createSyncIfNeeded() {
3694 // Started a sync already or there's nothing needing to sync
3695 if (isInLocalSync() || !mReportNextDraw) {
3696 return;
3697 }
3698
3699 final int seqId = mSyncSeqId;
3700 mLocalSyncState = LOCAL_SYNC_PENDING;
3701 mSyncId = mSurfaceSyncer.setupSync(transaction -> {
3702 mLocalSyncState = LOCAL_SYNC_RETURNED;
3703 // Callback will be invoked on executor thread so post to main thread.
3704 mHandler.postAtFrontOfQueue(() -> {
3705 mLocalSyncState = LOCAL_SYNC_MERGED;
3706 mSurfaceChangedTransaction.merge(transaction);
3707 reportDrawFinished(seqId);
3708 });
3709 });
3710 if (DEBUG_BLAST) {
3711 Log.d(mTag, "Setup new sync id=" + mSyncId);
3712 }
3713 mSurfaceSyncer.addToSync(mSyncId, mSyncTarget);
3714 notifySurfaceSyncStarted();
3715 }
3716
3717 private void notifyContentCatpureEvents() {
3718 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "notifyContentCaptureEvents");
3719 try {
3720 MainContentCaptureSession mainSession = mAttachInfo.mContentCaptureManager
3721 .getMainContentCaptureSession();
3722 for (int i = 0; i < mAttachInfo.mContentCaptureEvents.size(); i++) {
3723 int sessionId = mAttachInfo.mContentCaptureEvents.keyAt(i);
3724 mainSession.notifyViewTreeEvent(sessionId, /* started= */ true);
3725 ArrayList<Object> events = mAttachInfo.mContentCaptureEvents
3726 .valueAt(i);
3727 for_each_event: for (int j = 0; j < events.size(); j++) {
3728 Object event = events.get(j);
3729 if (event instanceof AutofillId) {
3730 mainSession.notifyViewDisappeared(sessionId, (AutofillId) event);
3731 } else if (event instanceof View) {
3732 View view = (View) event;
3733 ContentCaptureSession session = view.getContentCaptureSession();
3734 if (session == null) {
3735 Log.w(mTag, "no content capture session on view: " + view);
3736 continue for_each_event;
3737 }
3738 int actualId = session.getId();
3739 if (actualId != sessionId) {
3740 Log.w(mTag, "content capture session mismatch for view (" + view
3741 + "): was " + sessionId + " before, it's " + actualId + " now");
3742 continue for_each_event;
3743 }
3744 ViewStructure structure = session.newViewStructure(view);
3745 view.onProvideContentCaptureStructure(structure, /* flags= */ 0);
3746 session.notifyViewAppeared(structure);
3747 } else if (event instanceof Insets) {
3748 mainSession.notifyViewInsetsChanged(sessionId, (Insets) event);
3749 } else {
3750 Log.w(mTag, "invalid content capture event: " + event);
3751 }
3752 }
3753 mainSession.notifyViewTreeEvent(sessionId, /* started= */ false);
3754 }
3755 mAttachInfo.mContentCaptureEvents = null;
3756 } finally {
3757 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
3758 }
3759 }
3760
3761 private void notifyHolderSurfaceDestroyed() {
3762 mSurfaceHolder.ungetCallbacks();
3763 SurfaceHolder.Callback[] callbacks = mSurfaceHolder.getCallbacks();
3764 if (callbacks != null) {
3765 for (SurfaceHolder.Callback c : callbacks) {
3766 c.surfaceDestroyed(mSurfaceHolder);
3767 }
3768 }
3769 }
3770
3771 private void maybeHandleWindowMove(Rect frame) {
3772 // TODO: Well, we are checking whether the frame has changed similarly
3773 // to how this is done for the insets. This is however incorrect since
3774 // the insets and the frame are translated. For example, the old frame
3775 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
3776 // reported frame is (2, 2 - 2, 2) which implies no change but this is not
3777 // true since we are comparing a not translated value to a translated one.
3778 // This scenario is rare but we may want to fix that.
3779
3780 final boolean windowMoved = mAttachInfo.mWindowLeft != frame.left
3781 || mAttachInfo.mWindowTop != frame.top;
3782 if (windowMoved) {
3783 mAttachInfo.mWindowLeft = frame.left;
3784 mAttachInfo.mWindowTop = frame.top;
3785 }
3786 if (windowMoved || mAttachInfo.mNeedsUpdateLightCenter) {
3787 // Update the light position for the new offsets.
3788 if (mAttachInfo.mThreadedRenderer != null) {
3789 mAttachInfo.mThreadedRenderer.setLightCenter(mAttachInfo);
3790 }
3791 mAttachInfo.mNeedsUpdateLightCenter = false;
3792 }
3793 }
3794
3795 private void handleWindowFocusChanged() {
3796 final boolean hasWindowFocus;
3797 synchronized (this) {
3798 if (!mWindowFocusChanged) {
3799 return;
3800 }
3801 mWindowFocusChanged = false;
3802 hasWindowFocus = mUpcomingWindowFocus;
3803 }
3804 // TODO (b/131181940): Make sure this doesn't leak Activity with mActivityConfigCallback
3805 // config changes.
3806 if (hasWindowFocus) {
3807 mInsetsController.onWindowFocusGained(
3808 getFocusedViewOrNull() != null /* hasViewFocused */);
3809 } else {
3810 mInsetsController.onWindowFocusLost();
3811 }
3812
3813 if (mAdded) {
3814 dispatchFocusEvent(hasWindowFocus, false /* fakeFocus */);
3815 // Note: must be done after the focus change callbacks,
3816 // so all of the view state is set up correctly.
3817 mImeFocusController.onPostWindowFocus(
3818 getFocusedViewOrNull(), hasWindowFocus, mWindowAttributes);
3819
3820 if (hasWindowFocus) {
3821 // Clear the forward bit. We can just do this directly, since
3822 // the window manager doesn't care about it.
3823 mWindowAttributes.softInputMode &=
3824 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3825 ((WindowManager.LayoutParams) mView.getLayoutParams())
3826 .softInputMode &=
3827 ~WindowManager.LayoutParams
3828 .SOFT_INPUT_IS_FORWARD_NAVIGATION;
3829
3830 // Refocusing a window that has a focused view should fire a
3831 // focus event for the view since the global focused view changed.
3832 fireAccessibilityFocusEventIfHasFocusedNode();
3833 } else {
3834 if (mPointerCapture) {
3835 handlePointerCaptureChanged(false);
3836 }
3837 }
3838 }
3839 mFirstInputStage.onWindowFocusChanged(hasWindowFocus);
3840
3841 // NOTE: there's no view visibility (appeared / disapparead) events when the windows focus
3842 // is lost, so we don't need to to force a flush - there might be other events such as
3843 // text changes, but these should be flushed independently.
3844 if (hasWindowFocus) {
3845 handleContentCaptureFlush();
3846 }
3847 }
3848
3849 /**
3850 * Send a fake focus event for unfocused apps in split screen as some game engines wait to
3851 * get focus before drawing the content of the app. This will be used so that apps do not get
3852 * blacked out when they are resumed and do not have focus yet.
3853 *
3854 * {@hide}
3855 */
3856 // TODO(b/263094829): Investigate dispatching this for onPause as well
3857 public void dispatchCompatFakeFocus() {
3858 boolean aboutToHaveFocus = false;
3859 synchronized (this) {
3860 aboutToHaveFocus = mWindowFocusChanged && mUpcomingWindowFocus;
3861 }
3862 final boolean alreadyHaveFocus = mAttachInfo.mHasWindowFocus;
3863 if (aboutToHaveFocus || alreadyHaveFocus) {
3864 // Do not need to toggle focus if app doesn't need it, or has focus.
3865 return;
3866 }
3867 EventLog.writeEvent(LOGTAG_INPUT_FOCUS,
3868 "Giving fake focus to " + mBasePackageName, "reason=unity bug workaround");
3869 dispatchFocusEvent(true /* hasWindowFocus */, true /* fakeFocus */);
3870 EventLog.writeEvent(LOGTAG_INPUT_FOCUS,
3871 "Removing fake focus from " + mBasePackageName, "reason=timeout callback");
3872 dispatchFocusEvent(false /* hasWindowFocus */, true /* fakeFocus */);
3873 }
3874
3875 private void dispatchFocusEvent(boolean hasWindowFocus, boolean fakeFocus) {
3876 profileRendering(hasWindowFocus);
3877 if (hasWindowFocus && mAttachInfo.mThreadedRenderer != null && mSurface.isValid()) {
3878 mFullRedrawNeeded = true;
3879 try {
3880 final Rect surfaceInsets = mWindowAttributes.surfaceInsets;
3881 mAttachInfo.mThreadedRenderer.initializeIfNeeded(
3882 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
3883 } catch (OutOfResourcesException e) {
3884 Log.e(mTag, "OutOfResourcesException locking surface", e);
3885 try {
3886 if (!mWindowSession.outOfMemory(mWindow)) {
3887 Slog.w(mTag, "No processes killed for memory;"
3888 + " killing self");
3889 Process.killProcess(Process.myPid());
3890 }
3891 } catch (RemoteException ex) {
3892 }
3893 // Retry in a bit.
3894 mHandler.sendMessageDelayed(mHandler.obtainMessage(
3895 MSG_WINDOW_FOCUS_CHANGED), 500);
3896 return;
3897 }
3898 }
3899
3900 mAttachInfo.mHasWindowFocus = hasWindowFocus;
3901 if (!fakeFocus) {
3902 mImeFocusController.updateImeFocusable(mWindowAttributes, true /* force */);
3903 mImeFocusController.onPreWindowFocus(hasWindowFocus, mWindowAttributes);
3904 }
3905
3906 if (mView != null) {
3907 mAttachInfo.mKeyDispatchState.reset();
3908 mView.dispatchWindowFocusChanged(hasWindowFocus);
3909 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3910 if (mAttachInfo.mTooltipHost != null) {
3911 mAttachInfo.mTooltipHost.hideTooltip();
3912 }
3913 }
3914 }
3915
3916 private void handleWindowTouchModeChanged() {
3917 final boolean inTouchMode;
3918 synchronized (this) {
3919 inTouchMode = mUpcomingInTouchMode;
3920 }
3921 ensureTouchModeLocally(inTouchMode);
3922 }
3923
3924 private void fireAccessibilityFocusEventIfHasFocusedNode() {
3925 if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
3926 return;
3927 }
3928 final View focusedView = mView.findFocus();
3929 if (focusedView == null) {
3930 return;
3931 }
3932 final AccessibilityNodeProvider provider = focusedView.getAccessibilityNodeProvider();
3933 if (provider == null) {
3934 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3935 } else {
3936 final AccessibilityNodeInfo focusedNode = findFocusedVirtualNode(provider);
3937 if (focusedNode != null) {
3938 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(
3939 focusedNode.getSourceNodeId());
3940 // This is a best effort since clearing and setting the focus via the
3941 // provider APIs could have side effects. We don't have a provider API
3942 // similar to that on View to ask a given event to be fired.
3943 final AccessibilityEvent event = AccessibilityEvent.obtain(
3944 AccessibilityEvent.TYPE_VIEW_FOCUSED);
3945 event.setSource(focusedView, virtualId);
3946 event.setPackageName(focusedNode.getPackageName());
3947 event.setChecked(focusedNode.isChecked());
3948 event.setContentDescription(focusedNode.getContentDescription());
3949 event.setPassword(focusedNode.isPassword());
3950 event.getText().add(focusedNode.getText());
3951 event.setEnabled(focusedNode.isEnabled());
3952 focusedView.getParent().requestSendAccessibilityEvent(focusedView, event);
3953 focusedNode.recycle();
3954 }
3955 }
3956 }
3957
3958 private AccessibilityNodeInfo findFocusedVirtualNode(AccessibilityNodeProvider provider) {
3959 AccessibilityNodeInfo focusedNode = provider.findFocus(
3960 AccessibilityNodeInfo.FOCUS_INPUT);
3961 if (focusedNode != null) {
3962 return focusedNode;
3963 }
3964
3965 if (!mContext.isAutofillCompatibilityEnabled()) {
3966 return null;
3967 }
3968
3969 // Unfortunately some provider implementations don't properly
3970 // implement AccessibilityNodeProvider#findFocus
3971 AccessibilityNodeInfo current = provider.createAccessibilityNodeInfo(
3972 AccessibilityNodeProvider.HOST_VIEW_ID);
3973 if (current.isFocused()) {
3974 return current;
3975 }
3976
3977 final Queue<AccessibilityNodeInfo> fringe = new ArrayDeque<>();
3978 fringe.offer(current);
3979
3980 while (!fringe.isEmpty()) {
3981 current = fringe.poll();
3982 final LongArray childNodeIds = current.getChildNodeIds();
3983 if (childNodeIds== null || childNodeIds.size() <= 0) {
3984 continue;
3985 }
3986 final int childCount = childNodeIds.size();
3987 for (int i = 0; i < childCount; i++) {
3988 final int virtualId = AccessibilityNodeInfo.getVirtualDescendantId(
3989 childNodeIds.get(i));
3990 final AccessibilityNodeInfo child = provider.createAccessibilityNodeInfo(virtualId);
3991 if (child != null) {
3992 if (child.isFocused()) {
3993 return child;
3994 }
3995 fringe.offer(child);
3996 }
3997 }
3998 current.recycle();
3999 }
4000
4001 return null;
4002 }
4003
4004 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
4005 Log.e(mTag, "OutOfResourcesException initializing HW surface", e);
4006 try {
4007 if (!mWindowSession.outOfMemory(mWindow) &&
4008 Process.myUid() != Process.SYSTEM_UID) {
4009 Slog.w(mTag, "No processes killed for memory; killing self");
4010 Process.killProcess(Process.myPid());
4011 }
4012 } catch (RemoteException ex) {
4013 }
4014 mLayoutRequested = true; // ask wm for a new surface next time.
4015 }
4016
4017 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
4018 if (mView == null) {
4019 return;
4020 }
4021 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
4022 try {
4023 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4024 } finally {
4025 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
4026 }
4027 mMeasuredWidth = mView.getMeasuredWidth();
4028 mMeasuredHeight = mView.getMeasuredHeight();
4029 mViewMeasureDeferred = false;
4030 }
4031
4032 /**
4033 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
4034 * is currently undergoing a layout pass.
4035 *
4036 * @return whether the view hierarchy is currently undergoing a layout pass
4037 */
4038 boolean isInLayout() {
4039 return mInLayout;
4040 }
4041
4042 /**
4043 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
4044 * undergoing a layout pass. requestLayout() should not generally be called during layout,
4045 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
4046 * all children in that container hierarchy are measured and laid out at the end of the layout
4047 * pass for that container). If requestLayout() is called anyway, we handle it correctly
4048 * by registering all requesters during a frame as it proceeds. At the end of the frame,
4049 * we check all of those views to see if any still have pending layout requests, which
4050 * indicates that they were not correctly handled by their container hierarchy. If that is
4051 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
4052 * to blank containers, and force a second request/measure/layout pass in this frame. If
4053 * more requestLayout() calls are received during that second layout pass, we post those
4054 * requests to the next frame to avoid possible infinite loops.
4055 *
4056 * <p>The return value from this method indicates whether the request should proceed
4057 * (if it is a request during the first layout pass) or should be skipped and posted to the
4058 * next frame (if it is a request during the second layout pass).</p>
4059 *
4060 * @param view the view that requested the layout.
4061 *
4062 * @return true if request should proceed, false otherwise.
4063 */
4064 boolean requestLayoutDuringLayout(final View view) {
4065 if (view.mParent == null || view.mAttachInfo == null) {
4066 // Would not normally trigger another layout, so just let it pass through as usual
4067 return true;
4068 }
4069 if (!mLayoutRequesters.contains(view)) {
4070 mLayoutRequesters.add(view);
4071 }
4072 if (!mHandlingLayoutInLayoutRequest) {
4073 // Let the request proceed normally; it will be processed in a second layout pass
4074 // if necessary
4075 return true;
4076 } else {
4077 // Don't let the request proceed during the second layout pass.
4078 // It will post to the next frame instead.
4079 return false;
4080 }
4081 }
4082
4083 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
4084 int desiredWindowHeight) {
4085 mScrollMayChange = true;
4086 mInLayout = true;
4087
4088 final View host = mView;
4089 if (host == null) {
4090 return;
4091 }
4092 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
4093 Log.v(mTag, "Laying out " + host + " to (" +
4094 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
4095 }
4096
4097 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
4098 try {
4099 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
4100
4101 mInLayout = false;
4102 int numViewsRequestingLayout = mLayoutRequesters.size();
4103 if (numViewsRequestingLayout > 0) {
4104 // requestLayout() was called during layout.
4105 // If no layout-request flags are set on the requesting views, there is no problem.
4106 // If some requests are still pending, then we need to clear those flags and do
4107 // a full request/measure/layout pass to handle this situation.
4108 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
4109 false);
4110 if (validLayoutRequesters != null) {
4111 // Set this flag to indicate that any further requests are happening during
4112 // the second pass, which may result in posting those requests to the next
4113 // frame instead
4114 mHandlingLayoutInLayoutRequest = true;
4115
4116 // Process fresh layout requests, then measure and layout
4117 int numValidRequests = validLayoutRequesters.size();
4118 for (int i = 0; i < numValidRequests; ++i) {
4119 final View view = validLayoutRequesters.get(i);
4120 Log.w("View", "requestLayout() improperly called by " + view +
4121 " during layout: running second layout pass");
4122 view.requestLayout();
4123 }
4124 measureHierarchy(host, lp, mView.getContext().getResources(),
4125 desiredWindowWidth, desiredWindowHeight, false /* forRootSizeOnly */);
4126 mInLayout = true;
4127 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
4128
4129 mHandlingLayoutInLayoutRequest = false;
4130
4131 // Check the valid requests again, this time without checking/clearing the
4132 // layout flags, since requests happening during the second pass get noop'd
4133 validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
4134 if (validLayoutRequesters != null) {
4135 final ArrayList<View> finalRequesters = validLayoutRequesters;
4136 // Post second-pass requests to the next frame
4137 getRunQueue().post(new Runnable() {
4138 @Override
4139 public void run() {
4140 int numValidRequests = finalRequesters.size();
4141 for (int i = 0; i < numValidRequests; ++i) {
4142 final View view = finalRequesters.get(i);
4143 Log.w("View", "requestLayout() improperly called by " + view +
4144 " during second layout pass: posting in next frame");
4145 view.requestLayout();
4146 }
4147 }
4148 });
4149 }
4150 }
4151
4152 }
4153 } finally {
4154 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
4155 }
4156 mInLayout = false;
4157 }
4158
4159 /**
4160 * This method is called during layout when there have been calls to requestLayout() during
4161 * layout. It walks through the list of views that requested layout to determine which ones
4162 * still need it, based on visibility in the hierarchy and whether they have already been
4163 * handled (as is usually the case with ListView children).
4164 *
4165 * @param layoutRequesters The list of views that requested layout during layout
4166 * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
4167 * If so, the FORCE_LAYOUT flag was not set on requesters.
4168 * @return A list of the actual views that still need to be laid out.
4169 */
4170 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
4171 boolean secondLayoutRequests) {
4172
4173 int numViewsRequestingLayout = layoutRequesters.size();
4174 ArrayList<View> validLayoutRequesters = null;
4175 for (int i = 0; i < numViewsRequestingLayout; ++i) {
4176 View view = layoutRequesters.get(i);
4177 if (view != null && view.mAttachInfo != null && view.mParent != null &&
4178 (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
4179 View.PFLAG_FORCE_LAYOUT)) {
4180 boolean gone = false;
4181 View parent = view;
4182 // Only trigger new requests for views in a non-GONE hierarchy
4183 while (parent != null) {
4184 if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
4185 gone = true;
4186 break;
4187 }
4188 if (parent.mParent instanceof View) {
4189 parent = (View) parent.mParent;
4190 } else {
4191 parent = null;
4192 }
4193 }
4194 if (!gone) {
4195 if (validLayoutRequesters == null) {
4196 validLayoutRequesters = new ArrayList<View>();
4197 }
4198 validLayoutRequesters.add(view);
4199 }
4200 }
4201 }
4202 if (!secondLayoutRequests) {
4203 // If we're checking the layout flags, then we need to clean them up also
4204 for (int i = 0; i < numViewsRequestingLayout; ++i) {
4205 View view = layoutRequesters.get(i);
4206 while (view != null &&
4207 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
4208 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
4209 if (view.mParent instanceof View) {
4210 view = (View) view.mParent;
4211 } else {
4212 view = null;
4213 }
4214 }
4215 }
4216 }
4217 layoutRequesters.clear();
4218 return validLayoutRequesters;
4219 }
4220
4221 @Override
4222 public void requestTransparentRegion(View child) {
4223 // the test below should not fail unless someone is messing with us
4224 checkThread();
4225 if (mView != child) {
4226 return;
4227 }
4228
4229 if ((mView.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) {
4230 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
4231 // Need to make sure we re-evaluate the window attributes next
4232 // time around, to ensure the window has the correct format.
4233 mWindowAttributesChanged = true;
4234 }
4235
4236 // Always request layout to apply the latest transparent region.
4237 requestLayout();
4238 }
4239
4240 /**
4241 * Figures out the measure spec for the root view in a window based on it's
4242 * layout params.
4243 *
4244 * @param windowSize The available width or height of the window.
4245 * @param measurement The layout width or height requested in the layout params.
4246 * @param privateFlags The private flags in the layout params of the window.
4247 * @return The measure spec to use to measure the root view.
4248 */
4249 private static int getRootMeasureSpec(int windowSize, int measurement, int privateFlags) {
4250 int measureSpec;
4251 final int rootDimension = (privateFlags & PRIVATE_FLAG_LAYOUT_SIZE_EXTENDED_BY_CUTOUT) != 0
4252 ? MATCH_PARENT : measurement;
4253 switch (rootDimension) {
4254 case ViewGroup.LayoutParams.MATCH_PARENT:
4255 // Window can't resize. Force root view to be windowSize.
4256 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
4257 break;
4258 case ViewGroup.LayoutParams.WRAP_CONTENT:
4259 // Window can resize. Set max size for root view.
4260 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
4261 break;
4262 default:
4263 // Window wants to be an exact size. Force root view to be that size.
4264 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
4265 break;
4266 }
4267 return measureSpec;
4268 }
4269
4270 int mHardwareXOffset;
4271 int mHardwareYOffset;
4272
4273 @Override
4274 public void onPreDraw(RecordingCanvas canvas) {
4275 // If mCurScrollY is not 0 then this influences the hardwareYOffset. The end result is we
4276 // can apply offsets that are not handled by anything else, resulting in underdraw as
4277 // the View is shifted (thus shifting the window background) exposing unpainted
4278 // content. To handle this with minimal glitches we just clear to BLACK if the window
4279 // is opaque. If it's not opaque then HWUI already internally does a glClear to
4280 // transparent, so there's no risk of underdraw on non-opaque surfaces.
4281 if (mCurScrollY != 0 && mHardwareYOffset != 0 && mAttachInfo.mThreadedRenderer.isOpaque()) {
4282 canvas.drawColor(Color.BLACK);
4283 }
4284 canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
4285 }
4286
4287 @Override
4288 public void onPostDraw(RecordingCanvas canvas) {
4289 drawAccessibilityFocusedDrawableIfNeeded(canvas);
4290 if (mUseMTRenderer) {
4291 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
4292 mWindowCallbacks.get(i).onPostDraw(canvas);
4293 }
4294 }
4295 }
4296
4297 /**
4298 * @hide
4299 */
4300 void outputDisplayList(View view) {
4301 view.mRenderNode.output();
4302 }
4303
4304 /**
4305 * @see #PROPERTY_PROFILE_RENDERING
4306 */
4307 private void profileRendering(boolean enabled) {
4308 if (mProfileRendering) {
4309 mRenderProfilingEnabled = enabled;
4310
4311 if (mRenderProfiler != null) {
4312 mChoreographer.removeFrameCallback(mRenderProfiler);
4313 }
4314 if (mRenderProfilingEnabled) {
4315 if (mRenderProfiler == null) {
4316 mRenderProfiler = new Choreographer.FrameCallback() {
4317 @Override
4318 public void doFrame(long frameTimeNanos) {
4319 mDirty.set(0, 0, mWidth, mHeight);
4320 scheduleTraversals();
4321 if (mRenderProfilingEnabled) {
4322 mChoreographer.postFrameCallback(mRenderProfiler);
4323 }
4324 }
4325 };
4326 }
4327 mChoreographer.postFrameCallback(mRenderProfiler);
4328 } else {
4329 mRenderProfiler = null;
4330 }
4331 }
4332 }
4333
4334 /**
4335 * Called from draw() when DEBUG_FPS is enabled
4336 */
4337 private void trackFPS() {
4338 // Tracks frames per second drawn. First value in a series of draws may be bogus
4339 // because it down not account for the intervening idle time
4340 long nowTime = System.currentTimeMillis();
4341 if (mFpsStartTime < 0) {
4342 mFpsStartTime = mFpsPrevTime = nowTime;
4343 mFpsNumFrames = 0;
4344 } else {
4345 ++mFpsNumFrames;
4346 String thisHash = Integer.toHexString(System.identityHashCode(this));
4347 long frameTime = nowTime - mFpsPrevTime;
4348 long totalTime = nowTime - mFpsStartTime;
4349 Log.v(mTag, "0x" + thisHash + "\tFrame time:\t" + frameTime);
4350 mFpsPrevTime = nowTime;
4351 if (totalTime > 1000) {
4352 float fps = (float) mFpsNumFrames * 1000 / totalTime;
4353 Log.v(mTag, "0x" + thisHash + "\tFPS:\t" + fps);
4354 mFpsStartTime = nowTime;
4355 mFpsNumFrames = 0;
4356 }
4357 }
4358 }
4359
4360 private void reportDrawFinished(int seqId) {
4361 if (DEBUG_BLAST) {
4362 Log.d(mTag, "reportDrawFinished " + Debug.getCallers(5));
4363 }
4364
4365 try {
4366 mWindowSession.finishDrawing(mWindow, mSurfaceChangedTransaction, seqId);
4367 } catch (RemoteException e) {
4368 Log.e(mTag, "Unable to report draw finished", e);
4369 mSurfaceChangedTransaction.apply();
4370 } finally {
4371 mSurfaceChangedTransaction.clear();
4372 }
4373 }
4374
4375 /**
4376 * @hide
4377 */
4378 public boolean isHardwareEnabled() {
4379 return mAttachInfo.mThreadedRenderer != null && mAttachInfo.mThreadedRenderer.isEnabled();
4380 }
4381
4382 void addToSync(SurfaceSyncer.SyncTarget syncable) {
4383 if (!isInLocalSync()) {
4384 return;
4385 }
4386 mSurfaceSyncer.addToSync(mSyncId, syncable);
4387 }
4388
4389 /**
4390 * This VRI is currently in the middle of a sync request, but specifically one initiated from
4391 * within VRI.
4392 */
4393 public boolean isInLocalSync() {
4394 return mSyncId != UNSET_SYNC_ID;
4395 }
4396
4397 private void addFrameCommitCallbackIfNeeded() {
4398 if (!isHardwareEnabled()) {
4399 return;
4400 }
4401
4402 ArrayList<Runnable> commitCallbacks = mAttachInfo.mTreeObserver
4403 .captureFrameCommitCallbacks();
4404 final boolean needFrameCommitCallback =
4405 (commitCallbacks != null && commitCallbacks.size() > 0);
4406 if (!needFrameCommitCallback) {
4407 return;
4408 }
4409
4410 if (DEBUG_DRAW) {
4411 Log.d(mTag, "Creating frameCommitCallback"
4412 + " commitCallbacks size=" + commitCallbacks.size());
4413 }
4414 mAttachInfo.mThreadedRenderer.setFrameCommitCallback(didProduceBuffer -> {
4415 if (DEBUG_DRAW) {
4416 Log.d(mTag, "Received frameCommitCallback didProduceBuffer=" + didProduceBuffer);
4417 }
4418
4419 mHandler.postAtFrontOfQueue(() -> {
4420 for (int i = 0; i < commitCallbacks.size(); i++) {
4421 commitCallbacks.get(i).run();
4422 }
4423 });
4424 });
4425 }
4426
4427 private void registerCallbackForPendingTransactions() {
4428 registerRtFrameCallback(new FrameDrawingCallback() {
4429 @Override
4430 public HardwareRenderer.FrameCommitCallback onFrameDraw(int syncResult, long frame) {
4431 if ((syncResult
4432 & (SYNC_LOST_SURFACE_REWARD_IF_FOUND | SYNC_CONTEXT_IS_STOPPED)) != 0) {
4433 mBlastBufferQueue.applyPendingTransactions(frame);
4434 return null;
4435 }
4436
4437 return didProduceBuffer -> {
4438 if (!didProduceBuffer) {
4439 mBlastBufferQueue.applyPendingTransactions(frame);
4440 }
4441 };
4442
4443 }
4444
4445 @Override
4446 public void onFrameDraw(long frame) {
4447 }
4448 });
4449 }
4450
4451 private boolean performDraw() {
4452 mLastPerformDrawSkippedReason = null;
4453 if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
4454 mLastPerformDrawSkippedReason = "screen_off";
4455 return false;
4456 } else if (mView == null) {
4457 mLastPerformDrawSkippedReason = "no_root_view";
4458 return false;
4459 }
4460
4461 final boolean fullRedrawNeeded = mFullRedrawNeeded || mSyncBufferCallback != null;
4462 mFullRedrawNeeded = false;
4463
4464 mIsDrawing = true;
4465 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
4466
4467 addFrameCommitCallbackIfNeeded();
4468
4469 boolean usingAsyncReport = isHardwareEnabled() && mSyncBufferCallback != null;
4470 if (usingAsyncReport) {
4471 registerCallbacksForSync(mSyncBuffer, mSyncBufferCallback);
4472 } else if (mHasPendingTransactions) {
4473 // These callbacks are only needed if there's no sync involved and there were calls to
4474 // applyTransactionOnDraw. These callbacks check if the draw failed for any reason and
4475 // apply those transactions directly so they don't get stuck forever.
4476 registerCallbackForPendingTransactions();
4477 }
4478 mHasPendingTransactions = false;
4479
4480 try {
4481 boolean canUseAsync = draw(fullRedrawNeeded, usingAsyncReport && mSyncBuffer);
4482 if (usingAsyncReport && !canUseAsync) {
4483 mAttachInfo.mThreadedRenderer.setFrameCallback(null);
4484 usingAsyncReport = false;
4485 }
4486 } finally {
4487 mIsDrawing = false;
4488 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
4489 }
4490
4491 // For whatever reason we didn't create a HardwareRenderer, end any
4492 // hardware animations that are now dangling
4493 if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
4494 final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
4495 for (int i = 0; i < count; i++) {
4496 mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
4497 }
4498 mAttachInfo.mPendingAnimatingRenderNodes.clear();
4499 }
4500
4501 if (mReportNextDraw) {
4502
4503 // if we're using multi-thread renderer, wait for the window frame draws
4504 if (mWindowDrawCountDown != null) {
4505 try {
4506 mWindowDrawCountDown.await();
4507 } catch (InterruptedException e) {
4508 Log.e(mTag, "Window redraw count down interrupted!");
4509 }
4510 mWindowDrawCountDown = null;
4511 }
4512
4513 if (mAttachInfo.mThreadedRenderer != null) {
4514 mAttachInfo.mThreadedRenderer.setStopped(mStopped);
4515 }
4516
4517 if (LOCAL_LOGV) {
4518 Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
4519 }
4520
4521 if (mSurfaceHolder != null && mSurface.isValid()) {
4522 final SurfaceSyncer.SyncBufferCallback syncBufferCallback = mSyncBufferCallback;
4523 SurfaceCallbackHelper sch = new SurfaceCallbackHelper(() ->
4524 mHandler.post(() -> syncBufferCallback.onBufferReady(null)));
4525 mSyncBufferCallback = null;
4526
4527 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
4528
4529 sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks);
4530 } else if (!usingAsyncReport) {
4531 if (mAttachInfo.mThreadedRenderer != null) {
4532 mAttachInfo.mThreadedRenderer.fence();
4533 }
4534 }
4535 }
4536 if (mSyncBufferCallback != null && !usingAsyncReport) {
4537 mSyncBufferCallback.onBufferReady(null);
4538 }
4539 if (mPerformContentCapture) {
4540 performContentCaptureInitialReport();
4541 }
4542 return true;
4543 }
4544
4545 /**
4546 * Checks (and caches) if content capture is enabled for this context.
4547 */
4548 private boolean isContentCaptureEnabled() {
4549 switch (mContentCaptureEnabled) {
4550 case CONTENT_CAPTURE_ENABLED_TRUE:
4551 return true;
4552 case CONTENT_CAPTURE_ENABLED_FALSE:
4553 return false;
4554 case CONTENT_CAPTURE_ENABLED_NOT_CHECKED:
4555 final boolean reallyEnabled = isContentCaptureReallyEnabled();
4556 mContentCaptureEnabled = reallyEnabled ? CONTENT_CAPTURE_ENABLED_TRUE
4557 : CONTENT_CAPTURE_ENABLED_FALSE;
4558 return reallyEnabled;
4559 default:
4560 Log.w(TAG, "isContentCaptureEnabled(): invalid state " + mContentCaptureEnabled);
4561 return false;
4562 }
4563
4564 }
4565
4566 /**
4567 * Checks (without caching) if content capture is enabled for this context.
4568 */
4569 private boolean isContentCaptureReallyEnabled() {
4570 // First check if context supports it, so it saves a service lookup when it doesn't
4571 if (mContext.getContentCaptureOptions() == null) return false;
4572
4573 final ContentCaptureManager ccm = mAttachInfo.getContentCaptureManager(mContext);
4574 // Then check if it's enabled in the contex itself.
4575 if (ccm == null || !ccm.isContentCaptureEnabled()) return false;
4576
4577 return true;
4578 }
4579
4580 private void performContentCaptureInitialReport() {
4581 mPerformContentCapture = false; // One-time offer!
4582 final View rootView = mView;
4583 if (DEBUG_CONTENT_CAPTURE) {
4584 Log.v(mTag, "performContentCaptureInitialReport() on " + rootView);
4585 }
4586 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
4587 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "dispatchContentCapture() for "
4588 + getClass().getSimpleName());
4589 }
4590 try {
4591 if (!isContentCaptureEnabled()) return;
4592
4593 // Initial dispatch of window bounds to content capture
4594 if (mAttachInfo.mContentCaptureManager != null) {
4595 MainContentCaptureSession session =
4596 mAttachInfo.mContentCaptureManager.getMainContentCaptureSession();
4597 session.notifyWindowBoundsChanged(session.getId(),
4598 getConfiguration().windowConfiguration.getBounds());
4599 }
4600
4601 // Content capture is a go!
4602 rootView.dispatchInitialProvideContentCaptureStructure();
4603 } finally {
4604 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
4605 }
4606 }
4607
4608 private void handleContentCaptureFlush() {
4609 if (DEBUG_CONTENT_CAPTURE) {
4610 Log.v(mTag, "handleContentCaptureFlush()");
4611 }
4612 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
4613 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "flushContentCapture for "
4614 + getClass().getSimpleName());
4615 }
4616 try {
4617 if (!isContentCaptureEnabled()) return;
4618
4619 final ContentCaptureManager ccm = mAttachInfo.mContentCaptureManager;
4620 if (ccm == null) {
4621 Log.w(TAG, "No ContentCapture on AttachInfo");
4622 return;
4623 }
4624 ccm.flush(ContentCaptureSession.FLUSH_REASON_VIEW_ROOT_ENTERED);
4625 } finally {
4626 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
4627 }
4628 }
4629
4630 private boolean draw(boolean fullRedrawNeeded, boolean forceDraw) {
4631 Surface surface = mSurface;
4632 if (!surface.isValid()) {
4633 return false;
4634 }
4635
4636 if (DEBUG_FPS) {
4637 trackFPS();
4638 }
4639
4640 if (!sFirstDrawComplete) {
4641 synchronized (sFirstDrawHandlers) {
4642 sFirstDrawComplete = true;
4643 final int count = sFirstDrawHandlers.size();
4644 for (int i = 0; i< count; i++) {
4645 mHandler.post(sFirstDrawHandlers.get(i));
4646 }
4647 }
4648 }
4649
4650 scrollToRectOrFocus(null, false);
4651
4652 if (mAttachInfo.mViewScrollChanged) {
4653 mAttachInfo.mViewScrollChanged = false;
4654 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
4655 }
4656
4657 boolean animating = mScroller != null && mScroller.computeScrollOffset();
4658 final int curScrollY;
4659 if (animating) {
4660 curScrollY = mScroller.getCurrY();
4661 } else {
4662 curScrollY = mScrollY;
4663 }
4664 if (mCurScrollY != curScrollY) {
4665 mCurScrollY = curScrollY;
4666 fullRedrawNeeded = true;
4667 if (mView instanceof RootViewSurfaceTaker) {
4668 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
4669 }
4670 }
4671
4672 final float appScale = mAttachInfo.mApplicationScale;
4673 final boolean scalingRequired = mAttachInfo.mScalingRequired;
4674
4675 final Rect dirty = mDirty;
4676 if (mSurfaceHolder != null) {
4677 // The app owns the surface, we won't draw.
4678 dirty.setEmpty();
4679 if (animating && mScroller != null) {
4680 mScroller.abortAnimation();
4681 }
4682 return false;
4683 }
4684
4685 if (fullRedrawNeeded) {
4686 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
4687 }
4688
4689 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
4690 Log.v(mTag, "Draw " + mView + "/"
4691 + mWindowAttributes.getTitle()
4692 + ": dirty={" + dirty.left + "," + dirty.top
4693 + "," + dirty.right + "," + dirty.bottom + "} surface="
4694 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
4695 appScale + ", width=" + mWidth + ", height=" + mHeight);
4696 }
4697
4698 mAttachInfo.mTreeObserver.dispatchOnDraw();
4699
4700 int xOffset = -mCanvasOffsetX;
4701 int yOffset = -mCanvasOffsetY + curScrollY;
4702 final WindowManager.LayoutParams params = mWindowAttributes;
4703 final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
4704 if (surfaceInsets != null) {
4705 xOffset -= surfaceInsets.left;
4706 yOffset -= surfaceInsets.top;
4707
4708 // Offset dirty rect for surface insets.
4709 dirty.offset(surfaceInsets.left, surfaceInsets.top);
4710 }
4711
4712 boolean accessibilityFocusDirty = false;
4713 final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
4714 if (drawable != null) {
4715 final Rect bounds = mAttachInfo.mTmpInvalRect;
4716 final boolean hasFocus = getAccessibilityFocusedRect(bounds);
4717 if (!hasFocus) {
4718 bounds.setEmpty();
4719 }
4720 if (!bounds.equals(drawable.getBounds())) {
4721 accessibilityFocusDirty = true;
4722 }
4723 }
4724
4725 mAttachInfo.mDrawingTime =
4726 mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
4727
4728 boolean useAsyncReport = false;
4729 if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
4730 if (isHardwareEnabled()) {
4731 // If accessibility focus moved, always invalidate the root.
4732 boolean invalidateRoot = accessibilityFocusDirty || mInvalidateRootRequested;
4733 mInvalidateRootRequested = false;
4734
4735 // Draw with hardware renderer.
4736 mIsAnimating = false;
4737
4738 if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
4739 mHardwareYOffset = yOffset;
4740 mHardwareXOffset = xOffset;
4741 invalidateRoot = true;
4742 }
4743
4744 if (invalidateRoot) {
4745 mAttachInfo.mThreadedRenderer.invalidateRoot();
4746 }
4747
4748 dirty.setEmpty();
4749
4750 // Stage the content drawn size now. It will be transferred to the renderer
4751 // shortly before the draw commands get send to the renderer.
4752 final boolean updated = updateContentDrawBounds();
4753
4754 if (mReportNextDraw) {
4755 // report next draw overrides setStopped()
4756 // This value is re-sync'd to the value of mStopped
4757 // in the handling of mReportNextDraw post-draw.
4758 mAttachInfo.mThreadedRenderer.setStopped(false);
4759 }
4760
4761 if (updated) {
4762 requestDrawWindow();
4763 }
4764
4765 useAsyncReport = true;
4766
4767 if (forceDraw) {
4768 mAttachInfo.mThreadedRenderer.forceDrawNextFrame();
4769 }
4770 mAttachInfo.mThreadedRenderer.draw(mView, mAttachInfo, this);
4771 } else {
4772 // If we get here with a disabled & requested hardware renderer, something went
4773 // wrong (an invalidate posted right before we destroyed the hardware surface
4774 // for instance) so we should just bail out. Locking the surface with software
4775 // rendering at this point would lock it forever and prevent hardware renderer
4776 // from doing its job when it comes back.
4777 // Before we request a new frame we must however attempt to reinitiliaze the
4778 // hardware renderer if it's in requested state. This would happen after an
4779 // eglTerminate() for instance.
4780 if (mAttachInfo.mThreadedRenderer != null &&
4781 !mAttachInfo.mThreadedRenderer.isEnabled() &&
4782 mAttachInfo.mThreadedRenderer.isRequested() &&
4783 mSurface.isValid()) {
4784
4785 try {
4786 mAttachInfo.mThreadedRenderer.initializeIfNeeded(
4787 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
4788 } catch (OutOfResourcesException e) {
4789 handleOutOfResourcesException(e);
4790 return false;
4791 }
4792
4793 mFullRedrawNeeded = true;
4794 scheduleTraversals();
4795 return false;
4796 }
4797
4798 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset,
4799 scalingRequired, dirty, surfaceInsets)) {
4800 return false;
4801 }
4802 }
4803 }
4804
4805 if (animating) {
4806 mFullRedrawNeeded = true;
4807 scheduleTraversals();
4808 }
4809 return useAsyncReport;
4810 }
4811
4812 /**
4813 * @return true if drawing was successful, false if an error occurred
4814 */
4815 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
4816 boolean scalingRequired, Rect dirty, Rect surfaceInsets) {
4817
4818 // Draw with software renderer.
4819 final Canvas canvas;
4820
4821 // We already have the offset of surfaceInsets in xoff, yoff and dirty region,
4822 // therefore we need to add it back when moving the dirty region.
4823 int dirtyXOffset = xoff;
4824 int dirtyYOffset = yoff;
4825 if (surfaceInsets != null) {
4826 dirtyXOffset += surfaceInsets.left;
4827 dirtyYOffset += surfaceInsets.top;
4828 }
4829
4830 try {
4831 dirty.offset(-dirtyXOffset, -dirtyYOffset);
4832 final int left = dirty.left;
4833 final int top = dirty.top;
4834 final int right = dirty.right;
4835 final int bottom = dirty.bottom;
4836
4837 canvas = mSurface.lockCanvas(dirty);
4838
4839 // TODO: Do this in native
4840 canvas.setDensity(mDensity);
4841 } catch (Surface.OutOfResourcesException e) {
4842 handleOutOfResourcesException(e);
4843 return false;
4844 } catch (IllegalArgumentException e) {
4845 Log.e(mTag, "Could not lock surface", e);
4846 // Don't assume this is due to out of memory, it could be
4847 // something else, and if it is something else then we could
4848 // kill stuff (or ourself) for no reason.
4849 mLayoutRequested = true; // ask wm for a new surface next time.
4850 return false;
4851 } finally {
4852 dirty.offset(dirtyXOffset, dirtyYOffset); // Reset to the original value.
4853 }
4854
4855 try {
4856 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
4857 Log.v(mTag, "Surface " + surface + " drawing to bitmap w="
4858 + canvas.getWidth() + ", h=" + canvas.getHeight());
4859 //canvas.drawARGB(255, 255, 0, 0);
4860 }
4861
4862 // If this bitmap's format includes an alpha channel, we
4863 // need to clear it before drawing so that the child will
4864 // properly re-composite its drawing on a transparent
4865 // background. This automatically respects the clip/dirty region
4866 // or
4867 // If we are applying an offset, we need to clear the area
4868 // where the offset doesn't appear to avoid having garbage
4869 // left in the blank areas.
4870 if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
4871 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
4872 }
4873
4874 dirty.setEmpty();
4875 mIsAnimating = false;
4876 mView.mPrivateFlags |= View.PFLAG_DRAWN;
4877
4878 if (DEBUG_DRAW) {
4879 Context cxt = mView.getContext();
4880 Log.i(mTag, "Drawing: package:" + cxt.getPackageName() +
4881 ", metrics=" + cxt.getResources().getDisplayMetrics() +
4882 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
4883 }
4884 canvas.translate(-xoff, -yoff);
4885 if (mTranslator != null) {
4886 mTranslator.translateCanvas(canvas);
4887 }
4888 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
4889
4890 mView.draw(canvas);
4891
4892 drawAccessibilityFocusedDrawableIfNeeded(canvas);
4893 } finally {
4894 try {
4895 surface.unlockCanvasAndPost(canvas);
4896 } catch (IllegalArgumentException e) {
4897 Log.e(mTag, "Could not unlock surface", e);
4898 mLayoutRequested = true; // ask wm for a new surface next time.
4899 //noinspection ReturnInsideFinallyBlock
4900 return false;
4901 }
4902
4903 if (LOCAL_LOGV) {
4904 Log.v(mTag, "Surface " + surface + " unlockCanvasAndPost");
4905 }
4906 }
4907 return true;
4908 }
4909
4910 /**
4911 * We want to draw a highlight around the current accessibility focused.
4912 * Since adding a style for all possible view is not a viable option we
4913 * have this specialized drawing method.
4914 *
4915 * Note: We are doing this here to be able to draw the highlight for
4916 * virtual views in addition to real ones.
4917 *
4918 * @param canvas The canvas on which to draw.
4919 */
4920 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
4921 final Rect bounds = mAttachInfo.mTmpInvalRect;
4922 if (getAccessibilityFocusedRect(bounds)) {
4923 final Drawable drawable = getAccessibilityFocusedDrawable();
4924 if (drawable != null) {
4925 drawable.setBounds(bounds);
4926 drawable.draw(canvas);
4927 }
4928 } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
4929 mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
4930 }
4931 }
4932
4933 private boolean getAccessibilityFocusedRect(Rect bounds) {
4934 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
4935 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
4936 return false;
4937 }
4938
4939 final View host = mAccessibilityFocusedHost;
4940 if (host == null || host.mAttachInfo == null) {
4941 return false;
4942 }
4943
4944 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
4945 if (provider == null) {
4946 host.getBoundsOnScreen(bounds, true);
4947 } else if (mAccessibilityFocusedVirtualView != null) {
4948 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
4949 } else {
4950 return false;
4951 }
4952
4953 // Transform the rect into window-relative coordinates.
4954 final AttachInfo attachInfo = mAttachInfo;
4955 bounds.offset(0, attachInfo.mViewRootImpl.mScrollY);
4956 bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
4957 if (!bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth,
4958 attachInfo.mViewRootImpl.mHeight)) {
4959 // If no intersection, set bounds to empty.
4960 bounds.setEmpty();
4961 }
4962 return !bounds.isEmpty();
4963 }
4964
4965 private Drawable getAccessibilityFocusedDrawable() {
4966 // Lazily load the accessibility focus drawable.
4967 if (mAttachInfo.mAccessibilityFocusDrawable == null) {
4968 final TypedValue value = new TypedValue();
4969 final boolean resolved = mView.mContext.getTheme().resolveAttribute(
4970 R.attr.accessibilityFocusedDrawable, value, true);
4971 if (resolved) {
4972 mAttachInfo.mAccessibilityFocusDrawable =
4973 mView.mContext.getDrawable(value.resourceId);
4974 }
4975 }
4976 // Sets the focus appearance data into the accessibility focus drawable.
4977 if (mAttachInfo.mAccessibilityFocusDrawable instanceof GradientDrawable) {
4978 final GradientDrawable drawable =
4979 (GradientDrawable) mAttachInfo.mAccessibilityFocusDrawable;
4980 drawable.setStroke(mAccessibilityManager.getAccessibilityFocusStrokeWidth(),
4981 mAccessibilityManager.getAccessibilityFocusColor());
4982 }
4983
4984 return mAttachInfo.mAccessibilityFocusDrawable;
4985 }
4986
4987 void updateSystemGestureExclusionRectsForView(View view) {
4988 mGestureExclusionTracker.updateRectsForView(view);
4989 mHandler.sendEmptyMessage(MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED);
4990 }
4991
4992 void systemGestureExclusionChanged() {
4993 final List<Rect> rectsForWindowManager = mGestureExclusionTracker.computeChangedRects();
4994 if (rectsForWindowManager != null && mView != null) {
4995 try {
4996 mWindowSession.reportSystemGestureExclusionChanged(mWindow, rectsForWindowManager);
4997 } catch (RemoteException e) {
4998 throw e.rethrowFromSystemServer();
4999 }
5000 mAttachInfo.mTreeObserver
5001 .dispatchOnSystemGestureExclusionRectsChanged(rectsForWindowManager);
5002 }
5003 }
5004
5005 /**
5006 * Set the root-level system gesture exclusion rects. These are added to those provided by
5007 * the root's view hierarchy.
5008 */
5009 public void setRootSystemGestureExclusionRects(@NonNull List<Rect> rects) {
5010 mGestureExclusionTracker.setRootRects(rects);
5011 mHandler.sendEmptyMessage(MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED);
5012 }
5013
5014 /**
5015 * Returns the root-level system gesture exclusion rects. These do not include those provided by
5016 * the root's view hierarchy.
5017 */
5018 @NonNull
5019 public List<Rect> getRootSystemGestureExclusionRects() {
5020 return mGestureExclusionTracker.getRootRects();
5021 }
5022
5023 /**
5024 * Called from View when the position listener is triggered
5025 */
5026 void updateKeepClearRectsForView(View view) {
5027 mKeepClearRectsTracker.updateRectsForView(view);
5028 mUnrestrictedKeepClearRectsTracker.updateRectsForView(view);
5029 mHandler.sendEmptyMessage(MSG_KEEP_CLEAR_RECTS_CHANGED);
5030 }
5031
5032 void keepClearRectsChanged() {
5033 boolean restrictedKeepClearRectsChanged = mKeepClearRectsTracker.computeChanges();
5034 boolean unrestrictedKeepClearRectsChanged =
5035 mUnrestrictedKeepClearRectsTracker.computeChanges();
5036
5037 if ((restrictedKeepClearRectsChanged || unrestrictedKeepClearRectsChanged)
5038 && mView != null) {
5039 mHasPendingKeepClearAreaChange = true;
5040 // Only report keep clear areas immediately if they have not been reported recently
5041 if (!mHandler.hasMessages(MSG_REPORT_KEEP_CLEAR_RECTS)) {
5042 mHandler.sendEmptyMessageDelayed(MSG_REPORT_KEEP_CLEAR_RECTS,
5043 KEEP_CLEAR_AREA_REPORT_RATE_MILLIS);
5044 reportKeepClearAreasChanged();
5045 }
5046 }
5047 }
5048
5049 void reportKeepClearAreasChanged() {
5050 if (!mHasPendingKeepClearAreaChange || mView == null) {
5051 return;
5052 }
5053 mHasPendingKeepClearAreaChange = false;
5054
5055 final List<Rect> restrictedKeepClearRects = mKeepClearRectsTracker.getLastComputedRects();
5056 final List<Rect> unrestrictedKeepClearRects =
5057 mUnrestrictedKeepClearRectsTracker.getLastComputedRects();
5058
5059 try {
5060 mWindowSession.reportKeepClearAreasChanged(mWindow, restrictedKeepClearRects,
5061 unrestrictedKeepClearRects);
5062 } catch (RemoteException e) {
5063 throw e.rethrowFromSystemServer();
5064 }
5065 }
5066
5067 /**
5068 * Requests that the root render node is invalidated next time we perform a draw, such that
5069 * {@link WindowCallbacks#onPostDraw} gets called.
5070 */
5071 public void requestInvalidateRootRenderNode() {
5072 mInvalidateRootRequested = true;
5073 }
5074
5075 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
5076 final Rect ci = mAttachInfo.mContentInsets;
5077 final Rect vi = mAttachInfo.mVisibleInsets;
5078 int scrollY = 0;
5079 boolean handled = false;
5080
5081 if (vi.left > ci.left || vi.top > ci.top
5082 || vi.right > ci.right || vi.bottom > ci.bottom) {
5083 // We'll assume that we aren't going to change the scroll
5084 // offset, since we want to avoid that unless it is actually
5085 // going to make the focus visible... otherwise we scroll
5086 // all over the place.
5087 scrollY = mScrollY;
5088 // We can be called for two different situations: during a draw,
5089 // to update the scroll position if the focus has changed (in which
5090 // case 'rectangle' is null), or in response to a
5091 // requestChildRectangleOnScreen() call (in which case 'rectangle'
5092 // is non-null and we just want to scroll to whatever that
5093 // rectangle is).
5094 final View focus = mView.findFocus();
5095 if (focus == null) {
5096 return false;
5097 }
5098 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
5099 if (focus != lastScrolledFocus) {
5100 // If the focus has changed, then ignore any requests to scroll
5101 // to a rectangle; first we want to make sure the entire focus
5102 // view is visible.
5103 rectangle = null;
5104 }
5105 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Eval scroll: focus=" + focus
5106 + " rectangle=" + rectangle + " ci=" + ci
5107 + " vi=" + vi);
5108 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
5109 // Optimization: if the focus hasn't changed since last
5110 // time, and no layout has happened, then just leave things
5111 // as they are.
5112 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Keeping scroll y="
5113 + mScrollY + " vi=" + vi.toShortString());
5114 } else {
5115 // We need to determine if the currently focused view is
5116 // within the visible part of the window and, if not, apply
5117 // a pan so it can be seen.
5118 mLastScrolledFocus = new WeakReference<View>(focus);
5119 mScrollMayChange = false;
5120 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Need to scroll?");
5121 // Try to find the rectangle from the focus view.
5122 if (focus.getGlobalVisibleRect(mVisRect, null)) {
5123 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Root w="
5124 + mView.getWidth() + " h=" + mView.getHeight()
5125 + " ci=" + ci.toShortString()
5126 + " vi=" + vi.toShortString());
5127 if (rectangle == null) {
5128 focus.getFocusedRect(mTempRect);
5129 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Focus " + focus
5130 + ": focusRect=" + mTempRect.toShortString());
5131 if (mView instanceof ViewGroup) {
5132 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
5133 focus, mTempRect);
5134 }
5135 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5136 "Focus in window: focusRect="
5137 + mTempRect.toShortString()
5138 + " visRect=" + mVisRect.toShortString());
5139 } else {
5140 mTempRect.set(rectangle);
5141 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5142 "Request scroll to rect: "
5143 + mTempRect.toShortString()
5144 + " visRect=" + mVisRect.toShortString());
5145 }
5146 if (mTempRect.intersect(mVisRect)) {
5147 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5148 "Focus window visible rect: "
5149 + mTempRect.toShortString());
5150 if (mTempRect.height() >
5151 (mView.getHeight()-vi.top-vi.bottom)) {
5152 // If the focus simply is not going to fit, then
5153 // best is probably just to leave things as-is.
5154 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5155 "Too tall; leaving scrollY=" + scrollY);
5156 }
5157 // Next, check whether top or bottom is covered based on the non-scrolled
5158 // position, and calculate new scrollY (or set it to 0).
5159 // We can't keep using mScrollY here. For example mScrollY is non-zero
5160 // due to IME, then IME goes away. The current value of mScrollY leaves top
5161 // and bottom both visible, but we still need to scroll it back to 0.
5162 else if (mTempRect.top < vi.top) {
5163 scrollY = mTempRect.top - vi.top;
5164 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5165 "Top covered; scrollY=" + scrollY);
5166 } else if (mTempRect.bottom > (mView.getHeight()-vi.bottom)) {
5167 scrollY = mTempRect.bottom - (mView.getHeight()-vi.bottom);
5168 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
5169 "Bottom covered; scrollY=" + scrollY);
5170 } else {
5171 scrollY = 0;
5172 }
5173 handled = true;
5174 }
5175 }
5176 }
5177 }
5178
5179 if (scrollY != mScrollY) {
5180 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Pan scroll changed: old="
5181 + mScrollY + " , new=" + scrollY);
5182 if (!immediate) {
5183 if (mScroller == null) {
5184 mScroller = new Scroller(mView.getContext());
5185 }
5186 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
5187 } else if (mScroller != null) {
5188 mScroller.abortAnimation();
5189 }
5190 mScrollY = scrollY;
5191 }
5192
5193 return handled;
5194 }
5195
5196 /**
5197 * @hide
5198 */
5199 @UnsupportedAppUsage
5200 public View getAccessibilityFocusedHost() {
5201 return mAccessibilityFocusedHost;
5202 }
5203
5204 /**
5205 * Get accessibility-focused virtual view. The bounds and sourceNodeId of the returned node is
5206 * up-to-date while other fields may be stale.
5207 *
5208 * @hide
5209 */
5210 @UnsupportedAppUsage
5211 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
5212 return mAccessibilityFocusedVirtualView;
5213 }
5214
5215 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
5216 // If we have a virtual view with accessibility focus we need
5217 // to clear the focus and invalidate the virtual view bounds.
5218 if (mAccessibilityFocusedVirtualView != null) {
5219
5220 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
5221 View focusHost = mAccessibilityFocusedHost;
5222
5223 // Wipe the state of the current accessibility focus since
5224 // the call into the provider to clear accessibility focus
5225 // will fire an accessibility event which will end up calling
5226 // this method and we want to have clean state when this
5227 // invocation happens.
5228 mAccessibilityFocusedHost = null;
5229 mAccessibilityFocusedVirtualView = null;
5230
5231 // Clear accessibility focus on the host after clearing state since
5232 // this method may be reentrant.
5233 focusHost.clearAccessibilityFocusNoCallbacks(
5234 AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5235
5236 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
5237 if (provider != null) {
5238 // Invalidate the area of the cleared accessibility focus.
5239 focusNode.getBoundsInParent(mTempRect);
5240 focusHost.invalidate(mTempRect);
5241 // Clear accessibility focus in the virtual node.
5242 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
5243 focusNode.getSourceNodeId());
5244 provider.performAction(virtualNodeId,
5245 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
5246 }
5247 focusNode.recycle();
5248 }
5249 if ((mAccessibilityFocusedHost != null) && (mAccessibilityFocusedHost != view)) {
5250 // Clear accessibility focus in the view.
5251 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(
5252 AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5253 }
5254
5255 // Set the new focus host and node.
5256 mAccessibilityFocusedHost = view;
5257 mAccessibilityFocusedVirtualView = node;
5258
5259 if (mAttachInfo.mThreadedRenderer != null) {
5260 mAttachInfo.mThreadedRenderer.invalidateRoot();
5261 }
5262 }
5263
5264 boolean hasPointerCapture() {
5265 return mPointerCapture;
5266 }
5267
5268 void requestPointerCapture(boolean enabled) {
5269 final IBinder inputToken = getInputToken();
5270 if (inputToken == null) {
5271 Log.e(mTag, "No input channel to request Pointer Capture.");
5272 return;
5273 }
5274 InputManager.getInstance().requestPointerCapture(inputToken, enabled);
5275 }
5276
5277 private void handlePointerCaptureChanged(boolean hasCapture) {
5278 if (mPointerCapture == hasCapture) {
5279 return;
5280 }
5281 mPointerCapture = hasCapture;
5282 if (mView != null) {
5283 mView.dispatchPointerCaptureChanged(hasCapture);
5284 }
5285 }
5286
5287 private void updateColorModeIfNeeded(@ActivityInfo.ColorMode int colorMode) {
5288 if (mAttachInfo.mThreadedRenderer == null) {
5289 return;
5290 }
5291 // TODO: Centralize this sanitization? Why do we let setting bad modes?
5292 // Alternatively, can we just let HWUI figure it out? Do we need to care here?
5293 if (colorMode != ActivityInfo.COLOR_MODE_A8
5294 && !getConfiguration().isScreenWideColorGamut()) {
5295 colorMode = ActivityInfo.COLOR_MODE_DEFAULT;
5296 }
5297 mAttachInfo.mThreadedRenderer.setColorMode(colorMode);
5298 }
5299
5300 @Override
5301 public void requestChildFocus(View child, View focused) {
5302 if (DEBUG_INPUT_RESIZE) {
5303 Log.v(mTag, "Request child focus: focus now " + focused);
5304 }
5305 checkThread();
5306 scheduleTraversals();
5307 }
5308
5309 @Override
5310 public void clearChildFocus(View child) {
5311 if (DEBUG_INPUT_RESIZE) {
5312 Log.v(mTag, "Clearing child focus");
5313 }
5314 checkThread();
5315 scheduleTraversals();
5316 }
5317
5318 @Override
5319 public ViewParent getParentForAccessibility() {
5320 return null;
5321 }
5322
5323 @Override
5324 public void focusableViewAvailable(View v) {
5325 checkThread();
5326 if (mView != null) {
5327 if (!mView.hasFocus()) {
5328 if (sAlwaysAssignFocus || !mAttachInfo.mInTouchMode) {
5329 v.requestFocus();
5330 }
5331 } else {
5332 // the one case where will transfer focus away from the current one
5333 // is if the current view is a view group that prefers to give focus
5334 // to its children first AND the view is a descendant of it.
5335 View focused = mView.findFocus();
5336 if (focused instanceof ViewGroup) {
5337 ViewGroup group = (ViewGroup) focused;
5338 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
5339 && isViewDescendantOf(v, focused)) {
5340 v.requestFocus();
5341 }
5342 }
5343 }
5344 }
5345 }
5346
5347 @Override
5348 public void recomputeViewAttributes(View child) {
5349 checkThread();
5350 if (mView == child) {
5351 mAttachInfo.mRecomputeGlobalAttributes = true;
5352 if (!mWillDrawSoon) {
5353 scheduleTraversals();
5354 }
5355 }
5356 }
5357
5358 void dispatchDetachedFromWindow() {
5359 // Make sure we free-up insets resources if view never received onWindowFocusLost()
5360 // because of a die-signal
5361 mInsetsController.onWindowFocusLost();
5362 mFirstInputStage.onDetachedFromWindow();
5363 if (mView != null && mView.mAttachInfo != null) {
5364 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
5365 mView.dispatchDetachedFromWindow();
5366 }
5367
5368 mAccessibilityInteractionConnectionManager.ensureNoConnection();
5369 removeSendWindowContentChangedCallback();
5370
5371 destroyHardwareRenderer();
5372
5373 setAccessibilityFocus(null, null);
5374
5375 mInsetsController.cancelExistingAnimations();
5376
5377 mView.assignParent(null);
5378 mView = null;
5379 mAttachInfo.mRootView = null;
5380
5381 destroySurface();
5382
5383 if (mInputQueueCallback != null && mInputQueue != null) {
5384 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
5385 mInputQueue.dispose();
5386 mInputQueueCallback = null;
5387 mInputQueue = null;
5388 }
5389 try {
5390 mWindowSession.remove(mWindow);
5391 } catch (RemoteException e) {
5392 }
5393 // Dispose receiver would dispose client InputChannel, too. That could send out a socket
5394 // broken event, so we need to unregister the server InputChannel when removing window to
5395 // prevent server side receive the event and prompt error.
5396 if (mInputEventReceiver != null) {
5397 mInputEventReceiver.dispose();
5398 mInputEventReceiver = null;
5399 }
5400
5401 unregisterListeners();
5402 unscheduleTraversals();
5403 }
5404
5405 /**
5406 * Notifies all callbacks that configuration and/or display has changed and updates internal
5407 * state.
5408 * @param mergedConfiguration New global and override config in {@link MergedConfiguration}
5409 * container.
5410 * @param force Flag indicating if we should force apply the config.
5411 * @param newDisplayId Id of new display if moved, {@link Display#INVALID_DISPLAY} if not
5412 * changed.
5413 */
5414 private void performConfigurationChange(MergedConfiguration mergedConfiguration, boolean force,
5415 int newDisplayId) {
5416 if (mergedConfiguration == null) {
5417 throw new IllegalArgumentException("No merged config provided.");
5418 }
5419
5420 final int lastRotation = mLastReportedMergedConfiguration.getMergedConfiguration()
5421 .windowConfiguration.getRotation();
5422 final int newRotation = mergedConfiguration.getMergedConfiguration()
5423 .windowConfiguration.getRotation();
5424 if (lastRotation != newRotation) {
5425 // Trigger ThreadedRenderer#updateSurface() if the surface control doesn't change.
5426 // Because even if the actual surface size is not changed, e.g. flip 180 degrees,
5427 // the buffers may still have content in previous rotation. And the next draw may
5428 // not update all regions, that causes some afterimages to flicker.
5429 mUpdateSurfaceNeeded = true;
5430 if (!mIsInTraversal) {
5431 mForceNextWindowRelayout = true;
5432 }
5433 }
5434
5435 Configuration globalConfig = mergedConfiguration.getGlobalConfiguration();
5436 final Configuration overrideConfig = mergedConfiguration.getOverrideConfiguration();
5437 if (DEBUG_CONFIGURATION) Log.v(mTag,
5438 "Applying new config to window " + mWindowAttributes.getTitle()
5439 + ", globalConfig: " + globalConfig
5440 + ", overrideConfig: " + overrideConfig);
5441
5442 final CompatibilityInfo ci = mDisplay.getDisplayAdjustments().getCompatibilityInfo();
5443 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
5444 globalConfig = new Configuration(globalConfig);
5445 ci.applyToConfiguration(mNoncompatDensity, globalConfig);
5446 }
5447
5448 synchronized (sConfigCallbacks) {
5449 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
5450 sConfigCallbacks.get(i).onConfigurationChanged(globalConfig);
5451 }
5452 }
5453
5454 mLastReportedMergedConfiguration.setConfiguration(globalConfig, overrideConfig);
5455
5456 mForceNextConfigUpdate = force;
5457 if (mActivityConfigCallback != null) {
5458 // An activity callback is set - notify it about override configuration update.
5459 // This basically initiates a round trip to ActivityThread and back, which will ensure
5460 // that corresponding activity and resources are updated before updating inner state of
5461 // ViewRootImpl. Eventually it will call #updateConfiguration().
5462 mActivityConfigCallback.onConfigurationChanged(overrideConfig, newDisplayId);
5463 } else {
5464 // There is no activity callback - update the configuration right away.
5465 updateConfiguration(newDisplayId);
5466 }
5467 mForceNextConfigUpdate = false;
5468 }
5469
5470 /**
5471 * Update display and views if last applied merged configuration changed.
5472 * @param newDisplayId Id of new display if moved, {@link Display#INVALID_DISPLAY} otherwise.
5473 */
5474 public void updateConfiguration(int newDisplayId) {
5475 if (mView == null) {
5476 return;
5477 }
5478
5479 // At this point the resources have been updated to
5480 // have the most recent config, whatever that is. Use
5481 // the one in them which may be newer.
5482 final Resources localResources = mView.getResources();
5483 final Configuration config = localResources.getConfiguration();
5484
5485 // Handle move to display.
5486 if (newDisplayId != INVALID_DISPLAY) {
5487 onMovedToDisplay(newDisplayId, config);
5488 }
5489
5490 // Handle configuration change.
5491 if (mForceNextConfigUpdate || mLastConfigurationFromResources.diff(config) != 0) {
5492 // Update the display with new DisplayAdjustments.
5493 updateInternalDisplay(mDisplay.getDisplayId(), localResources);
5494
5495 updateLastConfigurationFromResources(config);
5496 mView.dispatchConfigurationChanged(config);
5497
5498 // We could have gotten this {@link Configuration} update after we called
5499 // {@link #performTraversals} with an older {@link Configuration}. As a result, our
5500 // window frame may be stale. We must ensure the next pass of {@link #performTraversals}
5501 // catches this.
5502 mForceNextWindowRelayout = true;
5503 requestLayout();
5504 }
5505
5506 updateForceDarkMode();
5507 }
5508
5509 private void updateLastConfigurationFromResources(Configuration resConfig) {
5510 final int lastLayoutDirection = mLastConfigurationFromResources.getLayoutDirection();
5511 final int currentLayoutDirection = resConfig.getLayoutDirection();
5512 mLastConfigurationFromResources.setTo(resConfig);
5513 // Update layout direction in case the language or screen layout is changed.
5514 if (lastLayoutDirection != currentLayoutDirection && mView != null
5515 && mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
5516 mView.setLayoutDirection(currentLayoutDirection);
5517 }
5518 }
5519
5520 /**
5521 * Return true if child is an ancestor of parent, (or equal to the parent).
5522 */
5523 public static boolean isViewDescendantOf(View child, View parent) {
5524 if (child == parent) {
5525 return true;
5526 }
5527
5528 final ViewParent theParent = child.getParent();
5529 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
5530 }
5531
5532 private static void forceLayout(View view) {
5533 view.forceLayout();
5534 if (view instanceof ViewGroup) {
5535 ViewGroup group = (ViewGroup) view;
5536 final int count = group.getChildCount();
5537 for (int i = 0; i < count; i++) {
5538 forceLayout(group.getChildAt(i));
5539 }
5540 }
5541 }
5542
5543 private static final int MSG_INVALIDATE = 1;
5544 private static final int MSG_INVALIDATE_RECT = 2;
5545 private static final int MSG_DIE = 3;
5546 private static final int MSG_RESIZED = 4;
5547 private static final int MSG_RESIZED_REPORT = 5;
5548 private static final int MSG_WINDOW_FOCUS_CHANGED = 6;
5549 private static final int MSG_DISPATCH_INPUT_EVENT = 7;
5550 private static final int MSG_DISPATCH_APP_VISIBILITY = 8;
5551 private static final int MSG_DISPATCH_GET_NEW_SURFACE = 9;
5552 private static final int MSG_DISPATCH_KEY_FROM_IME = 11;
5553 private static final int MSG_DISPATCH_KEY_FROM_AUTOFILL = 12;
5554 private static final int MSG_CHECK_FOCUS = 13;
5555 private static final int MSG_CLOSE_SYSTEM_DIALOGS = 14;
5556 private static final int MSG_DISPATCH_DRAG_EVENT = 15;
5557 private static final int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
5558 private static final int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
5559 private static final int MSG_UPDATE_CONFIGURATION = 18;
5560 private static final int MSG_PROCESS_INPUT_EVENTS = 19;
5561 private static final int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
5562 private static final int MSG_INVALIDATE_WORLD = 22;
5563 private static final int MSG_WINDOW_MOVED = 23;
5564 private static final int MSG_SYNTHESIZE_INPUT_EVENT = 24;
5565 private static final int MSG_DISPATCH_WINDOW_SHOWN = 25;
5566 private static final int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
5567 private static final int MSG_UPDATE_POINTER_ICON = 27;
5568 private static final int MSG_POINTER_CAPTURE_CHANGED = 28;
5569 private static final int MSG_INSETS_CONTROL_CHANGED = 29;
5570 private static final int MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED = 30;
5571 private static final int MSG_SHOW_INSETS = 31;
5572 private static final int MSG_HIDE_INSETS = 32;
5573 private static final int MSG_REQUEST_SCROLL_CAPTURE = 33;
5574 private static final int MSG_WINDOW_TOUCH_MODE_CHANGED = 34;
5575 private static final int MSG_KEEP_CLEAR_RECTS_CHANGED = 35;
5576 private static final int MSG_REPORT_KEEP_CLEAR_RECTS = 36;
5577
5578
5579 final class ViewRootHandler extends Handler {
5580 @Override
5581 public String getMessageName(Message message) {
5582 switch (message.what) {
5583 case MSG_INVALIDATE:
5584 return "MSG_INVALIDATE";
5585 case MSG_INVALIDATE_RECT:
5586 return "MSG_INVALIDATE_RECT";
5587 case MSG_DIE:
5588 return "MSG_DIE";
5589 case MSG_RESIZED:
5590 return "MSG_RESIZED";
5591 case MSG_RESIZED_REPORT:
5592 return "MSG_RESIZED_REPORT";
5593 case MSG_WINDOW_FOCUS_CHANGED:
5594 return "MSG_WINDOW_FOCUS_CHANGED";
5595 case MSG_DISPATCH_INPUT_EVENT:
5596 return "MSG_DISPATCH_INPUT_EVENT";
5597 case MSG_DISPATCH_APP_VISIBILITY:
5598 return "MSG_DISPATCH_APP_VISIBILITY";
5599 case MSG_DISPATCH_GET_NEW_SURFACE:
5600 return "MSG_DISPATCH_GET_NEW_SURFACE";
5601 case MSG_DISPATCH_KEY_FROM_IME:
5602 return "MSG_DISPATCH_KEY_FROM_IME";
5603 case MSG_DISPATCH_KEY_FROM_AUTOFILL:
5604 return "MSG_DISPATCH_KEY_FROM_AUTOFILL";
5605 case MSG_CHECK_FOCUS:
5606 return "MSG_CHECK_FOCUS";
5607 case MSG_CLOSE_SYSTEM_DIALOGS:
5608 return "MSG_CLOSE_SYSTEM_DIALOGS";
5609 case MSG_DISPATCH_DRAG_EVENT:
5610 return "MSG_DISPATCH_DRAG_EVENT";
5611 case MSG_DISPATCH_DRAG_LOCATION_EVENT:
5612 return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
5613 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
5614 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
5615 case MSG_UPDATE_CONFIGURATION:
5616 return "MSG_UPDATE_CONFIGURATION";
5617 case MSG_PROCESS_INPUT_EVENTS:
5618 return "MSG_PROCESS_INPUT_EVENTS";
5619 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
5620 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
5621 case MSG_WINDOW_MOVED:
5622 return "MSG_WINDOW_MOVED";
5623 case MSG_SYNTHESIZE_INPUT_EVENT:
5624 return "MSG_SYNTHESIZE_INPUT_EVENT";
5625 case MSG_DISPATCH_WINDOW_SHOWN:
5626 return "MSG_DISPATCH_WINDOW_SHOWN";
5627 case MSG_UPDATE_POINTER_ICON:
5628 return "MSG_UPDATE_POINTER_ICON";
5629 case MSG_POINTER_CAPTURE_CHANGED:
5630 return "MSG_POINTER_CAPTURE_CHANGED";
5631 case MSG_INSETS_CONTROL_CHANGED:
5632 return "MSG_INSETS_CONTROL_CHANGED";
5633 case MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED:
5634 return "MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED";
5635 case MSG_SHOW_INSETS:
5636 return "MSG_SHOW_INSETS";
5637 case MSG_HIDE_INSETS:
5638 return "MSG_HIDE_INSETS";
5639 case MSG_WINDOW_TOUCH_MODE_CHANGED:
5640 return "MSG_WINDOW_TOUCH_MODE_CHANGED";
5641 case MSG_KEEP_CLEAR_RECTS_CHANGED:
5642 return "MSG_KEEP_CLEAR_RECTS_CHANGED";
5643 }
5644 return super.getMessageName(message);
5645 }
5646
5647 @Override
5648 public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
5649 if (msg.what == MSG_REQUEST_KEYBOARD_SHORTCUTS && msg.obj == null) {
5650 // Debugging for b/27963013
5651 throw new NullPointerException(
5652 "Attempted to call MSG_REQUEST_KEYBOARD_SHORTCUTS with null receiver:");
5653 }
5654 return super.sendMessageAtTime(msg, uptimeMillis);
5655 }
5656
5657 @Override
5658 public void handleMessage(Message msg) {
5659 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
5660 Trace.traceBegin(Trace.TRACE_TAG_VIEW, getMessageName(msg));
5661 }
5662 try {
5663 handleMessageImpl(msg);
5664 } finally {
5665 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
5666 }
5667 }
5668
5669 private void handleMessageImpl(Message msg) {
5670 switch (msg.what) {
5671 case MSG_INVALIDATE:
5672 ((View) msg.obj).invalidate();
5673 break;
5674 case MSG_INVALIDATE_RECT:
5675 final View.AttachInfo.InvalidateInfo info =
5676 (View.AttachInfo.InvalidateInfo) msg.obj;
5677 info.target.invalidate(info.left, info.top, info.right, info.bottom);
5678 info.recycle();
5679 break;
5680 case MSG_PROCESS_INPUT_EVENTS:
5681 mProcessInputEventsScheduled = false;
5682 doProcessInputEvents();
5683 break;
5684 case MSG_DISPATCH_APP_VISIBILITY:
5685 handleAppVisibility(msg.arg1 != 0);
5686 break;
5687 case MSG_DISPATCH_GET_NEW_SURFACE:
5688 handleGetNewSurface();
5689 break;
5690 case MSG_RESIZED:
5691 case MSG_RESIZED_REPORT: {
5692 final SomeArgs args = (SomeArgs) msg.obj;
5693 mInsetsController.onStateChanged((InsetsState) args.arg3);
5694 handleResized(msg.what, args);
5695 args.recycle();
5696 break;
5697 }
5698 case MSG_INSETS_CONTROL_CHANGED: {
5699 SomeArgs args = (SomeArgs) msg.obj;
5700
5701 // Deliver state change before control change, such that:
5702 // a) When gaining control, controller can compare with server state to evaluate
5703 // whether it needs to run animation.
5704 // b) When loosing control, controller can restore server state by taking last
5705 // dispatched state as truth.
5706 mInsetsController.onStateChanged((InsetsState) args.arg1);
5707 InsetsSourceControl[] controls = (InsetsSourceControl[]) args.arg2;
5708 if (mAdded) {
5709 mInsetsController.onControlsChanged(controls);
5710 } else if (controls != null) {
5711 for (InsetsSourceControl control : controls) {
5712 if (control != null) {
5713 control.release(SurfaceControl::release);
5714 }
5715 }
5716 }
5717 args.recycle();
5718 break;
5719 }
5720 case MSG_SHOW_INSETS: {
5721 if (mView == null) {
5722 Log.e(TAG,
5723 String.format("Calling showInsets(%d,%b) on window that no longer"
5724 + " has views.", msg.arg1, msg.arg2 == 1));
5725 }
5726 clearLowProfileModeIfNeeded(msg.arg1, msg.arg2 == 1);
5727 mInsetsController.show(msg.arg1, msg.arg2 == 1);
5728 break;
5729 }
5730 case MSG_HIDE_INSETS: {
5731 mInsetsController.hide(msg.arg1, msg.arg2 == 1);
5732 break;
5733 }
5734 case MSG_WINDOW_MOVED:
5735 if (mAdded) {
5736 final int w = mWinFrame.width();
5737 final int h = mWinFrame.height();
5738 final int l = msg.arg1;
5739 final int t = msg.arg2;
5740 mTmpFrames.frame.left = l;
5741 mTmpFrames.frame.right = l + w;
5742 mTmpFrames.frame.top = t;
5743 mTmpFrames.frame.bottom = t + h;
5744 setFrame(mTmpFrames.frame);
5745 maybeHandleWindowMove(mWinFrame);
5746 }
5747 break;
5748 case MSG_WINDOW_FOCUS_CHANGED: {
5749 handleWindowFocusChanged();
5750 } break;
5751 case MSG_WINDOW_TOUCH_MODE_CHANGED: {
5752 handleWindowTouchModeChanged();
5753 } break;
5754 case MSG_DIE: {
5755 doDie();
5756 } break;
5757 case MSG_DISPATCH_INPUT_EVENT: {
5758 SomeArgs args = (SomeArgs) msg.obj;
5759 InputEvent event = (InputEvent) args.arg1;
5760 InputEventReceiver receiver = (InputEventReceiver) args.arg2;
5761 enqueueInputEvent(event, receiver, 0, true);
5762 args.recycle();
5763 } break;
5764 case MSG_SYNTHESIZE_INPUT_EVENT: {
5765 InputEvent event = (InputEvent) msg.obj;
5766 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
5767 } break;
5768 case MSG_DISPATCH_KEY_FROM_IME: {
5769 if (LOCAL_LOGV) {
5770 Log.v(TAG, "Dispatching key " + msg.obj + " from IME to " + mView);
5771 }
5772 KeyEvent event = (KeyEvent) msg.obj;
5773 if ((event.getFlags() & KeyEvent.FLAG_FROM_SYSTEM) != 0) {
5774 // The IME is trying to say this event is from the
5775 // system! Bad bad bad!
5776 //noinspection UnusedAssignment
5777 event = KeyEvent.changeFlags(event,
5778 event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM);
5779 }
5780 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
5781 } break;
5782 case MSG_DISPATCH_KEY_FROM_AUTOFILL: {
5783 if (LOCAL_LOGV) {
5784 Log.v(TAG, "Dispatching key " + msg.obj + " from Autofill to " + mView);
5785 }
5786 KeyEvent event = (KeyEvent) msg.obj;
5787 enqueueInputEvent(event, null, 0, true);
5788 } break;
5789 case MSG_CHECK_FOCUS: {
5790 getImeFocusController().checkFocus(false, true);
5791 } break;
5792 case MSG_CLOSE_SYSTEM_DIALOGS: {
5793 if (mView != null) {
5794 mView.onCloseSystemDialogs((String) msg.obj);
5795 }
5796 } break;
5797 case MSG_DISPATCH_DRAG_EVENT: {
5798 } // fall through
5799 case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
5800 DragEvent event = (DragEvent) msg.obj;
5801 // only present when this app called startDrag()
5802 event.mLocalState = mLocalDragState;
5803 handleDragEvent(event);
5804 } break;
5805 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
5806 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
5807 } break;
5808 case MSG_UPDATE_CONFIGURATION: {
5809 Configuration config = (Configuration) msg.obj;
5810 if (config.isOtherSeqNewer(
5811 mLastReportedMergedConfiguration.getMergedConfiguration())) {
5812 // If we already have a newer merged config applied - use its global part.
5813 config = mLastReportedMergedConfiguration.getGlobalConfiguration();
5814 }
5815
5816 // Use the newer global config and last reported override config.
5817 mPendingMergedConfiguration.setConfiguration(config,
5818 mLastReportedMergedConfiguration.getOverrideConfiguration());
5819
5820 performConfigurationChange(new MergedConfiguration(mPendingMergedConfiguration),
5821 false /* force */, INVALID_DISPLAY /* same display */);
5822 } break;
5823 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
5824 setAccessibilityFocus(null, null);
5825 } break;
5826 case MSG_INVALIDATE_WORLD: {
5827 if (mView != null) {
5828 invalidateWorld(mView);
5829 }
5830 } break;
5831 case MSG_DISPATCH_WINDOW_SHOWN: {
5832 handleDispatchWindowShown();
5833 } break;
5834 case MSG_REQUEST_KEYBOARD_SHORTCUTS: {
5835 final IResultReceiver receiver = (IResultReceiver) msg.obj;
5836 final int deviceId = msg.arg1;
5837 handleRequestKeyboardShortcuts(receiver, deviceId);
5838 } break;
5839 case MSG_UPDATE_POINTER_ICON: {
5840 MotionEvent event = (MotionEvent) msg.obj;
5841 resetPointerIcon(event);
5842 } break;
5843 case MSG_POINTER_CAPTURE_CHANGED: {
5844 final boolean hasCapture = msg.arg1 != 0;
5845 handlePointerCaptureChanged(hasCapture);
5846 } break;
5847 case MSG_SYSTEM_GESTURE_EXCLUSION_CHANGED: {
5848 systemGestureExclusionChanged();
5849 } break;
5850 case MSG_KEEP_CLEAR_RECTS_CHANGED: {
5851 keepClearRectsChanged();
5852 } break;
5853 case MSG_REPORT_KEEP_CLEAR_RECTS: {
5854 reportKeepClearAreasChanged();
5855 } break;
5856 case MSG_REQUEST_SCROLL_CAPTURE:
5857 handleScrollCaptureRequest((IScrollCaptureResponseListener) msg.obj);
5858 break;
5859 }
5860 }
5861 }
5862
5863 final ViewRootHandler mHandler = new ViewRootHandler();
5864
5865 /**
5866 * Something in the current window tells us we need to change the touch mode. For
5867 * example, we are not in touch mode, and the user touches the screen.
5868 *
5869 * If the touch mode has changed, tell the window manager, and handle it locally.
5870 *
5871 * @param inTouchMode Whether we want to be in touch mode.
5872 * @return True if the touch mode changed and focus changed was changed as a result
5873 */
5874 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5875 boolean ensureTouchMode(boolean inTouchMode) {
5876 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
5877 + "touch mode is " + mAttachInfo.mInTouchMode);
5878 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
5879
5880 // tell the window manager
5881 try {
5882 mWindowSession.setInTouchMode(inTouchMode);
5883 } catch (RemoteException e) {
5884 throw new RuntimeException(e);
5885 }
5886
5887 // handle the change
5888 return ensureTouchModeLocally(inTouchMode);
5889 }
5890
5891 /**
5892 * Ensure that the touch mode for this window is set, and if it is changing,
5893 * take the appropriate action.
5894 * @param inTouchMode Whether we want to be in touch mode.
5895 * @return True if the touch mode changed and focus changed was changed as a result
5896 */
5897 private boolean ensureTouchModeLocally(boolean inTouchMode) {
5898 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
5899 + "touch mode is " + mAttachInfo.mInTouchMode);
5900
5901 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
5902
5903 mAttachInfo.mInTouchMode = inTouchMode;
5904 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
5905
5906 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
5907 }
5908
5909 private boolean enterTouchMode() {
5910 if (mView != null && mView.hasFocus()) {
5911 // note: not relying on mFocusedView here because this could
5912 // be when the window is first being added, and mFocused isn't
5913 // set yet.
5914 final View focused = mView.findFocus();
5915 if (focused != null && !focused.isFocusableInTouchMode()) {
5916 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
5917 if (ancestorToTakeFocus != null) {
5918 // there is an ancestor that wants focus after its
5919 // descendants that is focusable in touch mode.. give it
5920 // focus
5921 return ancestorToTakeFocus.requestFocus();
5922 } else {
5923 // There's nothing to focus. Clear and propagate through the
5924 // hierarchy, but don't attempt to place new focus.
5925 focused.clearFocusInternal(null, true, false);
5926 return true;
5927 }
5928 }
5929 }
5930 return false;
5931 }
5932
5933 /**
5934 * Find an ancestor of focused that wants focus after its descendants and is
5935 * focusable in touch mode.
5936 * @param focused The currently focused view.
5937 * @return An appropriate view, or null if no such view exists.
5938 */
5939 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
5940 ViewParent parent = focused.getParent();
5941 while (parent instanceof ViewGroup) {
5942 final ViewGroup vgParent = (ViewGroup) parent;
5943 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
5944 && vgParent.isFocusableInTouchMode()) {
5945 return vgParent;
5946 }
5947 if (vgParent.isRootNamespace()) {
5948 return null;
5949 } else {
5950 parent = vgParent.getParent();
5951 }
5952 }
5953 return null;
5954 }
5955
5956 private boolean leaveTouchMode() {
5957 if (mView != null) {
5958 if (mView.hasFocus()) {
5959 View focusedView = mView.findFocus();
5960 if (!(focusedView instanceof ViewGroup)) {
5961 // some view has focus, let it keep it
5962 return false;
5963 } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
5964 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
5965 // some view group has focus, and doesn't prefer its children
5966 // over itself for focus, so let them keep it.
5967 return false;
5968 }
5969 }
5970
5971 // find the best view to give focus to in this brave new non-touch-mode
5972 // world
5973 return mView.restoreDefaultFocus();
5974 }
5975 return false;
5976 }
5977
5978 /**
5979 * Base class for implementing a stage in the chain of responsibility
5980 * for processing input events.
5981 * <p>
5982 * Events are delivered to the stage by the {@link #deliver} method. The stage
5983 * then has the choice of finishing the event or forwarding it to the next stage.
5984 * </p>
5985 */
5986 abstract class InputStage {
5987 private final InputStage mNext;
5988
5989 protected static final int FORWARD = 0;
5990 protected static final int FINISH_HANDLED = 1;
5991 protected static final int FINISH_NOT_HANDLED = 2;
5992
5993 private String mTracePrefix;
5994
5995 /**
5996 * Creates an input stage.
5997 * @param next The next stage to which events should be forwarded.
5998 */
5999 public InputStage(InputStage next) {
6000 mNext = next;
6001 }
6002
6003 /**
6004 * Delivers an event to be processed.
6005 */
6006 public final void deliver(QueuedInputEvent q) {
6007 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
6008 forward(q);
6009 } else if (shouldDropInputEvent(q)) {
6010 finish(q, false);
6011 } else {
6012 traceEvent(q, Trace.TRACE_TAG_VIEW);
6013 final int result;
6014 try {
6015 result = onProcess(q);
6016 } finally {
6017 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
6018 }
6019 apply(q, result);
6020 }
6021 }
6022
6023 /**
6024 * Marks the input event as finished then forwards it to the next stage.
6025 */
6026 protected void finish(QueuedInputEvent q, boolean handled) {
6027 q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
6028 if (handled) {
6029 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
6030 }
6031 forward(q);
6032 }
6033
6034 /**
6035 * Forwards the event to the next stage.
6036 */
6037 protected void forward(QueuedInputEvent q) {
6038 onDeliverToNext(q);
6039 }
6040
6041 /**
6042 * Applies a result code from {@link #onProcess} to the specified event.
6043 */
6044 protected void apply(QueuedInputEvent q, int result) {
6045 if (result == FORWARD) {
6046 forward(q);
6047 } else if (result == FINISH_HANDLED) {
6048 finish(q, true);
6049 } else if (result == FINISH_NOT_HANDLED) {
6050 finish(q, false);
6051 } else {
6052 throw new IllegalArgumentException("Invalid result: " + result);
6053 }
6054 }
6055
6056 /**
6057 * Called when an event is ready to be processed.
6058 * @return A result code indicating how the event was handled.
6059 */
6060 protected int onProcess(QueuedInputEvent q) {
6061 return FORWARD;
6062 }
6063
6064 /**
6065 * Called when an event is being delivered to the next stage.
6066 */
6067 protected void onDeliverToNext(QueuedInputEvent q) {
6068 if (DEBUG_INPUT_STAGES) {
6069 Log.v(mTag, "Done with " + getClass().getSimpleName() + ". " + q);
6070 }
6071 if (mNext != null) {
6072 mNext.deliver(q);
6073 } else {
6074 finishInputEvent(q);
6075 }
6076 }
6077
6078 protected void onWindowFocusChanged(boolean hasWindowFocus) {
6079 if (mNext != null) {
6080 mNext.onWindowFocusChanged(hasWindowFocus);
6081 }
6082 }
6083
6084 protected void onDetachedFromWindow() {
6085 if (mNext != null) {
6086 mNext.onDetachedFromWindow();
6087 }
6088 }
6089
6090 protected boolean shouldDropInputEvent(QueuedInputEvent q) {
6091 if (mView == null || !mAdded) {
6092 Slog.w(mTag, "Dropping event due to root view being removed: " + q.mEvent);
6093 return true;
6094 }
6095
6096 // Find a reason for dropping or canceling the event.
6097 final String reason;
6098 if (!mAttachInfo.mHasWindowFocus
6099 && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)
6100 && !isAutofillUiShowing()) {
6101 // This is a non-pointer event and the window doesn't currently have input focus
6102 // This could be an event that came back from the previous stage
6103 // but the window has lost focus or stopped in the meantime.
6104 reason = "no window focus";
6105 } else if (mStopped) {
6106 reason = "window is stopped";
6107 } else if (mIsAmbientMode
6108 && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_BUTTON)) {
6109 reason = "non-button event in ambient mode";
6110 } else if (mPausedForTransition && !isBack(q.mEvent)) {
6111 reason = "paused for transition";
6112 } else {
6113 // Most common path: no reason to drop or cancel the event
6114 return false;
6115 }
6116
6117 if (isTerminalInputEvent(q.mEvent)) {
6118 // Don't drop terminal input events, however mark them as canceled.
6119 q.mEvent.cancel();
6120 Slog.w(mTag, "Cancelling event (" + reason + "):" + q.mEvent);
6121 return false;
6122 }
6123
6124 // Drop non-terminal input events.
6125 Slog.w(mTag, "Dropping event (" + reason + "):" + q.mEvent);
6126 return true;
6127 }
6128
6129 void dump(String prefix, PrintWriter writer) {
6130 if (mNext != null) {
6131 mNext.dump(prefix, writer);
6132 }
6133 }
6134
6135 boolean isBack(InputEvent event) {
6136 if (event instanceof KeyEvent) {
6137 return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;
6138 } else {
6139 return false;
6140 }
6141 }
6142
6143 private void traceEvent(QueuedInputEvent q, long traceTag) {
6144 if (!Trace.isTagEnabled(traceTag)) {
6145 return;
6146 }
6147
6148 if (mTracePrefix == null) {
6149 mTracePrefix = getClass().getSimpleName();
6150 }
6151 Trace.traceBegin(traceTag, mTracePrefix + " id=0x"
6152 + Integer.toHexString(q.mEvent.getId()));
6153 }
6154 }
6155
6156 /**
6157 * Base class for implementing an input pipeline stage that supports
6158 * asynchronous and out-of-order processing of input events.
6159 * <p>
6160 * In addition to what a normal input stage can do, an asynchronous
6161 * input stage may also defer an input event that has been delivered to it
6162 * and finish or forward it later.
6163 * </p>
6164 */
6165 abstract class AsyncInputStage extends InputStage {
6166 private final String mTraceCounter;
6167
6168 private QueuedInputEvent mQueueHead;
6169 private QueuedInputEvent mQueueTail;
6170 private int mQueueLength;
6171
6172 protected static final int DEFER = 3;
6173
6174 /**
6175 * Creates an asynchronous input stage.
6176 * @param next The next stage to which events should be forwarded.
6177 * @param traceCounter The name of a counter to record the size of
6178 * the queue of pending events.
6179 */
6180 public AsyncInputStage(InputStage next, String traceCounter) {
6181 super(next);
6182 mTraceCounter = traceCounter;
6183 }
6184
6185 /**
6186 * Marks the event as deferred, which is to say that it will be handled
6187 * asynchronously. The caller is responsible for calling {@link #forward}
6188 * or {@link #finish} later when it is done handling the event.
6189 */
6190 protected void defer(QueuedInputEvent q) {
6191 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
6192 enqueue(q);
6193 }
6194
6195 @Override
6196 protected void forward(QueuedInputEvent q) {
6197 // Clear the deferred flag.
6198 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
6199
6200 // Fast path if the queue is empty.
6201 QueuedInputEvent curr = mQueueHead;
6202 if (curr == null) {
6203 super.forward(q);
6204 return;
6205 }
6206
6207 // Determine whether the event must be serialized behind any others
6208 // before it can be delivered to the next stage. This is done because
6209 // deferred events might be handled out of order by the stage.
6210 final int deviceId = q.mEvent.getDeviceId();
6211 QueuedInputEvent prev = null;
6212 boolean blocked = false;
6213 while (curr != null && curr != q) {
6214 if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
6215 blocked = true;
6216 }
6217 prev = curr;
6218 curr = curr.mNext;
6219 }
6220
6221 // If the event is blocked, then leave it in the queue to be delivered later.
6222 // Note that the event might not yet be in the queue if it was not previously
6223 // deferred so we will enqueue it if needed.
6224 if (blocked) {
6225 if (curr == null) {
6226 enqueue(q);
6227 }
6228 return;
6229 }
6230
6231 // The event is not blocked. Deliver it immediately.
6232 if (curr != null) {
6233 curr = curr.mNext;
6234 dequeue(q, prev);
6235 }
6236 super.forward(q);
6237
6238 // Dequeuing this event may have unblocked successors. Deliver them.
6239 while (curr != null) {
6240 if (deviceId == curr.mEvent.getDeviceId()) {
6241 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
6242 break;
6243 }
6244 QueuedInputEvent next = curr.mNext;
6245 dequeue(curr, prev);
6246 super.forward(curr);
6247 curr = next;
6248 } else {
6249 prev = curr;
6250 curr = curr.mNext;
6251 }
6252 }
6253 }
6254
6255 @Override
6256 protected void apply(QueuedInputEvent q, int result) {
6257 if (result == DEFER) {
6258 defer(q);
6259 } else {
6260 super.apply(q, result);
6261 }
6262 }
6263
6264 private void enqueue(QueuedInputEvent q) {
6265 if (mQueueTail == null) {
6266 mQueueHead = q;
6267 mQueueTail = q;
6268 } else {
6269 mQueueTail.mNext = q;
6270 mQueueTail = q;
6271 }
6272
6273 mQueueLength += 1;
6274 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
6275 }
6276
6277 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
6278 if (prev == null) {
6279 mQueueHead = q.mNext;
6280 } else {
6281 prev.mNext = q.mNext;
6282 }
6283 if (mQueueTail == q) {
6284 mQueueTail = prev;
6285 }
6286 q.mNext = null;
6287
6288 mQueueLength -= 1;
6289 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
6290 }
6291
6292 @Override
6293 void dump(String prefix, PrintWriter writer) {
6294 writer.print(prefix);
6295 writer.print(getClass().getName());
6296 writer.print(": mQueueLength=");
6297 writer.println(mQueueLength);
6298
6299 super.dump(prefix, writer);
6300 }
6301 }
6302
6303 /**
6304 * Delivers pre-ime input events to a native activity.
6305 * Does not support pointer events.
6306 */
6307 final class NativePreImeInputStage extends AsyncInputStage
6308 implements InputQueue.FinishedInputEventCallback {
6309 public NativePreImeInputStage(InputStage next, String traceCounter) {
6310 super(next, traceCounter);
6311 }
6312
6313 @Override
6314 protected int onProcess(QueuedInputEvent q) {
6315 if (q.mEvent instanceof KeyEvent) {
6316 final KeyEvent event = (KeyEvent) q.mEvent;
6317
6318 // If the new back dispatch is enabled, intercept KEYCODE_BACK before it reaches the
6319 // view tree or IME, and invoke the appropriate {@link OnBackInvokedCallback}.
6320 if (isBack(event)
6321 && mContext != null
6322 && WindowOnBackInvokedDispatcher.isOnBackInvokedCallbackEnabled(mContext)) {
6323 OnBackInvokedCallback topCallback =
6324 getOnBackInvokedDispatcher().getTopCallback();
6325 if (event.getAction() == KeyEvent.ACTION_UP) {
6326 if (topCallback != null) {
6327 topCallback.onBackInvoked();
6328 return FINISH_HANDLED;
6329 }
6330 } else {
6331 // Drop other actions such as {@link KeyEvent.ACTION_DOWN}.
6332 return FINISH_NOT_HANDLED;
6333 }
6334 }
6335 }
6336
6337 if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
6338 mInputQueue.sendInputEvent(q.mEvent, q, true, this);
6339 return DEFER;
6340 }
6341 return FORWARD;
6342 }
6343
6344 @Override
6345 public void onFinishedInputEvent(Object token, boolean handled) {
6346 QueuedInputEvent q = (QueuedInputEvent)token;
6347 if (handled) {
6348 finish(q, true);
6349 return;
6350 }
6351 forward(q);
6352 }
6353 }
6354
6355 /**
6356 * Delivers pre-ime input events to the view hierarchy.
6357 * Does not support pointer events.
6358 */
6359 final class ViewPreImeInputStage extends InputStage {
6360 public ViewPreImeInputStage(InputStage next) {
6361 super(next);
6362 }
6363
6364 @Override
6365 protected int onProcess(QueuedInputEvent q) {
6366 if (q.mEvent instanceof KeyEvent) {
6367 return processKeyEvent(q);
6368 }
6369 return FORWARD;
6370 }
6371
6372 private int processKeyEvent(QueuedInputEvent q) {
6373 final KeyEvent event = (KeyEvent)q.mEvent;
6374 if (mView.dispatchKeyEventPreIme(event)) {
6375 return FINISH_HANDLED;
6376 }
6377 return FORWARD;
6378 }
6379 }
6380
6381 /**
6382 * Delivers input events to the ime.
6383 * Does not support pointer events.
6384 */
6385 final class ImeInputStage extends AsyncInputStage
6386 implements InputMethodManager.FinishedInputEventCallback {
6387 public ImeInputStage(InputStage next, String traceCounter) {
6388 super(next, traceCounter);
6389 }
6390
6391 @Override
6392 protected int onProcess(QueuedInputEvent q) {
6393 final int result = mImeFocusController.onProcessImeInputStage(
6394 q, q.mEvent, mWindowAttributes, this);
6395 switch (result) {
6396 case InputMethodManager.DISPATCH_IN_PROGRESS:
6397 // callback will be invoked later
6398 return DEFER;
6399 case InputMethodManager.DISPATCH_NOT_HANDLED:
6400 // The IME could not handle it, so skip along to the next InputStage
6401 return FORWARD;
6402 case InputMethodManager.DISPATCH_HANDLED:
6403 return FINISH_HANDLED;
6404 default:
6405 throw new IllegalStateException("Unexpected result=" + result);
6406 }
6407 }
6408
6409 @Override
6410 public void onFinishedInputEvent(Object token, boolean handled) {
6411 QueuedInputEvent q = (QueuedInputEvent)token;
6412 if (handled) {
6413 finish(q, true);
6414 return;
6415 }
6416 forward(q);
6417 }
6418 }
6419
6420 /**
6421 * Performs early processing of post-ime input events.
6422 */
6423 final class EarlyPostImeInputStage extends InputStage {
6424 public EarlyPostImeInputStage(InputStage next) {
6425 super(next);
6426 }
6427
6428 @Override
6429 protected int onProcess(QueuedInputEvent q) {
6430 if (q.mEvent instanceof KeyEvent) {
6431 return processKeyEvent(q);
6432 } else if (q.mEvent instanceof MotionEvent) {
6433 return processMotionEvent(q);
6434 }
6435 return FORWARD;
6436 }
6437
6438 private int processKeyEvent(QueuedInputEvent q) {
6439 final KeyEvent event = (KeyEvent)q.mEvent;
6440
6441 if (mAttachInfo.mTooltipHost != null) {
6442 mAttachInfo.mTooltipHost.handleTooltipKey(event);
6443 }
6444
6445 // If the key's purpose is to exit touch mode then we consume it
6446 // and consider it handled.
6447 if (checkForLeavingTouchModeAndConsume(event)) {
6448 return FINISH_HANDLED;
6449 }
6450
6451 // Make sure the fallback event policy sees all keys that will be
6452 // delivered to the view hierarchy.
6453 mFallbackEventHandler.preDispatchKeyEvent(event);
6454 return FORWARD;
6455 }
6456
6457 private int processMotionEvent(QueuedInputEvent q) {
6458 final MotionEvent event = (MotionEvent) q.mEvent;
6459
6460 if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
6461 return processPointerEvent(q);
6462 }
6463
6464 // If the motion event is from an absolute position device, exit touch mode
6465 final int action = event.getActionMasked();
6466 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
6467 if (event.isFromSource(InputDevice.SOURCE_CLASS_POSITION)) {
6468 ensureTouchMode(false);
6469 }
6470 }
6471 return FORWARD;
6472 }
6473
6474 private int processPointerEvent(QueuedInputEvent q) {
6475 final MotionEvent event = (MotionEvent)q.mEvent;
6476
6477 // Translate the pointer event for compatibility, if needed.
6478 if (mTranslator != null) {
6479 mTranslator.translateEventInScreenToAppWindow(event);
6480 }
6481
6482 // Enter touch mode on down or scroll from any type of a device.
6483 final int action = event.getAction();
6484 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
6485 ensureTouchMode(true);
6486 }
6487
6488 if (action == MotionEvent.ACTION_DOWN) {
6489 // Upon motion event within app window, close autofill ui.
6490 AutofillManager afm = getAutofillManager();
6491 if (afm != null) {
6492 afm.requestHideFillUi();
6493 }
6494 }
6495
6496 if (action == MotionEvent.ACTION_DOWN && mAttachInfo.mTooltipHost != null) {
6497 mAttachInfo.mTooltipHost.hideTooltip();
6498 }
6499
6500 // Offset the scroll position.
6501 if (mCurScrollY != 0) {
6502 event.offsetLocation(0, mCurScrollY);
6503 }
6504
6505 // Remember the touch position for possible drag-initiation.
6506 if (event.isTouchEvent()) {
6507 mLastTouchPoint.x = event.getRawX();
6508 mLastTouchPoint.y = event.getRawY();
6509 mLastTouchSource = event.getSource();
6510 }
6511 return FORWARD;
6512 }
6513 }
6514
6515 /**
6516 * Delivers post-ime input events to a native activity.
6517 */
6518 final class NativePostImeInputStage extends AsyncInputStage
6519 implements InputQueue.FinishedInputEventCallback {
6520 public NativePostImeInputStage(InputStage next, String traceCounter) {
6521 super(next, traceCounter);
6522 }
6523
6524 @Override
6525 protected int onProcess(QueuedInputEvent q) {
6526 if (mInputQueue != null) {
6527 mInputQueue.sendInputEvent(q.mEvent, q, false, this);
6528 return DEFER;
6529 }
6530 return FORWARD;
6531 }
6532
6533 @Override
6534 public void onFinishedInputEvent(Object token, boolean handled) {
6535 QueuedInputEvent q = (QueuedInputEvent)token;
6536 if (handled) {
6537 finish(q, true);
6538 return;
6539 }
6540 forward(q);
6541 }
6542 }
6543
6544 /**
6545 * Delivers post-ime input events to the view hierarchy.
6546 */
6547 final class ViewPostImeInputStage extends InputStage {
6548 public ViewPostImeInputStage(InputStage next) {
6549 super(next);
6550 }
6551
6552 @Override
6553 protected int onProcess(QueuedInputEvent q) {
6554 if (q.mEvent instanceof KeyEvent) {
6555 return processKeyEvent(q);
6556 } else {
6557 final int source = q.mEvent.getSource();
6558 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6559 return processPointerEvent(q);
6560 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
6561 return processTrackballEvent(q);
6562 } else {
6563 return processGenericMotionEvent(q);
6564 }
6565 }
6566 }
6567
6568 @Override
6569 protected void onDeliverToNext(QueuedInputEvent q) {
6570 if (mUnbufferedInputDispatch
6571 && q.mEvent instanceof MotionEvent
6572 && ((MotionEvent)q.mEvent).isTouchEvent()
6573 && isTerminalInputEvent(q.mEvent)) {
6574 mUnbufferedInputDispatch = false;
6575 scheduleConsumeBatchedInput();
6576 }
6577 super.onDeliverToNext(q);
6578 }
6579
6580 private boolean performFocusNavigation(KeyEvent event) {
6581 int direction = 0;
6582 switch (event.getKeyCode()) {
6583 case KeyEvent.KEYCODE_DPAD_LEFT:
6584 if (event.hasNoModifiers()) {
6585 direction = View.FOCUS_LEFT;
6586 }
6587 break;
6588 case KeyEvent.KEYCODE_DPAD_RIGHT:
6589 if (event.hasNoModifiers()) {
6590 direction = View.FOCUS_RIGHT;
6591 }
6592 break;
6593 case KeyEvent.KEYCODE_DPAD_UP:
6594 if (event.hasNoModifiers()) {
6595 direction = View.FOCUS_UP;
6596 }
6597 break;
6598 case KeyEvent.KEYCODE_DPAD_DOWN:
6599 if (event.hasNoModifiers()) {
6600 direction = View.FOCUS_DOWN;
6601 }
6602 break;
6603 case KeyEvent.KEYCODE_TAB:
6604 if (event.hasNoModifiers()) {
6605 direction = View.FOCUS_FORWARD;
6606 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
6607 direction = View.FOCUS_BACKWARD;
6608 }
6609 break;
6610 }
6611 if (direction != 0) {
6612 View focused = mView.findFocus();
6613 if (focused != null) {
6614 View v = focused.focusSearch(direction);
6615 if (v != null && v != focused) {
6616 // do the math the get the interesting rect
6617 // of previous focused into the coord system of
6618 // newly focused view
6619 focused.getFocusedRect(mTempRect);
6620 if (mView instanceof ViewGroup) {
6621 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
6622 focused, mTempRect);
6623 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
6624 v, mTempRect);
6625 }
6626 if (v.requestFocus(direction, mTempRect)) {
6627 boolean isFastScrolling = event.getRepeatCount() > 0;
6628 playSoundEffect(
6629 SoundEffectConstants.getConstantForFocusDirection(direction,
6630 isFastScrolling));
6631 return true;
6632 }
6633 }
6634
6635 // Give the focused view a last chance to handle the dpad key.
6636 if (mView.dispatchUnhandledMove(focused, direction)) {
6637 return true;
6638 }
6639 } else {
6640 if (mView.restoreDefaultFocus()) {
6641 return true;
6642 }
6643 }
6644 }
6645 return false;
6646 }
6647
6648 private boolean performKeyboardGroupNavigation(int direction) {
6649 final View focused = mView.findFocus();
6650 if (focused == null && mView.restoreDefaultFocus()) {
6651 return true;
6652 }
6653 View cluster = focused == null ? keyboardNavigationClusterSearch(null, direction)
6654 : focused.keyboardNavigationClusterSearch(null, direction);
6655
6656 // Since requestFocus only takes "real" focus directions (and therefore also
6657 // restoreFocusInCluster), convert forward/backward focus into FOCUS_DOWN.
6658 int realDirection = direction;
6659 if (direction == View.FOCUS_FORWARD || direction == View.FOCUS_BACKWARD) {
6660 realDirection = View.FOCUS_DOWN;
6661 }
6662
6663 if (cluster != null && cluster.isRootNamespace()) {
6664 // the default cluster. Try to find a non-clustered view to focus.
6665 if (cluster.restoreFocusNotInCluster()) {
6666 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
6667 return true;
6668 }
6669 // otherwise skip to next actual cluster
6670 cluster = keyboardNavigationClusterSearch(null, direction);
6671 }
6672
6673 if (cluster != null && cluster.restoreFocusInCluster(realDirection)) {
6674 playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
6675 return true;
6676 }
6677
6678 return false;
6679 }
6680
6681 private int processKeyEvent(QueuedInputEvent q) {
6682 final KeyEvent event = (KeyEvent)q.mEvent;
6683
6684 if (mUnhandledKeyManager.preViewDispatch(event)) {
6685 return FINISH_HANDLED;
6686 }
6687
6688 // Deliver the key to the view hierarchy.
6689 if (mView.dispatchKeyEvent(event)) {
6690 return FINISH_HANDLED;
6691 }
6692
6693 if (shouldDropInputEvent(q)) {
6694 return FINISH_NOT_HANDLED;
6695 }
6696
6697 // This dispatch is for windows that don't have a Window.Callback. Otherwise,
6698 // the Window.Callback usually will have already called this (see
6699 // DecorView.superDispatchKeyEvent) leaving this call a no-op.
6700 if (mUnhandledKeyManager.dispatch(mView, event)) {
6701 return FINISH_HANDLED;
6702 }
6703
6704 int groupNavigationDirection = 0;
6705
6706 if (event.getAction() == KeyEvent.ACTION_DOWN
6707 && event.getKeyCode() == KeyEvent.KEYCODE_TAB) {
6708 if (KeyEvent.metaStateHasModifiers(event.getMetaState(), KeyEvent.META_META_ON)) {
6709 groupNavigationDirection = View.FOCUS_FORWARD;
6710 } else if (KeyEvent.metaStateHasModifiers(event.getMetaState(),
6711 KeyEvent.META_META_ON | KeyEvent.META_SHIFT_ON)) {
6712 groupNavigationDirection = View.FOCUS_BACKWARD;
6713 }
6714 }
6715
6716 // If a modifier is held, try to interpret the key as a shortcut.
6717 if (event.getAction() == KeyEvent.ACTION_DOWN
6718 && !KeyEvent.metaStateHasNoModifiers(event.getMetaState())
6719 && event.getRepeatCount() == 0
6720 && !KeyEvent.isModifierKey(event.getKeyCode())
6721 && groupNavigationDirection == 0) {
6722 if (mView.dispatchKeyShortcutEvent(event)) {
6723 return FINISH_HANDLED;
6724 }
6725 if (shouldDropInputEvent(q)) {
6726 return FINISH_NOT_HANDLED;
6727 }
6728 }
6729
6730 // Apply the fallback event policy.
6731 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
6732 return FINISH_HANDLED;
6733 }
6734 if (shouldDropInputEvent(q)) {
6735 return FINISH_NOT_HANDLED;
6736 }
6737
6738 // Handle automatic focus changes.
6739 if (event.getAction() == KeyEvent.ACTION_DOWN) {
6740 if (groupNavigationDirection != 0) {
6741 if (performKeyboardGroupNavigation(groupNavigationDirection)) {
6742 return FINISH_HANDLED;
6743 }
6744 } else {
6745 if (performFocusNavigation(event)) {
6746 return FINISH_HANDLED;
6747 }
6748 }
6749 }
6750 return FORWARD;
6751 }
6752
6753 private int processPointerEvent(QueuedInputEvent q) {
6754 final MotionEvent event = (MotionEvent)q.mEvent;
6755 mHandwritingInitiator.onTouchEvent(event);
6756
6757 mAttachInfo.mUnbufferedDispatchRequested = false;
6758 mAttachInfo.mHandlingPointerEvent = true;
6759 boolean handled = mView.dispatchPointerEvent(event);
6760 maybeUpdatePointerIcon(event);
6761 maybeUpdateTooltip(event);
6762 mAttachInfo.mHandlingPointerEvent = false;
6763 if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
6764 mUnbufferedInputDispatch = true;
6765 if (mConsumeBatchedInputScheduled) {
6766 scheduleConsumeBatchedInputImmediately();
6767 }
6768 }
6769 return handled ? FINISH_HANDLED : FORWARD;
6770 }
6771
6772 private void maybeUpdatePointerIcon(MotionEvent event) {
6773 if (event.getPointerCount() == 1 && event.isFromSource(InputDevice.SOURCE_MOUSE)) {
6774 if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
6775 || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
6776 // Other apps or the window manager may change the icon type outside of
6777 // this app, therefore the icon type has to be reset on enter/exit event.
6778 mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
6779 }
6780
6781 if (event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
6782 if (!updatePointerIcon(event) &&
6783 event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE) {
6784 mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
6785 }
6786 }
6787 }
6788 }
6789
6790 private int processTrackballEvent(QueuedInputEvent q) {
6791 final MotionEvent event = (MotionEvent)q.mEvent;
6792
6793 if (event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) {
6794 if (!hasPointerCapture() || mView.dispatchCapturedPointerEvent(event)) {
6795 return FINISH_HANDLED;
6796 }
6797 }
6798
6799 if (mView.dispatchTrackballEvent(event)) {
6800 return FINISH_HANDLED;
6801 }
6802 return FORWARD;
6803 }
6804
6805 private int processGenericMotionEvent(QueuedInputEvent q) {
6806 final MotionEvent event = (MotionEvent)q.mEvent;
6807
6808 if (event.isFromSource(InputDevice.SOURCE_TOUCHPAD)) {
6809 if (hasPointerCapture() && mView.dispatchCapturedPointerEvent(event)) {
6810 return FINISH_HANDLED;
6811 }
6812 }
6813
6814 // Deliver the event to the view.
6815 if (mView.dispatchGenericMotionEvent(event)) {
6816 return FINISH_HANDLED;
6817 }
6818 return FORWARD;
6819 }
6820 }
6821
6822 private void resetPointerIcon(MotionEvent event) {
6823 mPointerIconType = PointerIcon.TYPE_NOT_SPECIFIED;
6824 updatePointerIcon(event);
6825 }
6826
6827 private boolean updatePointerIcon(MotionEvent event) {
6828 final int pointerIndex = 0;
6829 final float x = event.getX(pointerIndex);
6830 final float y = event.getY(pointerIndex);
6831 if (mView == null) {
6832 // E.g. click outside a popup to dismiss it
6833 Slog.d(mTag, "updatePointerIcon called after view was removed");
6834 return false;
6835 }
6836 if (x < 0 || x >= mView.getWidth() || y < 0 || y >= mView.getHeight()) {
6837 // E.g. when moving window divider with mouse
6838 Slog.d(mTag, "updatePointerIcon called with position out of bounds");
6839 return false;
6840 }
6841 final PointerIcon pointerIcon = mView.onResolvePointerIcon(event, pointerIndex);
6842 final int pointerType = (pointerIcon != null) ?
6843 pointerIcon.getType() : PointerIcon.TYPE_DEFAULT;
6844
6845 if (mPointerIconType != pointerType) {
6846 mPointerIconType = pointerType;
6847 mCustomPointerIcon = null;
6848 if (mPointerIconType != PointerIcon.TYPE_CUSTOM) {
6849 InputManager.getInstance().setPointerIconType(pointerType);
6850 return true;
6851 }
6852 }
6853 if (mPointerIconType == PointerIcon.TYPE_CUSTOM &&
6854 !pointerIcon.equals(mCustomPointerIcon)) {
6855 mCustomPointerIcon = pointerIcon;
6856 InputManager.getInstance().setCustomPointerIcon(mCustomPointerIcon);
6857 }
6858 return true;
6859 }
6860
6861 private void maybeUpdateTooltip(MotionEvent event) {
6862 if (event.getPointerCount() != 1) {
6863 return;
6864 }
6865 final int action = event.getActionMasked();
6866 if (action != MotionEvent.ACTION_HOVER_ENTER
6867 && action != MotionEvent.ACTION_HOVER_MOVE
6868 && action != MotionEvent.ACTION_HOVER_EXIT) {
6869 return;
6870 }
6871 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6872 if (manager.isEnabled() && manager.isTouchExplorationEnabled()) {
6873 return;
6874 }
6875 if (mView == null) {
6876 Slog.d(mTag, "maybeUpdateTooltip called after view was removed");
6877 return;
6878 }
6879 mView.dispatchTooltipHoverEvent(event);
6880 }
6881
6882 @Nullable
6883 private View getFocusedViewOrNull() {
6884 return mView != null ? mView.findFocus() : null;
6885 }
6886
6887 /**
6888 * Performs synthesis of new input events from unhandled input events.
6889 */
6890 final class SyntheticInputStage extends InputStage {
6891 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
6892 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
6893 private final SyntheticTouchNavigationHandler mTouchNavigation =
6894 new SyntheticTouchNavigationHandler();
6895 private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
6896
6897 public SyntheticInputStage() {
6898 super(null);
6899 }
6900
6901 @Override
6902 protected int onProcess(QueuedInputEvent q) {
6903 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
6904 if (q.mEvent instanceof MotionEvent) {
6905 final MotionEvent event = (MotionEvent)q.mEvent;
6906 final int source = event.getSource();
6907 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
6908 mTrackball.process(event);
6909 return FINISH_HANDLED;
6910 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6911 mJoystick.process(event);
6912 return FINISH_HANDLED;
6913 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
6914 == InputDevice.SOURCE_TOUCH_NAVIGATION) {
6915 mTouchNavigation.process(event);
6916 return FINISH_HANDLED;
6917 }
6918 } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
6919 mKeyboard.process((KeyEvent)q.mEvent);
6920 return FINISH_HANDLED;
6921 }
6922
6923 return FORWARD;
6924 }
6925
6926 @Override
6927 protected void onDeliverToNext(QueuedInputEvent q) {
6928 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
6929 // Cancel related synthetic events if any prior stage has handled the event.
6930 if (q.mEvent instanceof MotionEvent) {
6931 final MotionEvent event = (MotionEvent)q.mEvent;
6932 final int source = event.getSource();
6933 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
6934 mTrackball.cancel();
6935 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6936 mJoystick.cancel();
6937 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
6938 == InputDevice.SOURCE_TOUCH_NAVIGATION) {
6939 mTouchNavigation.cancel(event);
6940 }
6941 }
6942 }
6943 super.onDeliverToNext(q);
6944 }
6945
6946 @Override
6947 protected void onWindowFocusChanged(boolean hasWindowFocus) {
6948 if (!hasWindowFocus) {
6949 mJoystick.cancel();
6950 }
6951 }
6952
6953 @Override
6954 protected void onDetachedFromWindow() {
6955 mJoystick.cancel();
6956 }
6957 }
6958
6959 /**
6960 * Creates dpad events from unhandled trackball movements.
6961 */
6962 final class SyntheticTrackballHandler {
6963 private final TrackballAxis mX = new TrackballAxis();
6964 private final TrackballAxis mY = new TrackballAxis();
6965 private long mLastTime;
6966
6967 public void process(MotionEvent event) {
6968 // Translate the trackball event into DPAD keys and try to deliver those.
6969 long curTime = SystemClock.uptimeMillis();
6970 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
6971 // It has been too long since the last movement,
6972 // so restart at the beginning.
6973 mX.reset(0);
6974 mY.reset(0);
6975 mLastTime = curTime;
6976 }
6977
6978 final int action = event.getAction();
6979 final int metaState = event.getMetaState();
6980 switch (action) {
6981 case MotionEvent.ACTION_DOWN:
6982 mX.reset(2);
6983 mY.reset(2);
6984 enqueueInputEvent(new KeyEvent(curTime, curTime,
6985 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
6986 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
6987 InputDevice.SOURCE_KEYBOARD));
6988 break;
6989 case MotionEvent.ACTION_UP:
6990 mX.reset(2);
6991 mY.reset(2);
6992 enqueueInputEvent(new KeyEvent(curTime, curTime,
6993 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
6994 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
6995 InputDevice.SOURCE_KEYBOARD));
6996 break;
6997 }
6998
6999 if (DEBUG_TRACKBALL) Log.v(mTag, "TB X=" + mX.position + " step="
7000 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
7001 + " move=" + event.getX()
7002 + " / Y=" + mY.position + " step="
7003 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
7004 + " move=" + event.getY());
7005 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
7006 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
7007
7008 // Generate DPAD events based on the trackball movement.
7009 // We pick the axis that has moved the most as the direction of
7010 // the DPAD. When we generate DPAD events for one axis, then the
7011 // other axis is reset -- we don't want to perform DPAD jumps due
7012 // to slight movements in the trackball when making major movements
7013 // along the other axis.
7014 int keycode = 0;
7015 int movement = 0;
7016 float accel = 1;
7017 if (xOff > yOff) {
7018 movement = mX.generate();
7019 if (movement != 0) {
7020 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
7021 : KeyEvent.KEYCODE_DPAD_LEFT;
7022 accel = mX.acceleration;
7023 mY.reset(2);
7024 }
7025 } else if (yOff > 0) {
7026 movement = mY.generate();
7027 if (movement != 0) {
7028 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
7029 : KeyEvent.KEYCODE_DPAD_UP;
7030 accel = mY.acceleration;
7031 mX.reset(2);
7032 }
7033 }
7034
7035 if (keycode != 0) {
7036 if (movement < 0) movement = -movement;
7037 int accelMovement = (int)(movement * accel);
7038 if (DEBUG_TRACKBALL) Log.v(mTag, "Move: movement=" + movement
7039 + " accelMovement=" + accelMovement
7040 + " accel=" + accel);
7041 if (accelMovement > movement) {
7042 if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
7043 + keycode);
7044 movement--;
7045 int repeatCount = accelMovement - movement;
7046 enqueueInputEvent(new KeyEvent(curTime, curTime,
7047 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
7048 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
7049 InputDevice.SOURCE_KEYBOARD));
7050 }
7051 while (movement > 0) {
7052 if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
7053 + keycode);
7054 movement--;
7055 curTime = SystemClock.uptimeMillis();
7056 enqueueInputEvent(new KeyEvent(curTime, curTime,
7057 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
7058 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
7059 InputDevice.SOURCE_KEYBOARD));
7060 enqueueInputEvent(new KeyEvent(curTime, curTime,
7061 KeyEvent.ACTION_UP, keycode, 0, metaState,
7062 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
7063 InputDevice.SOURCE_KEYBOARD));
7064 }
7065 mLastTime = curTime;
7066 }
7067 }
7068
7069 public void cancel() {
7070 mLastTime = Integer.MIN_VALUE;
7071
7072 // If we reach this, we consumed a trackball event.
7073 // Because we will not translate the trackball event into a key event,
7074 // touch mode will not exit, so we exit touch mode here.
7075 if (mView != null && mAdded) {
7076 ensureTouchMode(false);
7077 }
7078 }
7079 }
7080
7081 /**
7082 * Maintains state information for a single trackball axis, generating
7083 * discrete (DPAD) movements based on raw trackball motion.
7084 */
7085 static final class TrackballAxis {
7086 /**
7087 * The maximum amount of acceleration we will apply.
7088 */
7089 static final float MAX_ACCELERATION = 20;
7090
7091 /**
7092 * The maximum amount of time (in milliseconds) between events in order
7093 * for us to consider the user to be doing fast trackball movements,
7094 * and thus apply an acceleration.
7095 */
7096 static final long FAST_MOVE_TIME = 150;
7097
7098 /**
7099 * Scaling factor to the time (in milliseconds) between events to how
7100 * much to multiple/divide the current acceleration. When movement
7101 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
7102 * FAST_MOVE_TIME it divides it.
7103 */
7104 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
7105
7106 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
7107 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
7108 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
7109
7110 float position;
7111 float acceleration = 1;
7112 long lastMoveTime = 0;
7113 int step;
7114 int dir;
7115 int nonAccelMovement;
7116
7117 void reset(int _step) {
7118 position = 0;
7119 acceleration = 1;
7120 lastMoveTime = 0;
7121 step = _step;
7122 dir = 0;
7123 }
7124
7125 /**
7126 * Add trackball movement into the state. If the direction of movement
7127 * has been reversed, the state is reset before adding the
7128 * movement (so that you don't have to compensate for any previously
7129 * collected movement before see the result of the movement in the
7130 * new direction).
7131 *
7132 * @return Returns the absolute value of the amount of movement
7133 * collected so far.
7134 */
7135 float collect(float off, long time, String axis) {
7136 long normTime;
7137 if (off > 0) {
7138 normTime = (long)(off * FAST_MOVE_TIME);
7139 if (dir < 0) {
7140 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
7141 position = 0;
7142 step = 0;
7143 acceleration = 1;
7144 lastMoveTime = 0;
7145 }
7146 dir = 1;
7147 } else if (off < 0) {
7148 normTime = (long)((-off) * FAST_MOVE_TIME);
7149 if (dir > 0) {
7150 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
7151 position = 0;
7152 step = 0;
7153 acceleration = 1;
7154 lastMoveTime = 0;
7155 }
7156 dir = -1;
7157 } else {
7158 normTime = 0;
7159 }
7160
7161 // The number of milliseconds between each movement that is
7162 // considered "normal" and will not result in any acceleration
7163 // or deceleration, scaled by the offset we have here.
7164 if (normTime > 0) {
7165 long delta = time - lastMoveTime;
7166 lastMoveTime = time;
7167 float acc = acceleration;
7168 if (delta < normTime) {
7169 // The user is scrolling rapidly, so increase acceleration.
7170 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
7171 if (scale > 1) acc *= scale;
7172 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
7173 + off + " normTime=" + normTime + " delta=" + delta
7174 + " scale=" + scale + " acc=" + acc);
7175 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
7176 } else {
7177 // The user is scrolling slowly, so decrease acceleration.
7178 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
7179 if (scale > 1) acc /= scale;
7180 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
7181 + off + " normTime=" + normTime + " delta=" + delta
7182 + " scale=" + scale + " acc=" + acc);
7183 acceleration = acc > 1 ? acc : 1;
7184 }
7185 }
7186 position += off;
7187 return Math.abs(position);
7188 }
7189
7190 /**
7191 * Generate the number of discrete movement events appropriate for
7192 * the currently collected trackball movement.
7193 *
7194 * @return Returns the number of discrete movements, either positive
7195 * or negative, or 0 if there is not enough trackball movement yet
7196 * for a discrete movement.
7197 */
7198 int generate() {
7199 int movement = 0;
7200 nonAccelMovement = 0;
7201 do {
7202 final int dir = position >= 0 ? 1 : -1;
7203 switch (step) {
7204 // If we are going to execute the first step, then we want
7205 // to do this as soon as possible instead of waiting for
7206 // a full movement, in order to make things look responsive.
7207 case 0:
7208 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
7209 return movement;
7210 }
7211 movement += dir;
7212 nonAccelMovement += dir;
7213 step = 1;
7214 break;
7215 // If we have generated the first movement, then we need
7216 // to wait for the second complete trackball motion before
7217 // generating the second discrete movement.
7218 case 1:
7219 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
7220 return movement;
7221 }
7222 movement += dir;
7223 nonAccelMovement += dir;
7224 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
7225 step = 2;
7226 break;
7227 // After the first two, we generate discrete movements
7228 // consistently with the trackball, applying an acceleration
7229 // if the trackball is moving quickly. This is a simple
7230 // acceleration on top of what we already compute based
7231 // on how quickly the wheel is being turned, to apply
7232 // a longer increasing acceleration to continuous movement
7233 // in one direction.
7234 default:
7235 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
7236 return movement;
7237 }
7238 movement += dir;
7239 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
7240 float acc = acceleration;
7241 acc *= 1.1f;
7242 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
7243 break;
7244 }
7245 } while (true);
7246 }
7247 }
7248
7249 /**
7250 * Creates dpad events from unhandled joystick movements.
7251 */
7252 final class SyntheticJoystickHandler extends Handler {
7253 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
7254 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
7255
7256 private final JoystickAxesState mJoystickAxesState = new JoystickAxesState();
7257 private final SparseArray<KeyEvent> mDeviceKeyEvents = new SparseArray<>();
7258
7259 public SyntheticJoystickHandler() {
7260 super(true);
7261 }
7262
7263 @Override
7264 public void handleMessage(Message msg) {
7265 switch (msg.what) {
7266 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
7267 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
7268 if (mAttachInfo.mHasWindowFocus) {
7269 KeyEvent oldEvent = (KeyEvent) msg.obj;
7270 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
7271 SystemClock.uptimeMillis(), oldEvent.getRepeatCount() + 1);
7272 enqueueInputEvent(e);
7273 Message m = obtainMessage(msg.what, e);
7274 m.setAsynchronous(true);
7275 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
7276 }
7277 } break;
7278 }
7279 }
7280
7281 public void process(MotionEvent event) {
7282 switch(event.getActionMasked()) {
7283 case MotionEvent.ACTION_CANCEL:
7284 cancel();
7285 break;
7286 case MotionEvent.ACTION_MOVE:
7287 update(event);
7288 break;
7289 default:
7290 Log.w(mTag, "Unexpected action: " + event.getActionMasked());
7291 }
7292 }
7293
7294 private void cancel() {
7295 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
7296 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
7297 for (int i = 0; i < mDeviceKeyEvents.size(); i++) {
7298 final KeyEvent keyEvent = mDeviceKeyEvents.valueAt(i);
7299 if (keyEvent != null) {
7300 enqueueInputEvent(KeyEvent.changeTimeRepeat(keyEvent,
7301 SystemClock.uptimeMillis(), 0));
7302 }
7303 }
7304 mDeviceKeyEvents.clear();
7305 mJoystickAxesState.resetState();
7306 }
7307
7308 private void update(MotionEvent event) {
7309 final int historySize = event.getHistorySize();
7310 for (int h = 0; h < historySize; h++) {
7311 final long time = event.getHistoricalEventTime(h);
7312 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_X,
7313 event.getHistoricalAxisValue(MotionEvent.AXIS_X, 0, h));
7314 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_Y,
7315 event.getHistoricalAxisValue(MotionEvent.AXIS_Y, 0, h));
7316 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_X,
7317 event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_X, 0, h));
7318 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_Y,
7319 event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_Y, 0, h));
7320 }
7321 final long time = event.getEventTime();
7322 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_X,
7323 event.getAxisValue(MotionEvent.AXIS_X));
7324 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_Y,
7325 event.getAxisValue(MotionEvent.AXIS_Y));
7326 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_X,
7327 event.getAxisValue(MotionEvent.AXIS_HAT_X));
7328 mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_Y,
7329 event.getAxisValue(MotionEvent.AXIS_HAT_Y));
7330 }
7331
7332 final class JoystickAxesState {
7333 // State machine: from neutral state (no button press) can go into
7334 // button STATE_UP_OR_LEFT or STATE_DOWN_OR_RIGHT state, emitting an ACTION_DOWN event.
7335 // From STATE_UP_OR_LEFT or STATE_DOWN_OR_RIGHT state can go into neutral state,
7336 // emitting an ACTION_UP event.
7337 private static final int STATE_UP_OR_LEFT = -1;
7338 private static final int STATE_NEUTRAL = 0;
7339 private static final int STATE_DOWN_OR_RIGHT = 1;
7340
7341 final int[] mAxisStatesHat = {STATE_NEUTRAL, STATE_NEUTRAL}; // {AXIS_HAT_X, AXIS_HAT_Y}
7342 final int[] mAxisStatesStick = {STATE_NEUTRAL, STATE_NEUTRAL}; // {AXIS_X, AXIS_Y}
7343
7344 void resetState() {
7345 mAxisStatesHat[0] = STATE_NEUTRAL;
7346 mAxisStatesHat[1] = STATE_NEUTRAL;
7347 mAxisStatesStick[0] = STATE_NEUTRAL;
7348 mAxisStatesStick[1] = STATE_NEUTRAL;
7349 }
7350
7351 void updateStateForAxis(MotionEvent event, long time, int axis, float value) {
7352 // Emit KeyEvent if necessary
7353 // axis can be AXIS_X, AXIS_Y, AXIS_HAT_X, AXIS_HAT_Y
7354 final int axisStateIndex;
7355 final int repeatMessage;
7356 if (isXAxis(axis)) {
7357 axisStateIndex = 0;
7358 repeatMessage = MSG_ENQUEUE_X_AXIS_KEY_REPEAT;
7359 } else if (isYAxis(axis)) {
7360 axisStateIndex = 1;
7361 repeatMessage = MSG_ENQUEUE_Y_AXIS_KEY_REPEAT;
7362 } else {
7363 Log.e(mTag, "Unexpected axis " + axis + " in updateStateForAxis!");
7364 return;
7365 }
7366 final int newState = joystickAxisValueToState(value);
7367
7368 final int currentState;
7369 if (axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_Y) {
7370 currentState = mAxisStatesStick[axisStateIndex];
7371 } else {
7372 currentState = mAxisStatesHat[axisStateIndex];
7373 }
7374
7375 if (currentState == newState) {
7376 return;
7377 }
7378
7379 final int metaState = event.getMetaState();
7380 final int deviceId = event.getDeviceId();
7381 final int source = event.getSource();
7382
7383 if (currentState == STATE_DOWN_OR_RIGHT || currentState == STATE_UP_OR_LEFT) {
7384 // send a button release event
7385 final int keyCode = joystickAxisAndStateToKeycode(axis, currentState);
7386 if (keyCode != KeyEvent.KEYCODE_UNKNOWN) {
7387 enqueueInputEvent(new KeyEvent(time, time, KeyEvent.ACTION_UP, keyCode,
7388 0, metaState, deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
7389 // remove the corresponding pending UP event if focus lost/view detached
7390 mDeviceKeyEvents.put(deviceId, null);
7391 }
7392 removeMessages(repeatMessage);
7393 }
7394
7395 if (newState == STATE_DOWN_OR_RIGHT || newState == STATE_UP_OR_LEFT) {
7396 // send a button down event
7397 final int keyCode = joystickAxisAndStateToKeycode(axis, newState);
7398 if (keyCode != KeyEvent.KEYCODE_UNKNOWN) {
7399 KeyEvent keyEvent = new KeyEvent(time, time, KeyEvent.ACTION_DOWN, keyCode,
7400 0, metaState, deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
7401 enqueueInputEvent(keyEvent);
7402 Message m = obtainMessage(repeatMessage, keyEvent);
7403 m.setAsynchronous(true);
7404 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
7405 // store the corresponding ACTION_UP event so that it can be sent
7406 // if focus is lost or root view is removed
7407 mDeviceKeyEvents.put(deviceId,
7408 new KeyEvent(time, time, KeyEvent.ACTION_UP, keyCode,
7409 0, metaState, deviceId, 0,
7410 KeyEvent.FLAG_FALLBACK | KeyEvent.FLAG_CANCELED,
7411 source));
7412 }
7413 }
7414 if (axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_Y) {
7415 mAxisStatesStick[axisStateIndex] = newState;
7416 } else {
7417 mAxisStatesHat[axisStateIndex] = newState;
7418 }
7419 }
7420
7421 private boolean isXAxis(int axis) {
7422 return axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_HAT_X;
7423 }
7424 private boolean isYAxis(int axis) {
7425 return axis == MotionEvent.AXIS_Y || axis == MotionEvent.AXIS_HAT_Y;
7426 }
7427
7428 private int joystickAxisAndStateToKeycode(int axis, int state) {
7429 if (isXAxis(axis) && state == STATE_UP_OR_LEFT) {
7430 return KeyEvent.KEYCODE_DPAD_LEFT;
7431 }
7432 if (isXAxis(axis) && state == STATE_DOWN_OR_RIGHT) {
7433 return KeyEvent.KEYCODE_DPAD_RIGHT;
7434 }
7435 if (isYAxis(axis) && state == STATE_UP_OR_LEFT) {
7436 return KeyEvent.KEYCODE_DPAD_UP;
7437 }
7438 if (isYAxis(axis) && state == STATE_DOWN_OR_RIGHT) {
7439 return KeyEvent.KEYCODE_DPAD_DOWN;
7440 }
7441 Log.e(mTag, "Unknown axis " + axis + " or direction " + state);
7442 return KeyEvent.KEYCODE_UNKNOWN; // should never happen
7443 }
7444
7445 private int joystickAxisValueToState(float value) {
7446 if (value >= 0.5f) {
7447 return STATE_DOWN_OR_RIGHT;
7448 } else if (value <= -0.5f) {
7449 return STATE_UP_OR_LEFT;
7450 } else {
7451 return STATE_NEUTRAL;
7452 }
7453 }
7454 }
7455 }
7456
7457 /**
7458 * Creates dpad events from unhandled touch navigation movements.
7459 */
7460 final class SyntheticTouchNavigationHandler extends Handler {
7461 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
7462 private static final boolean LOCAL_DEBUG = false;
7463
7464 // Assumed nominal width and height in millimeters of a touch navigation pad,
7465 // if no resolution information is available from the input system.
7466 private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
7467 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
7468
7469 /* TODO: These constants should eventually be moved to ViewConfiguration. */
7470
7471 // The nominal distance traveled to move by one unit.
7472 private static final int TICK_DISTANCE_MILLIMETERS = 12;
7473
7474 // Minimum and maximum fling velocity in ticks per second.
7475 // The minimum velocity should be set such that we perform enough ticks per
7476 // second that the fling appears to be fluid. For example, if we set the minimum
7477 // to 2 ticks per second, then there may be up to half a second delay between the next
7478 // to last and last ticks which is noticeably discrete and jerky. This value should
7479 // probably not be set to anything less than about 4.
7480 // If fling accuracy is a problem then consider tuning the tick distance instead.
7481 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
7482 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
7483
7484 // Fling velocity decay factor applied after each new key is emitted.
7485 // This parameter controls the deceleration and overall duration of the fling.
7486 // The fling stops automatically when its velocity drops below the minimum
7487 // fling velocity defined above.
7488 private static final float FLING_TICK_DECAY = 0.8f;
7489
7490 /* The input device that we are tracking. */
7491
7492 private int mCurrentDeviceId = -1;
7493 private int mCurrentSource;
7494 private boolean mCurrentDeviceSupported;
7495
7496 /* Configuration for the current input device. */
7497
7498 // The scaled tick distance. A movement of this amount should generally translate
7499 // into a single dpad event in a given direction.
7500 private float mConfigTickDistance;
7501
7502 // The minimum and maximum scaled fling velocity.
7503 private float mConfigMinFlingVelocity;
7504 private float mConfigMaxFlingVelocity;
7505
7506 /* Tracking state. */
7507
7508 // The velocity tracker for detecting flings.
7509 private VelocityTracker mVelocityTracker;
7510
7511 // The active pointer id, or -1 if none.
7512 private int mActivePointerId = -1;
7513
7514 // Location where tracking started.
7515 private float mStartX;
7516 private float mStartY;
7517
7518 // Most recently observed position.
7519 private float mLastX;
7520 private float mLastY;
7521
7522 // Accumulated movement delta since the last direction key was sent.
7523 private float mAccumulatedX;
7524 private float mAccumulatedY;
7525
7526 // Set to true if any movement was delivered to the app.
7527 // Implies that tap slop was exceeded.
7528 private boolean mConsumedMovement;
7529
7530 // The most recently sent key down event.
7531 // The keycode remains set until the direction changes or a fling ends
7532 // so that repeated key events may be generated as required.
7533 private long mPendingKeyDownTime;
7534 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
7535 private int mPendingKeyRepeatCount;
7536 private int mPendingKeyMetaState;
7537
7538 // The current fling velocity while a fling is in progress.
7539 private boolean mFlinging;
7540 private float mFlingVelocity;
7541
7542 public SyntheticTouchNavigationHandler() {
7543 super(true);
7544 }
7545
7546 public void process(MotionEvent event) {
7547 // Update the current device information.
7548 final long time = event.getEventTime();
7549 final int deviceId = event.getDeviceId();
7550 final int source = event.getSource();
7551 if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
7552 finishKeys(time);
7553 finishTracking(time);
7554 mCurrentDeviceId = deviceId;
7555 mCurrentSource = source;
7556 mCurrentDeviceSupported = false;
7557 InputDevice device = event.getDevice();
7558 if (device != null) {
7559 // In order to support an input device, we must know certain
7560 // characteristics about it, such as its size and resolution.
7561 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
7562 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
7563 if (xRange != null && yRange != null) {
7564 mCurrentDeviceSupported = true;
7565
7566 // Infer the resolution if it not actually known.
7567 float xRes = xRange.getResolution();
7568 if (xRes <= 0) {
7569 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
7570 }
7571 float yRes = yRange.getResolution();
7572 if (yRes <= 0) {
7573 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
7574 }
7575 float nominalRes = (xRes + yRes) * 0.5f;
7576
7577 // Precompute all of the configuration thresholds we will need.
7578 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
7579 mConfigMinFlingVelocity =
7580 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
7581 mConfigMaxFlingVelocity =
7582 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
7583
7584 if (LOCAL_DEBUG) {
7585 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
7586 + " (" + Integer.toHexString(mCurrentSource) + "): "
7587 + ", mConfigTickDistance=" + mConfigTickDistance
7588 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
7589 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
7590 }
7591 }
7592 }
7593 }
7594 if (!mCurrentDeviceSupported) {
7595 return;
7596 }
7597
7598 // Handle the event.
7599 final int action = event.getActionMasked();
7600 switch (action) {
7601 case MotionEvent.ACTION_DOWN: {
7602 boolean caughtFling = mFlinging;
7603 finishKeys(time);
7604 finishTracking(time);
7605 mActivePointerId = event.getPointerId(0);
7606 mVelocityTracker = VelocityTracker.obtain();
7607 mVelocityTracker.addMovement(event);
7608 mStartX = event.getX();
7609 mStartY = event.getY();
7610 mLastX = mStartX;
7611 mLastY = mStartY;
7612 mAccumulatedX = 0;
7613 mAccumulatedY = 0;
7614
7615 // If we caught a fling, then pretend that the tap slop has already
7616 // been exceeded to suppress taps whose only purpose is to stop the fling.
7617 mConsumedMovement = caughtFling;
7618 break;
7619 }
7620
7621 case MotionEvent.ACTION_MOVE:
7622 case MotionEvent.ACTION_UP: {
7623 if (mActivePointerId < 0) {
7624 break;
7625 }
7626 final int index = event.findPointerIndex(mActivePointerId);
7627 if (index < 0) {
7628 finishKeys(time);
7629 finishTracking(time);
7630 break;
7631 }
7632
7633 mVelocityTracker.addMovement(event);
7634 final float x = event.getX(index);
7635 final float y = event.getY(index);
7636 mAccumulatedX += x - mLastX;
7637 mAccumulatedY += y - mLastY;
7638 mLastX = x;
7639 mLastY = y;
7640
7641 // Consume any accumulated movement so far.
7642 final int metaState = event.getMetaState();
7643 consumeAccumulatedMovement(time, metaState);
7644
7645 // Detect taps and flings.
7646 if (action == MotionEvent.ACTION_UP) {
7647 if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
7648 // It might be a fling.
7649 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
7650 final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
7651 final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
7652 if (!startFling(time, vx, vy)) {
7653 finishKeys(time);
7654 }
7655 }
7656 finishTracking(time);
7657 }
7658 break;
7659 }
7660
7661 case MotionEvent.ACTION_CANCEL: {
7662 finishKeys(time);
7663 finishTracking(time);
7664 break;
7665 }
7666 }
7667 }
7668
7669 public void cancel(MotionEvent event) {
7670 if (mCurrentDeviceId == event.getDeviceId()
7671 && mCurrentSource == event.getSource()) {
7672 final long time = event.getEventTime();
7673 finishKeys(time);
7674 finishTracking(time);
7675 }
7676 }
7677
7678 private void finishKeys(long time) {
7679 cancelFling();
7680 sendKeyUp(time);
7681 }
7682
7683 private void finishTracking(long time) {
7684 if (mActivePointerId >= 0) {
7685 mActivePointerId = -1;
7686 mVelocityTracker.recycle();
7687 mVelocityTracker = null;
7688 }
7689 }
7690
7691 private void consumeAccumulatedMovement(long time, int metaState) {
7692 final float absX = Math.abs(mAccumulatedX);
7693 final float absY = Math.abs(mAccumulatedY);
7694 if (absX >= absY) {
7695 if (absX >= mConfigTickDistance) {
7696 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
7697 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
7698 mAccumulatedY = 0;
7699 mConsumedMovement = true;
7700 }
7701 } else {
7702 if (absY >= mConfigTickDistance) {
7703 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
7704 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
7705 mAccumulatedX = 0;
7706 mConsumedMovement = true;
7707 }
7708 }
7709 }
7710
7711 private float consumeAccumulatedMovement(long time, int metaState,
7712 float accumulator, int negativeKeyCode, int positiveKeyCode) {
7713 while (accumulator <= -mConfigTickDistance) {
7714 sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
7715 accumulator += mConfigTickDistance;
7716 }
7717 while (accumulator >= mConfigTickDistance) {
7718 sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
7719 accumulator -= mConfigTickDistance;
7720 }
7721 return accumulator;
7722 }
7723
7724 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
7725 if (mPendingKeyCode != keyCode) {
7726 sendKeyUp(time);
7727 mPendingKeyDownTime = time;
7728 mPendingKeyCode = keyCode;
7729 mPendingKeyRepeatCount = 0;
7730 } else {
7731 mPendingKeyRepeatCount += 1;
7732 }
7733 mPendingKeyMetaState = metaState;
7734
7735 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
7736 // but it doesn't quite make sense when simulating the events in this way.
7737 if (LOCAL_DEBUG) {
7738 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
7739 + ", repeatCount=" + mPendingKeyRepeatCount
7740 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
7741 }
7742 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
7743 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
7744 mPendingKeyMetaState, mCurrentDeviceId,
7745 KeyEvent.FLAG_FALLBACK, mCurrentSource));
7746 }
7747
7748 private void sendKeyUp(long time) {
7749 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
7750 if (LOCAL_DEBUG) {
7751 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
7752 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
7753 }
7754 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
7755 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
7756 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
7757 mCurrentSource));
7758 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
7759 }
7760 }
7761
7762 private boolean startFling(long time, float vx, float vy) {
7763 if (LOCAL_DEBUG) {
7764 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
7765 + ", min=" + mConfigMinFlingVelocity);
7766 }
7767
7768 // Flings must be oriented in the same direction as the preceding movements.
7769 switch (mPendingKeyCode) {
7770 case KeyEvent.KEYCODE_DPAD_LEFT:
7771 if (-vx >= mConfigMinFlingVelocity
7772 && Math.abs(vy) < mConfigMinFlingVelocity) {
7773 mFlingVelocity = -vx;
7774 break;
7775 }
7776 return false;
7777
7778 case KeyEvent.KEYCODE_DPAD_RIGHT:
7779 if (vx >= mConfigMinFlingVelocity
7780 && Math.abs(vy) < mConfigMinFlingVelocity) {
7781 mFlingVelocity = vx;
7782 break;
7783 }
7784 return false;
7785
7786 case KeyEvent.KEYCODE_DPAD_UP:
7787 if (-vy >= mConfigMinFlingVelocity
7788 && Math.abs(vx) < mConfigMinFlingVelocity) {
7789 mFlingVelocity = -vy;
7790 break;
7791 }
7792 return false;
7793
7794 case KeyEvent.KEYCODE_DPAD_DOWN:
7795 if (vy >= mConfigMinFlingVelocity
7796 && Math.abs(vx) < mConfigMinFlingVelocity) {
7797 mFlingVelocity = vy;
7798 break;
7799 }
7800 return false;
7801 }
7802
7803 // Post the first fling event.
7804 mFlinging = postFling(time);
7805 return mFlinging;
7806 }
7807
7808 private boolean postFling(long time) {
7809 // The idea here is to estimate the time when the pointer would have
7810 // traveled one tick distance unit given the current fling velocity.
7811 // This effect creates continuity of motion.
7812 if (mFlingVelocity >= mConfigMinFlingVelocity) {
7813 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
7814 postAtTime(mFlingRunnable, time + delay);
7815 if (LOCAL_DEBUG) {
7816 Log.d(LOCAL_TAG, "Posted fling: velocity="
7817 + mFlingVelocity + ", delay=" + delay
7818 + ", keyCode=" + mPendingKeyCode);
7819 }
7820 return true;
7821 }
7822 return false;
7823 }
7824
7825 private void cancelFling() {
7826 if (mFlinging) {
7827 removeCallbacks(mFlingRunnable);
7828 mFlinging = false;
7829 }
7830 }
7831
7832 private final Runnable mFlingRunnable = new Runnable() {
7833 @Override
7834 public void run() {
7835 final long time = SystemClock.uptimeMillis();
7836 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
7837 mFlingVelocity *= FLING_TICK_DECAY;
7838 if (!postFling(time)) {
7839 mFlinging = false;
7840 finishKeys(time);
7841 }
7842 }
7843 };
7844 }
7845
7846 final class SyntheticKeyboardHandler {
7847 public void process(KeyEvent event) {
7848 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
7849 return;
7850 }
7851
7852 final KeyCharacterMap kcm = event.getKeyCharacterMap();
7853 final int keyCode = event.getKeyCode();
7854 final int metaState = event.getMetaState();
7855
7856 // Check for fallback actions specified by the key character map.
7857 KeyCharacterMap.FallbackAction fallbackAction =
7858 kcm.getFallbackAction(keyCode, metaState);
7859 if (fallbackAction != null) {
7860 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
7861 KeyEvent fallbackEvent = KeyEvent.obtain(
7862 event.getDownTime(), event.getEventTime(),
7863 event.getAction(), fallbackAction.keyCode,
7864 event.getRepeatCount(), fallbackAction.metaState,
7865 event.getDeviceId(), event.getScanCode(),
7866 flags, event.getSource(), null);
7867 fallbackAction.recycle();
7868 enqueueInputEvent(fallbackEvent);
7869 }
7870 }
7871 }
7872
7873 /**
7874 * Returns true if the key is used for keyboard navigation.
7875 * @param keyEvent The key event.
7876 * @return True if the key is used for keyboard navigation.
7877 */
7878 private static boolean isNavigationKey(KeyEvent keyEvent) {
7879 switch (keyEvent.getKeyCode()) {
7880 case KeyEvent.KEYCODE_DPAD_LEFT:
7881 case KeyEvent.KEYCODE_DPAD_RIGHT:
7882 case KeyEvent.KEYCODE_DPAD_UP:
7883 case KeyEvent.KEYCODE_DPAD_DOWN:
7884 case KeyEvent.KEYCODE_DPAD_CENTER:
7885 case KeyEvent.KEYCODE_PAGE_UP:
7886 case KeyEvent.KEYCODE_PAGE_DOWN:
7887 case KeyEvent.KEYCODE_MOVE_HOME:
7888 case KeyEvent.KEYCODE_MOVE_END:
7889 case KeyEvent.KEYCODE_TAB:
7890 case KeyEvent.KEYCODE_SPACE:
7891 case KeyEvent.KEYCODE_ENTER:
7892 return true;
7893 }
7894 return false;
7895 }
7896
7897 /**
7898 * Returns true if the key is used for typing.
7899 * @param keyEvent The key event.
7900 * @return True if the key is used for typing.
7901 */
7902 private static boolean isTypingKey(KeyEvent keyEvent) {
7903 return keyEvent.getUnicodeChar() > 0;
7904 }
7905
7906 /**
7907 * See if the key event means we should leave touch mode (and leave touch mode if so).
7908 * @param event The key event.
7909 * @return Whether this key event should be consumed (meaning the act of
7910 * leaving touch mode alone is considered the event).
7911 */
7912 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
7913 // Only relevant in touch mode.
7914 if (!mAttachInfo.mInTouchMode) {
7915 return false;
7916 }
7917
7918 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
7919 final int action = event.getAction();
7920 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
7921 return false;
7922 }
7923
7924 // Don't leave touch mode if the IME told us not to.
7925 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
7926 return false;
7927 }
7928
7929 // If the key can be used for keyboard navigation then leave touch mode
7930 // and select a focused view if needed (in ensureTouchMode).
7931 // When a new focused view is selected, we consume the navigation key because
7932 // navigation doesn't make much sense unless a view already has focus so
7933 // the key's purpose is to set focus.
7934 if (event.hasNoModifiers() && isNavigationKey(event)) {
7935 return ensureTouchMode(false);
7936 }
7937
7938 // If the key can be used for typing then leave touch mode
7939 // and select a focused view if needed (in ensureTouchMode).
7940 // Always allow the view to process the typing key.
7941 if (isTypingKey(event)) {
7942 ensureTouchMode(false);
7943 return false;
7944 }
7945
7946 return false;
7947 }
7948
7949 /* drag/drop */
7950 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
7951 void setLocalDragState(Object obj) {
7952 mLocalDragState = obj;
7953 }
7954
7955 private void handleDragEvent(DragEvent event) {
7956 // From the root, only drag start/end/location are dispatched. entered/exited
7957 // are determined and dispatched by the viewgroup hierarchy, who then report
7958 // that back here for ultimate reporting back to the framework.
7959 if (mView != null && mAdded) {
7960 final int what = event.mAction;
7961
7962 // Cache the drag description when the operation starts, then fill it in
7963 // on subsequent calls as a convenience
7964 if (what == DragEvent.ACTION_DRAG_STARTED) {
7965 mCurrentDragView = null; // Start the current-recipient tracking
7966 mDragDescription = event.mClipDescription;
7967 if (mStartedDragViewForA11y != null) {
7968 // Send a drag started a11y event
7969 mStartedDragViewForA11y.sendWindowContentChangedAccessibilityEvent(
7970 AccessibilityEvent.CONTENT_CHANGE_TYPE_DRAG_STARTED);
7971 }
7972 } else {
7973 if (what == DragEvent.ACTION_DRAG_ENDED) {
7974 mDragDescription = null;
7975 }
7976 event.mClipDescription = mDragDescription;
7977 }
7978
7979 if (what == DragEvent.ACTION_DRAG_EXITED) {
7980 // A direct EXITED event means that the window manager knows we've just crossed
7981 // a window boundary, so the current drag target within this one must have
7982 // just been exited. Send the EXITED notification to the current drag view, if any.
7983 if (View.sCascadedDragDrop) {
7984 mView.dispatchDragEnterExitInPreN(event);
7985 }
7986 setDragFocus(null, event);
7987 } else {
7988 // For events with a [screen] location, translate into window coordinates
7989 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
7990 mDragPoint.set(event.mX, event.mY);
7991 if (mTranslator != null) {
7992 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
7993 }
7994
7995 if (mCurScrollY != 0) {
7996 mDragPoint.offset(0, mCurScrollY);
7997 }
7998
7999 event.mX = mDragPoint.x;
8000 event.mY = mDragPoint.y;
8001 }
8002
8003 // Remember who the current drag target is pre-dispatch
8004 final View prevDragView = mCurrentDragView;
8005
8006 if (what == DragEvent.ACTION_DROP && event.mClipData != null) {
8007 event.mClipData.prepareToEnterProcess(
8008 mView.getContext().getAttributionSource());
8009 }
8010
8011 // Now dispatch the drag/drop event
8012 boolean result = mView.dispatchDragEvent(event);
8013
8014 if (what == DragEvent.ACTION_DRAG_LOCATION && !event.mEventHandlerWasCalled) {
8015 // If the LOCATION event wasn't delivered to any handler, no view now has a drag
8016 // focus.
8017 setDragFocus(null, event);
8018 }
8019
8020 // If we changed apparent drag target, tell the OS about it
8021 if (prevDragView != mCurrentDragView) {
8022 try {
8023 if (prevDragView != null) {
8024 mWindowSession.dragRecipientExited(mWindow);
8025 }
8026 if (mCurrentDragView != null) {
8027 mWindowSession.dragRecipientEntered(mWindow);
8028 }
8029 } catch (RemoteException e) {
8030 Slog.e(mTag, "Unable to note drag target change");
8031 }
8032 }
8033
8034 // Report the drop result when we're done
8035 if (what == DragEvent.ACTION_DROP) {
8036 try {
8037 Log.i(mTag, "Reporting drop result: " + result);
8038 mWindowSession.reportDropResult(mWindow, result);
8039 } catch (RemoteException e) {
8040 Log.e(mTag, "Unable to report drop result");
8041 }
8042 }
8043
8044 // When the drag operation ends, reset drag-related state
8045 if (what == DragEvent.ACTION_DRAG_ENDED) {
8046 if (mStartedDragViewForA11y != null) {
8047 // If the drag failed, send a cancelled event from the source. Otherwise,
8048 // the View that accepted the drop sends CONTENT_CHANGE_TYPE_DRAG_DROPPED
8049 if (!event.getResult()) {
8050 mStartedDragViewForA11y.sendWindowContentChangedAccessibilityEvent(
8051 AccessibilityEvent.CONTENT_CHANGE_TYPE_DRAG_CANCELLED);
8052 }
8053 mStartedDragViewForA11y.setAccessibilityDragStarted(false);
8054 }
8055 mStartedDragViewForA11y = null;
8056 mCurrentDragView = null;
8057 setLocalDragState(null);
8058 mAttachInfo.mDragToken = null;
8059 if (mAttachInfo.mDragSurface != null) {
8060 mAttachInfo.mDragSurface.release();
8061 mAttachInfo.mDragSurface = null;
8062 }
8063 }
8064 }
8065 }
8066 event.recycle();
8067 }
8068
8069 /**
8070 * Notify that the window title changed
8071 */
8072 public void onWindowTitleChanged() {
8073 mAttachInfo.mForceReportNewAttributes = true;
8074 }
8075
8076 public void handleDispatchWindowShown() {
8077 mAttachInfo.mTreeObserver.dispatchOnWindowShown();
8078 }
8079
8080 public void handleRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
8081 Bundle data = new Bundle();
8082 ArrayList<KeyboardShortcutGroup> list = new ArrayList<>();
8083 if (mView != null) {
8084 mView.requestKeyboardShortcuts(list, deviceId);
8085 }
8086 data.putParcelableArrayList(WindowManager.PARCEL_KEY_SHORTCUTS_ARRAY, list);
8087 try {
8088 receiver.send(0, data);
8089 } catch (RemoteException e) {
8090 }
8091 }
8092
8093 @UnsupportedAppUsage
8094 public void getLastTouchPoint(Point outLocation) {
8095 outLocation.x = (int) mLastTouchPoint.x;
8096 outLocation.y = (int) mLastTouchPoint.y;
8097 }
8098
8099 public int getLastTouchSource() {
8100 return mLastTouchSource;
8101 }
8102
8103 public void setDragFocus(View newDragTarget, DragEvent event) {
8104 if (mCurrentDragView != newDragTarget && !View.sCascadedDragDrop) {
8105 // Send EXITED and ENTERED notifications to the old and new drag focus views.
8106
8107 final float tx = event.mX;
8108 final float ty = event.mY;
8109 final int action = event.mAction;
8110 final ClipData td = event.mClipData;
8111 // Position should not be available for ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED.
8112 event.mX = 0;
8113 event.mY = 0;
8114 event.mClipData = null;
8115
8116 if (mCurrentDragView != null) {
8117 event.mAction = DragEvent.ACTION_DRAG_EXITED;
8118 mCurrentDragView.callDragEventHandler(event);
8119 }
8120
8121 if (newDragTarget != null) {
8122 event.mAction = DragEvent.ACTION_DRAG_ENTERED;
8123 newDragTarget.callDragEventHandler(event);
8124 }
8125
8126 event.mAction = action;
8127 event.mX = tx;
8128 event.mY = ty;
8129 event.mClipData = td;
8130 }
8131
8132 mCurrentDragView = newDragTarget;
8133 }
8134
8135 /** Sets the view that started drag and drop for the purpose of sending AccessibilityEvents */
8136 void setDragStartedViewForAccessibility(View view) {
8137 if (mStartedDragViewForA11y == null) {
8138 mStartedDragViewForA11y = view;
8139 }
8140 }
8141
8142 private AudioManager getAudioManager() {
8143 if (mView == null) {
8144 throw new IllegalStateException("getAudioManager called when there is no mView");
8145 }
8146 if (mAudioManager == null) {
8147 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
8148 }
8149 return mAudioManager;
8150 }
8151
8152 private @Nullable AutofillManager getAutofillManager() {
8153 if (mView instanceof ViewGroup) {
8154 ViewGroup decorView = (ViewGroup) mView;
8155 if (decorView.getChildCount() > 0) {
8156 // We cannot use decorView's Context for querying AutofillManager: DecorView's
8157 // context is based on Application Context, it would allocate a different
8158 // AutofillManager instance.
8159 return decorView.getChildAt(0).getContext()
8160 .getSystemService(AutofillManager.class);
8161 }
8162 }
8163 return null;
8164 }
8165
8166 private boolean isAutofillUiShowing() {
8167 AutofillManager afm = getAutofillManager();
8168 if (afm == null) {
8169 return false;
8170 }
8171 return afm.isAutofillUiShowing();
8172 }
8173
8174 public AccessibilityInteractionController getAccessibilityInteractionController() {
8175 if (mView == null) {
8176 throw new IllegalStateException("getAccessibilityInteractionController"
8177 + " called when there is no mView");
8178 }
8179 if (mAccessibilityInteractionController == null) {
8180 mAccessibilityInteractionController = new AccessibilityInteractionController(this);
8181 }
8182 return mAccessibilityInteractionController;
8183 }
8184
8185 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
8186 boolean insetsPending) throws RemoteException {
8187 final WindowConfiguration winConfigFromAm = getConfiguration().windowConfiguration;
8188 final WindowConfiguration winConfigFromWm =
8189 mLastReportedMergedConfiguration.getGlobalConfiguration().windowConfiguration;
8190 final WindowConfiguration winConfig = getCompatWindowConfiguration();
8191 final int measuredWidth = mMeasuredWidth;
8192 final int measuredHeight = mMeasuredHeight;
8193 final boolean relayoutAsync;
8194 if (LOCAL_LAYOUT
8195 && (mViewFrameInfo.flags & FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED) == 0
8196 && mWindowAttributes.type != TYPE_APPLICATION_STARTING
8197 && mSyncSeqId <= mLastSyncSeqId
8198 && winConfigFromAm.diff(winConfigFromWm, false /* compareUndefined */) == 0) {
8199 final InsetsState state = mInsetsController.getState();
8200 final Rect displayCutoutSafe = mTempRect;
8201 state.getDisplayCutoutSafe(displayCutoutSafe);
8202 mWindowLayout.computeFrames(mWindowAttributes.forRotation(winConfig.getRotation()),
8203 state, displayCutoutSafe, winConfig.getBounds(), winConfig.getWindowingMode(),
8204 measuredWidth, measuredHeight, mInsetsController.getRequestedVisibilities(),
8205 1f /* compatScale */, mTmpFrames);
8206 mWinFrameInScreen.set(mTmpFrames.frame);
8207 if (mTranslator != null) {
8208 mTranslator.translateRectInAppWindowToScreen(mWinFrameInScreen);
8209 }
8210
8211 // If the position and the size of the frame are both changed, it will trigger a BLAST
8212 // sync, and we still need to call relayout to obtain the syncSeqId. Otherwise, we just
8213 // need to send attributes via relayoutAsync.
8214 final Rect oldFrame = mWinFrame;
8215 final Rect newFrame = mTmpFrames.frame;
8216 final boolean positionChanged =
8217 newFrame.top != oldFrame.top || newFrame.left != oldFrame.left;
8218 final boolean sizeChanged =
8219 newFrame.width() != oldFrame.width() || newFrame.height() != oldFrame.height();
8220 relayoutAsync = !positionChanged || !sizeChanged;
8221 } else {
8222 relayoutAsync = false;
8223 }
8224
8225 float appScale = mAttachInfo.mApplicationScale;
8226 boolean restore = false;
8227 if (params != null && mTranslator != null) {
8228 restore = true;
8229 params.backup();
8230 mTranslator.translateWindowLayout(params);
8231 }
8232
8233 if (params != null) {
8234 if (DBG) Log.d(mTag, "WindowLayout in layoutWindow:" + params);
8235
8236 if (mOrigWindowType != params.type) {
8237 // For compatibility with old apps, don't crash here.
8238 if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
8239 Slog.w(mTag, "Window type can not be changed after "
8240 + "the window is added; ignoring change of " + mView);
8241 params.type = mOrigWindowType;
8242 }
8243 }
8244 }
8245
8246 final int requestedWidth = (int) (measuredWidth * appScale + 0.5f);
8247 final int requestedHeight = (int) (measuredHeight * appScale + 0.5f);
8248 int relayoutResult = 0;
8249 mRelayoutSeq++;
8250 if (relayoutAsync) {
8251 mWindowSession.relayoutAsync(mWindow, params,
8252 requestedWidth, requestedHeight, viewVisibility,
8253 insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, mRelayoutSeq,
8254 mLastSyncSeqId);
8255 } else {
8256 relayoutResult = mWindowSession.relayout(mWindow, params,
8257 requestedWidth, requestedHeight, viewVisibility,
8258 insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, mRelayoutSeq,
8259 mLastSyncSeqId, mTmpFrames, mPendingMergedConfiguration, mSurfaceControl,
8260 mTempInsets, mTempControls, mRelayoutBundle);
8261 mRelayoutRequested = true;
8262
8263 final int maybeSyncSeqId = mRelayoutBundle.getInt("seqid");
8264 if (maybeSyncSeqId > 0) {
8265 mSyncSeqId = maybeSyncSeqId;
8266 }
8267 mWinFrameInScreen.set(mTmpFrames.frame);
8268 if (mTranslator != null) {
8269 mTranslator.translateRectInScreenToAppWindow(mTmpFrames.frame);
8270 mTranslator.translateRectInScreenToAppWindow(mTmpFrames.displayFrame);
8271 mTranslator.translateRectInScreenToAppWindow(mTmpFrames.attachedFrame);
8272 mTranslator.translateInsetsStateInScreenToAppWindow(mTempInsets);
8273 mTranslator.translateSourceControlsInScreenToAppWindow(mTempControls);
8274 }
8275 mInvCompatScale = 1f / mTmpFrames.compatScale;
8276 mInsetsController.onStateChanged(mTempInsets);
8277 mInsetsController.onControlsChanged(mTempControls);
8278
8279 mPendingAlwaysConsumeSystemBars =
8280 (relayoutResult & RELAYOUT_RES_CONSUME_ALWAYS_SYSTEM_BARS) != 0;
8281 }
8282
8283 final int transformHint = SurfaceControl.rotationToBufferTransform(
8284 (mDisplayInstallOrientation + mDisplay.getRotation()) % 4);
8285
8286 WindowLayout.computeSurfaceSize(mWindowAttributes, winConfig.getMaxBounds(), requestedWidth,
8287 requestedHeight, mWinFrameInScreen, mPendingDragResizing, mSurfaceSize);
8288
8289 final boolean transformHintChanged = transformHint != mLastTransformHint;
8290 final boolean sizeChanged = !mLastSurfaceSize.equals(mSurfaceSize);
8291 final boolean surfaceControlChanged =
8292 (relayoutResult & RELAYOUT_RES_SURFACE_CHANGED) == RELAYOUT_RES_SURFACE_CHANGED;
8293 if (mAttachInfo.mThreadedRenderer != null &&
8294 (transformHintChanged || sizeChanged || surfaceControlChanged)) {
8295 if (mAttachInfo.mThreadedRenderer.pause()) {
8296 // Animations were running so we need to push a frame
8297 // to resume them
8298 mDirty.set(0, 0, mWidth, mHeight);
8299 }
8300 }
8301
8302 if (mSurfaceControl.isValid() && !HardwareRenderer.isDrawingEnabled()) {
8303 // When drawing is disabled the window layer won't have a valid buffer.
8304 // Set a window crop so input can get delivered to the window.
8305 mTransaction.setWindowCrop(mSurfaceControl, mSurfaceSize.x, mSurfaceSize.y).apply();
8306 }
8307
8308 mLastTransformHint = transformHint;
8309
8310 mSurfaceControl.setTransformHint(transformHint);
8311
8312 if (mAttachInfo.mContentCaptureManager != null) {
8313 MainContentCaptureSession mainSession = mAttachInfo.mContentCaptureManager
8314 .getMainContentCaptureSession();
8315 mainSession.notifyWindowBoundsChanged(mainSession.getId(),
8316 getConfiguration().windowConfiguration.getBounds());
8317 }
8318
8319 if (mSurfaceControl.isValid()) {
8320 if (!useBLAST()) {
8321 mSurface.copyFrom(mSurfaceControl);
8322 } else {
8323 updateBlastSurfaceIfNeeded();
8324 }
8325 if (mAttachInfo.mThreadedRenderer != null) {
8326 mAttachInfo.mThreadedRenderer.setSurfaceControl(mSurfaceControl);
8327 mAttachInfo.mThreadedRenderer.setBlastBufferQueue(mBlastBufferQueue);
8328 }
8329 if (mPreviousTransformHint != transformHint) {
8330 mPreviousTransformHint = transformHint;
8331 dispatchTransformHintChanged(transformHint);
8332 }
8333 } else {
8334 if (mAttachInfo.mThreadedRenderer != null && mAttachInfo.mThreadedRenderer.pause()) {
8335 mDirty.set(0, 0, mWidth, mHeight);
8336 }
8337 destroySurface();
8338 }
8339
8340 if (restore) {
8341 params.restore();
8342 }
8343
8344 setFrame(mTmpFrames.frame);
8345 return relayoutResult;
8346 }
8347
8348 private void updateOpacity(WindowManager.LayoutParams params, boolean dragResizing,
8349 boolean forceUpdate) {
8350 boolean opaque = false;
8351
8352 if (!PixelFormat.formatHasAlpha(params.format)
8353 // Don't make surface with surfaceInsets opaque as they display a
8354 // translucent shadow.
8355 && params.surfaceInsets.left == 0
8356 && params.surfaceInsets.top == 0
8357 && params.surfaceInsets.right == 0
8358 && params.surfaceInsets.bottom == 0
8359 // Don't make surface opaque when resizing to reduce the amount of
8360 // artifacts shown in areas the app isn't drawing content to.
8361 && !dragResizing) {
8362 opaque = true;
8363 }
8364
8365 if (!forceUpdate && mIsSurfaceOpaque == opaque) {
8366 return;
8367 }
8368
8369 final ThreadedRenderer renderer = mAttachInfo.mThreadedRenderer;
8370 if (renderer != null && renderer.rendererOwnsSurfaceControlOpacity()) {
8371 opaque = renderer.setSurfaceControlOpaque(opaque);
8372 } else {
8373 mTransaction.setOpaque(mSurfaceControl, opaque).apply();
8374 }
8375
8376 mIsSurfaceOpaque = opaque;
8377 }
8378
8379 private void setFrame(Rect frame) {
8380 mWinFrame.set(frame);
8381
8382 final WindowConfiguration winConfig = getCompatWindowConfiguration();
8383 mPendingBackDropFrame.set(mPendingDragResizing && !winConfig.useWindowFrameForBackdrop()
8384 ? winConfig.getMaxBounds()
8385 : frame);
8386 // Surface position is now inherited from parent, and BackdropFrameRenderer uses backdrop
8387 // frame to position content. Thus, we just keep the size of backdrop frame, and remove the
8388 // offset to avoid double offset from display origin.
8389 mPendingBackDropFrame.offsetTo(0, 0);
8390
8391 mInsetsController.onFrameChanged(mOverrideInsetsFrame != null ?
8392 mOverrideInsetsFrame : frame);
8393 }
8394
8395 /**
8396 * In the normal course of operations we compute insets relative to
8397 * the frame returned from relayout window. In the case of
8398 * SurfaceControlViewHost, this frame is in local coordinates
8399 * instead of global coordinates. We support this override
8400 * frame so we can allow SurfaceControlViewHost to set a frame
8401 * to be used to calculate insets, without disturbing the main
8402 * mFrame.
8403 */
8404 void setOverrideInsetsFrame(Rect frame) {
8405 mOverrideInsetsFrame = new Rect(frame);
8406 mInsetsController.onFrameChanged(mOverrideInsetsFrame);
8407 }
8408
8409 /**
8410 * Gets the current display size in which the window is being laid out, accounting for screen
8411 * decorations around it.
8412 */
8413 void getDisplayFrame(Rect outFrame) {
8414 outFrame.set(mTmpFrames.displayFrame);
8415 }
8416
8417 /**
8418 * Gets the current display size in which the window is being laid out, accounting for screen
8419 * decorations around it.
8420 */
8421 void getWindowVisibleDisplayFrame(Rect outFrame) {
8422 outFrame.set(mTmpFrames.displayFrame);
8423 // XXX This is really broken, and probably all needs to be done
8424 // in the window manager, and we need to know more about whether
8425 // we want the area behind or in front of the IME.
8426 final Rect insets = mAttachInfo.mVisibleInsets;
8427 outFrame.left += insets.left;
8428 outFrame.top += insets.top;
8429 outFrame.right -= insets.right;
8430 outFrame.bottom -= insets.bottom;
8431 }
8432
8433 /**
8434 * {@inheritDoc}
8435 */
8436 @Override
8437 public void playSoundEffect(@SoundEffectConstants.SoundEffect int effectId) {
8438 if ((mDisplay.getFlags() & Display.FLAG_TOUCH_FEEDBACK_DISABLED) != 0) {
8439 return;
8440 }
8441
8442 checkThread();
8443
8444 try {
8445 final AudioManager audioManager = getAudioManager();
8446
8447 if (mFastScrollSoundEffectsEnabled
8448 && SoundEffectConstants.isNavigationRepeat(effectId)) {
8449 audioManager.playSoundEffect(
8450 SoundEffectConstants.nextNavigationRepeatSoundEffectId());
8451 return;
8452 }
8453
8454 switch (effectId) {
8455 case SoundEffectConstants.CLICK:
8456 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
8457 return;
8458 case SoundEffectConstants.NAVIGATION_DOWN:
8459 case SoundEffectConstants.NAVIGATION_REPEAT_DOWN:
8460 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
8461 return;
8462 case SoundEffectConstants.NAVIGATION_LEFT:
8463 case SoundEffectConstants.NAVIGATION_REPEAT_LEFT:
8464 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
8465 return;
8466 case SoundEffectConstants.NAVIGATION_RIGHT:
8467 case SoundEffectConstants.NAVIGATION_REPEAT_RIGHT:
8468 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
8469 return;
8470 case SoundEffectConstants.NAVIGATION_UP:
8471 case SoundEffectConstants.NAVIGATION_REPEAT_UP:
8472 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
8473 return;
8474 default:
8475 throw new IllegalArgumentException("unknown effect id " + effectId +
8476 " not defined in " + SoundEffectConstants.class.getCanonicalName());
8477 }
8478 } catch (IllegalStateException e) {
8479 // Exception thrown by getAudioManager() when mView is null
8480 Log.e(mTag, "FATAL EXCEPTION when attempting to play sound effect: " + e);
8481 e.printStackTrace();
8482 }
8483 }
8484
8485 /**
8486 * {@inheritDoc}
8487 */
8488 @Override
8489 public boolean performHapticFeedback(int effectId, boolean always) {
8490 if ((mDisplay.getFlags() & Display.FLAG_TOUCH_FEEDBACK_DISABLED) != 0) {
8491 return false;
8492 }
8493
8494 try {
8495 return mWindowSession.performHapticFeedback(effectId, always);
8496 } catch (RemoteException e) {
8497 return false;
8498 }
8499 }
8500
8501 /**
8502 * {@inheritDoc}
8503 */
8504 @Override
8505 public View focusSearch(View focused, int direction) {
8506 checkThread();
8507 if (!(mView instanceof ViewGroup)) {
8508 return null;
8509 }
8510 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
8511 }
8512
8513 /**
8514 * {@inheritDoc}
8515 */
8516 @Override
8517 public View keyboardNavigationClusterSearch(View currentCluster,
8518 @FocusDirection int direction) {
8519 checkThread();
8520 return FocusFinder.getInstance().findNextKeyboardNavigationCluster(
8521 mView, currentCluster, direction);
8522 }
8523
8524 public void debug() {
8525 mView.debug();
8526 }
8527
8528 /**
8529 * Export the state of {@link ViewRootImpl} and other relevant classes into a protocol buffer
8530 * output stream.
8531 *
8532 * @param proto Stream to write the state to
8533 * @param fieldId FieldId of ViewRootImpl as defined in the parent message
8534 */
8535 @GuardedBy("this")
8536 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
8537 final long token = proto.start(fieldId);
8538 proto.write(VIEW, Objects.toString(mView));
8539 proto.write(DISPLAY_ID, mDisplay.getDisplayId());
8540 proto.write(APP_VISIBLE, mAppVisible);
8541 proto.write(HEIGHT, mHeight);
8542 proto.write(WIDTH, mWidth);
8543 proto.write(IS_ANIMATING, mIsAnimating);
8544 mVisRect.dumpDebug(proto, VISIBLE_RECT);
8545 proto.write(IS_DRAWING, mIsDrawing);
8546 proto.write(ADDED, mAdded);
8547 mWinFrame.dumpDebug(proto, WIN_FRAME);
8548 proto.write(LAST_WINDOW_INSETS, Objects.toString(mLastWindowInsets));
8549 proto.write(SOFT_INPUT_MODE, InputMethodDebug.softInputModeToString(mSoftInputMode));
8550 proto.write(SCROLL_Y, mScrollY);
8551 proto.write(CUR_SCROLL_Y, mCurScrollY);
8552 proto.write(REMOVED, mRemoved);
8553 mWindowAttributes.dumpDebug(proto, WINDOW_ATTRIBUTES);
8554 proto.end(token);
8555 mInsetsController.dumpDebug(proto, INSETS_CONTROLLER);
8556 mImeFocusController.dumpDebug(proto, IME_FOCUS_CONTROLLER);
8557 }
8558
8559 /**
8560 * Dump information about this ViewRootImpl
8561 * @param prefix the prefix that will be prepended to each line of the produced output
8562 * @param writer the writer that will receive the resulting text
8563 */
8564 public void dump(String prefix, PrintWriter writer) {
8565 String innerPrefix = prefix + " ";
8566 writer.println(prefix + "ViewRoot:");
8567 writer.println(innerPrefix + "mAdded=" + mAdded);
8568 writer.println(innerPrefix + "mRemoved=" + mRemoved);
8569 writer.println(innerPrefix + "mStopped=" + mStopped);
8570 writer.println(innerPrefix + "mPausedForTransition=" + mPausedForTransition);
8571 writer.println(innerPrefix + "mConsumeBatchedInputScheduled="
8572 + mConsumeBatchedInputScheduled);
8573 writer.println(innerPrefix + "mConsumeBatchedInputImmediatelyScheduled="
8574 + mConsumeBatchedInputImmediatelyScheduled);
8575 writer.println(innerPrefix + "mPendingInputEventCount=" + mPendingInputEventCount);
8576 writer.println(innerPrefix + "mProcessInputEventsScheduled="
8577 + mProcessInputEventsScheduled);
8578 writer.println(innerPrefix + "mTraversalScheduled=" + mTraversalScheduled);
8579 if (mTraversalScheduled) {
8580 writer.println(innerPrefix + " (barrier=" + mTraversalBarrier + ")");
8581 }
8582 writer.println(innerPrefix + "mReportNextDraw=" + mReportNextDraw);
8583 if (mReportNextDraw) {
8584 writer.println(innerPrefix + " (reason=" + mLastReportNextDrawReason + ")");
8585 }
8586 if (mLastPerformTraversalsSkipDrawReason != null) {
8587 writer.println(innerPrefix + "mLastPerformTraversalsFailedReason="
8588 + mLastPerformTraversalsSkipDrawReason);
8589 }
8590 if (mLastPerformDrawSkippedReason != null) {
8591 writer.println(innerPrefix + "mLastPerformDrawFailedReason="
8592 + mLastPerformDrawSkippedReason);
8593 }
8594 if (mLocalSyncState != LOCAL_SYNC_NONE) {
8595 writer.println(innerPrefix + "mLocalSyncState=" + mLocalSyncState);
8596 }
8597 writer.println(innerPrefix + "mLastReportedMergedConfiguration="
8598 + mLastReportedMergedConfiguration);
8599 writer.println(innerPrefix + "mLastConfigurationFromResources="
8600 + mLastConfigurationFromResources);
8601 writer.println(innerPrefix + "mIsAmbientMode=" + mIsAmbientMode);
8602 writer.println(innerPrefix + "mUnbufferedInputSource="
8603 + Integer.toHexString(mUnbufferedInputSource));
8604 if (mAttachInfo != null) {
8605 writer.print(innerPrefix + "mAttachInfo= ");
8606 mAttachInfo.dump(innerPrefix, writer);
8607 } else {
8608 writer.println(innerPrefix + "mAttachInfo=<null>");
8609 }
8610
8611 mFirstInputStage.dump(innerPrefix, writer);
8612
8613 if (mInputEventReceiver != null) {
8614 mInputEventReceiver.dump(innerPrefix, writer);
8615 }
8616
8617 mChoreographer.dump(prefix, writer);
8618
8619 mInsetsController.dump(prefix, writer);
8620
8621 writer.println(prefix + "View Hierarchy:");
8622 dumpViewHierarchy(innerPrefix, writer, mView);
8623 }
8624
8625 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
8626 writer.print(prefix);
8627 if (view == null) {
8628 writer.println("null");
8629 return;
8630 }
8631 writer.println(view.toString());
8632 if (!(view instanceof ViewGroup)) {
8633 return;
8634 }
8635 ViewGroup grp = (ViewGroup)view;
8636 final int N = grp.getChildCount();
8637 if (N <= 0) {
8638 return;
8639 }
8640 prefix = prefix + " ";
8641 for (int i=0; i<N; i++) {
8642 dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
8643 }
8644 }
8645
8646 static final class GfxInfo {
8647 public int viewCount;
8648 public long renderNodeMemoryUsage;
8649 public long renderNodeMemoryAllocated;
8650
8651 void add(GfxInfo other) {
8652 viewCount += other.viewCount;
8653 renderNodeMemoryUsage += other.renderNodeMemoryUsage;
8654 renderNodeMemoryAllocated += other.renderNodeMemoryAllocated;
8655 }
8656 }
8657
8658 GfxInfo getGfxInfo() {
8659 GfxInfo info = new GfxInfo();
8660 if (mView != null) {
8661 appendGfxInfo(mView, info);
8662 }
8663 return info;
8664 }
8665
8666 private static void computeRenderNodeUsage(RenderNode node, GfxInfo info) {
8667 if (node == null) return;
8668 info.renderNodeMemoryUsage += node.computeApproximateMemoryUsage();
8669 info.renderNodeMemoryAllocated += node.computeApproximateMemoryAllocated();
8670 }
8671
8672 private static void appendGfxInfo(View view, GfxInfo info) {
8673 info.viewCount++;
8674 computeRenderNodeUsage(view.mRenderNode, info);
8675 computeRenderNodeUsage(view.mBackgroundRenderNode, info);
8676 if (view instanceof ViewGroup) {
8677 ViewGroup group = (ViewGroup) view;
8678
8679 int count = group.getChildCount();
8680 for (int i = 0; i < count; i++) {
8681 appendGfxInfo(group.getChildAt(i), info);
8682 }
8683 }
8684 }
8685
8686 /**
8687 * @param immediate True, do now if not in traversal. False, put on queue and do later.
8688 * @return True, request has been queued. False, request has been completed.
8689 */
8690 boolean die(boolean immediate) {
8691 // Make sure we do execute immediately if we are in the middle of a traversal or the damage
8692 // done by dispatchDetachedFromWindow will cause havoc on return.
8693 if (immediate && !mIsInTraversal) {
8694 doDie();
8695 return false;
8696 }
8697
8698 if (!mIsDrawing) {
8699 destroyHardwareRenderer();
8700 } else {
8701 Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
8702 " window=" + this + ", title=" + mWindowAttributes.getTitle());
8703 }
8704 mHandler.sendEmptyMessage(MSG_DIE);
8705 return true;
8706 }
8707
8708 void doDie() {
8709 checkThread();
8710 if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
8711 synchronized (this) {
8712 if (mRemoved) {
8713 return;
8714 }
8715 mRemoved = true;
8716 mOnBackInvokedDispatcher.detachFromWindow();
8717 if (mAdded) {
8718 dispatchDetachedFromWindow();
8719 }
8720
8721 if (mAdded && !mFirst) {
8722 destroyHardwareRenderer();
8723
8724 if (mView != null) {
8725 int viewVisibility = mView.getVisibility();
8726 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
8727 if (mWindowAttributesChanged || viewVisibilityChanged) {
8728 // If layout params have been changed, first give them
8729 // to the window manager to make sure it has the correct
8730 // animation info.
8731 try {
8732 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
8733 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
8734 mWindowSession.finishDrawing(
8735 mWindow, null /* postDrawTransaction */, Integer.MAX_VALUE);
8736 }
8737 } catch (RemoteException e) {
8738 }
8739 }
8740
8741 destroySurface();
8742 }
8743 }
8744
8745 // If our window is removed, we might not get notified about losing control.
8746 // Invoking this can release the leashes as soon as possible instead of relying on GC.
8747 mInsetsController.onControlsChanged(null);
8748
8749 mAdded = false;
8750 AnimationHandler.removeRequestor(this);
8751 }
8752 WindowManagerGlobal.getInstance().doRemoveView(this);
8753 }
8754
8755 public void requestUpdateConfiguration(Configuration config) {
8756 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
8757 mHandler.sendMessage(msg);
8758 }
8759
8760 public void loadSystemProperties() {
8761 mHandler.post(new Runnable() {
8762 @Override
8763 public void run() {
8764 // Profiling
8765 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
8766 profileRendering(mAttachInfo.mHasWindowFocus);
8767
8768 // Hardware rendering
8769 if (mAttachInfo.mThreadedRenderer != null) {
8770 if (mAttachInfo.mThreadedRenderer.loadSystemProperties()) {
8771 invalidate();
8772 }
8773 }
8774
8775 // Layout debugging
8776 boolean layout = DisplayProperties.debug_layout().orElse(false);
8777 if (layout != mAttachInfo.mDebugLayout) {
8778 mAttachInfo.mDebugLayout = layout;
8779 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
8780 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
8781 }
8782 }
8783 }
8784 });
8785 }
8786
8787 private void destroyHardwareRenderer() {
8788 ThreadedRenderer hardwareRenderer = mAttachInfo.mThreadedRenderer;
8789
8790 if (hardwareRenderer != null) {
8791 if (mHardwareRendererObserver != null) {
8792 hardwareRenderer.removeObserver(mHardwareRendererObserver);
8793 }
8794 if (mView != null) {
8795 hardwareRenderer.destroyHardwareResources(mView);
8796 }
8797 hardwareRenderer.destroy();
8798 hardwareRenderer.setRequested(false);
8799
8800 mAttachInfo.mThreadedRenderer = null;
8801 mAttachInfo.mHardwareAccelerated = false;
8802 }
8803 }
8804
8805 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8806 private void dispatchResized(ClientWindowFrames frames, boolean reportDraw,
8807 MergedConfiguration mergedConfiguration, InsetsState insetsState, boolean forceLayout,
8808 boolean alwaysConsumeSystemBars, int displayId, int syncSeqId, int resizeMode) {
8809 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
8810 SomeArgs args = SomeArgs.obtain();
8811 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
8812 if (sameProcessCall) {
8813 insetsState = new InsetsState(insetsState, true /* copySource */);
8814 }
8815 if (mTranslator != null) {
8816 mTranslator.translateInsetsStateInScreenToAppWindow(insetsState);
8817 }
8818 if (insetsState.getSourceOrDefaultVisibility(ITYPE_IME)) {
8819 ImeTracing.getInstance().triggerClientDump("ViewRootImpl#dispatchResized",
8820 getInsetsController().getHost().getInputMethodManager(), null /* icProto */);
8821 }
8822 args.arg1 = sameProcessCall ? new ClientWindowFrames(frames) : frames;
8823 args.arg2 = sameProcessCall && mergedConfiguration != null
8824 ? new MergedConfiguration(mergedConfiguration) : mergedConfiguration;
8825 args.arg3 = insetsState;
8826 args.argi1 = forceLayout ? 1 : 0;
8827 args.argi2 = alwaysConsumeSystemBars ? 1 : 0;
8828 args.argi3 = displayId;
8829 args.argi4 = syncSeqId;
8830 args.argi5 = resizeMode;
8831
8832 msg.obj = args;
8833 mHandler.sendMessage(msg);
8834 }
8835
8836 private void dispatchInsetsControlChanged(InsetsState insetsState,
8837 InsetsSourceControl[] activeControls) {
8838 if (Binder.getCallingPid() == android.os.Process.myPid()) {
8839 insetsState = new InsetsState(insetsState, true /* copySource */);
8840 if (activeControls != null) {
8841 for (int i = activeControls.length - 1; i >= 0; i--) {
8842 activeControls[i] = new InsetsSourceControl(activeControls[i]);
8843 }
8844 }
8845 }
8846 if (mTranslator != null) {
8847 mTranslator.translateInsetsStateInScreenToAppWindow(insetsState);
8848 mTranslator.translateSourceControlsInScreenToAppWindow(activeControls);
8849 }
8850 if (insetsState != null && insetsState.getSourceOrDefaultVisibility(ITYPE_IME)) {
8851 ImeTracing.getInstance().triggerClientDump("ViewRootImpl#dispatchInsetsControlChanged",
8852 getInsetsController().getHost().getInputMethodManager(), null /* icProto */);
8853 }
8854 SomeArgs args = SomeArgs.obtain();
8855 args.arg1 = insetsState;
8856 args.arg2 = activeControls;
8857 mHandler.obtainMessage(MSG_INSETS_CONTROL_CHANGED, args).sendToTarget();
8858 }
8859
8860 private void showInsets(@InsetsType int types, boolean fromIme) {
8861 mHandler.obtainMessage(MSG_SHOW_INSETS, types, fromIme ? 1 : 0).sendToTarget();
8862 }
8863
8864 private void hideInsets(@InsetsType int types, boolean fromIme) {
8865 mHandler.obtainMessage(MSG_HIDE_INSETS, types, fromIme ? 1 : 0).sendToTarget();
8866 }
8867
8868 public void dispatchMoved(int newX, int newY) {
8869 if (DEBUG_LAYOUT) Log.v(mTag, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
8870 if (mTranslator != null) {
8871 PointF point = new PointF(newX, newY);
8872 mTranslator.translatePointInScreenToAppWindow(point);
8873 newX = (int) (point.x + 0.5);
8874 newY = (int) (point.y + 0.5);
8875 }
8876 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
8877 mHandler.sendMessage(msg);
8878 }
8879
8880 /**
8881 * Represents a pending input event that is waiting in a queue.
8882 *
8883 * Input events are processed in serial order by the timestamp specified by
8884 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers
8885 * one input event to the application at a time and waits for the application
8886 * to finish handling it before delivering the next one.
8887 *
8888 * However, because the application or IME can synthesize and inject multiple
8889 * key events at a time without going through the input dispatcher, we end up
8890 * needing a queue on the application's side.
8891 */
8892 private static final class QueuedInputEvent {
8893 public static final int FLAG_DELIVER_POST_IME = 1 << 0;
8894 public static final int FLAG_DEFERRED = 1 << 1;
8895 public static final int FLAG_FINISHED = 1 << 2;
8896 public static final int FLAG_FINISHED_HANDLED = 1 << 3;
8897 public static final int FLAG_RESYNTHESIZED = 1 << 4;
8898 public static final int FLAG_UNHANDLED = 1 << 5;
8899 public static final int FLAG_MODIFIED_FOR_COMPATIBILITY = 1 << 6;
8900
8901 public QueuedInputEvent mNext;
8902
8903 public InputEvent mEvent;
8904 public InputEventReceiver mReceiver;
8905 public int mFlags;
8906
8907 public boolean shouldSkipIme() {
8908 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
8909 return true;
8910 }
8911 return mEvent instanceof MotionEvent
8912 && (mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)
8913 || mEvent.isFromSource(InputDevice.SOURCE_ROTARY_ENCODER));
8914 }
8915
8916 public boolean shouldSendToSynthesizer() {
8917 if ((mFlags & FLAG_UNHANDLED) != 0) {
8918 return true;
8919 }
8920
8921 return false;
8922 }
8923
8924 @Override
8925 public String toString() {
8926 StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
8927 boolean hasPrevious = false;
8928 hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
8929 hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
8930 hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
8931 hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
8932 hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
8933 hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
8934 if (!hasPrevious) {
8935 sb.append("0");
8936 }
8937 sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
8938 sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
8939 sb.append(", mEvent=" + mEvent + "}");
8940 return sb.toString();
8941 }
8942
8943 private boolean flagToString(String name, int flag,
8944 boolean hasPrevious, StringBuilder sb) {
8945 if ((mFlags & flag) != 0) {
8946 if (hasPrevious) {
8947 sb.append("|");
8948 }
8949 sb.append(name);
8950 return true;
8951 }
8952 return hasPrevious;
8953 }
8954 }
8955
8956 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
8957 InputEventReceiver receiver, int flags) {
8958 QueuedInputEvent q = mQueuedInputEventPool;
8959 if (q != null) {
8960 mQueuedInputEventPoolSize -= 1;
8961 mQueuedInputEventPool = q.mNext;
8962 q.mNext = null;
8963 } else {
8964 q = new QueuedInputEvent();
8965 }
8966
8967 q.mEvent = event;
8968 q.mReceiver = receiver;
8969 q.mFlags = flags;
8970 return q;
8971 }
8972
8973 private void recycleQueuedInputEvent(QueuedInputEvent q) {
8974 q.mEvent = null;
8975 q.mReceiver = null;
8976
8977 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
8978 mQueuedInputEventPoolSize += 1;
8979 q.mNext = mQueuedInputEventPool;
8980 mQueuedInputEventPool = q;
8981 }
8982 }
8983
8984 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8985 void enqueueInputEvent(InputEvent event) {
8986 enqueueInputEvent(event, null, 0, false);
8987 }
8988
8989 @UnsupportedAppUsage
8990 void enqueueInputEvent(InputEvent event,
8991 InputEventReceiver receiver, int flags, boolean processImmediately) {
8992 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
8993
8994 if (event instanceof MotionEvent) {
8995 MotionEvent me = (MotionEvent) event;
8996 if (me.getAction() == MotionEvent.ACTION_CANCEL) {
8997 EventLog.writeEvent(EventLogTags.VIEW_ENQUEUE_INPUT_EVENT, "Motion - Cancel",
8998 getTitle().toString());
8999 }
9000 } else if (event instanceof KeyEvent) {
9001 KeyEvent ke = (KeyEvent) event;
9002 if (ke.isCanceled()) {
9003 EventLog.writeEvent(EventLogTags.VIEW_ENQUEUE_INPUT_EVENT, "Key - Cancel",
9004 getTitle().toString());
9005 }
9006 }
9007 // Always enqueue the input event in order, regardless of its time stamp.
9008 // We do this because the application or the IME may inject key events
9009 // in response to touch events and we want to ensure that the injected keys
9010 // are processed in the order they were received and we cannot trust that
9011 // the time stamp of injected events are monotonic.
9012 QueuedInputEvent last = mPendingInputEventTail;
9013 if (last == null) {
9014 mPendingInputEventHead = q;
9015 mPendingInputEventTail = q;
9016 } else {
9017 last.mNext = q;
9018 mPendingInputEventTail = q;
9019 }
9020 mPendingInputEventCount += 1;
9021 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
9022 mPendingInputEventCount);
9023
9024 if (processImmediately) {
9025 doProcessInputEvents();
9026 } else {
9027 scheduleProcessInputEvents();
9028 }
9029 }
9030
9031 private void scheduleProcessInputEvents() {
9032 if (!mProcessInputEventsScheduled) {
9033 mProcessInputEventsScheduled = true;
9034 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
9035 msg.setAsynchronous(true);
9036 mHandler.sendMessage(msg);
9037 }
9038 }
9039
9040 void doProcessInputEvents() {
9041 // Deliver all pending input events in the queue.
9042 while (mPendingInputEventHead != null) {
9043 QueuedInputEvent q = mPendingInputEventHead;
9044 mPendingInputEventHead = q.mNext;
9045 if (mPendingInputEventHead == null) {
9046 mPendingInputEventTail = null;
9047 }
9048 q.mNext = null;
9049
9050 mPendingInputEventCount -= 1;
9051 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
9052 mPendingInputEventCount);
9053
9054 mViewFrameInfo.setInputEvent(mInputEventAssigner.processEvent(q.mEvent));
9055
9056 deliverInputEvent(q);
9057 }
9058
9059 // We are done processing all input events that we can process right now
9060 // so we can clear the pending flag immediately.
9061 if (mProcessInputEventsScheduled) {
9062 mProcessInputEventsScheduled = false;
9063 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
9064 }
9065 }
9066
9067 private void deliverInputEvent(QueuedInputEvent q) {
9068 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
9069 q.mEvent.getId());
9070
9071 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
9072 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent src=0x"
9073 + Integer.toHexString(q.mEvent.getSource()) + " eventTimeNano="
9074 + q.mEvent.getEventTimeNano() + " id=0x"
9075 + Integer.toHexString(q.mEvent.getId()));
9076 }
9077 try {
9078 if (mInputEventConsistencyVerifier != null) {
9079 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "verifyEventConsistency");
9080 try {
9081 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
9082 } finally {
9083 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
9084 }
9085 }
9086
9087 InputStage stage;
9088 if (q.shouldSendToSynthesizer()) {
9089 stage = mSyntheticInputStage;
9090 } else {
9091 stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
9092 }
9093
9094 if (q.mEvent instanceof KeyEvent) {
9095 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "preDispatchToUnhandledKeyManager");
9096 try {
9097 mUnhandledKeyManager.preDispatch((KeyEvent) q.mEvent);
9098 } finally {
9099 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
9100 }
9101 }
9102
9103 if (stage != null) {
9104 handleWindowFocusChanged();
9105 stage.deliver(q);
9106 } else {
9107 finishInputEvent(q);
9108 }
9109 } finally {
9110 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
9111 }
9112 }
9113
9114 private void finishInputEvent(QueuedInputEvent q) {
9115 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
9116 q.mEvent.getId());
9117
9118 if (q.mReceiver != null) {
9119 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
9120 boolean modified = (q.mFlags & QueuedInputEvent.FLAG_MODIFIED_FOR_COMPATIBILITY) != 0;
9121 if (modified) {
9122 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "processInputEventBeforeFinish");
9123 InputEvent processedEvent;
9124 try {
9125 processedEvent =
9126 mInputCompatProcessor.processInputEventBeforeFinish(q.mEvent);
9127 } finally {
9128 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
9129 }
9130 if (processedEvent != null) {
9131 q.mReceiver.finishInputEvent(processedEvent, handled);
9132 }
9133 } else {
9134 q.mReceiver.finishInputEvent(q.mEvent, handled);
9135 }
9136 } else {
9137 q.mEvent.recycleIfNeededAfterDispatch();
9138 }
9139
9140 recycleQueuedInputEvent(q);
9141 }
9142
9143 static boolean isTerminalInputEvent(InputEvent event) {
9144 if (event instanceof KeyEvent) {
9145 final KeyEvent keyEvent = (KeyEvent)event;
9146 return keyEvent.getAction() == KeyEvent.ACTION_UP;
9147 } else {
9148 final MotionEvent motionEvent = (MotionEvent)event;
9149 final int action = motionEvent.getAction();
9150 return action == MotionEvent.ACTION_UP
9151 || action == MotionEvent.ACTION_CANCEL
9152 || action == MotionEvent.ACTION_HOVER_EXIT;
9153 }
9154 }
9155
9156 void scheduleConsumeBatchedInput() {
9157 // If anything is currently scheduled to consume batched input then there's no point in
9158 // scheduling it again.
9159 if (!mConsumeBatchedInputScheduled && !mConsumeBatchedInputImmediatelyScheduled) {
9160 mConsumeBatchedInputScheduled = true;
9161 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
9162 mConsumedBatchedInputRunnable, null);
9163 }
9164 }
9165
9166 void unscheduleConsumeBatchedInput() {
9167 if (mConsumeBatchedInputScheduled) {
9168 mConsumeBatchedInputScheduled = false;
9169 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
9170 mConsumedBatchedInputRunnable, null);
9171 }
9172 }
9173
9174 void scheduleConsumeBatchedInputImmediately() {
9175 if (!mConsumeBatchedInputImmediatelyScheduled) {
9176 unscheduleConsumeBatchedInput();
9177 mConsumeBatchedInputImmediatelyScheduled = true;
9178 mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
9179 }
9180 }
9181
9182 boolean doConsumeBatchedInput(long frameTimeNanos) {
9183 final boolean consumedBatches;
9184 if (mInputEventReceiver != null) {
9185 consumedBatches = mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos);
9186 } else {
9187 consumedBatches = false;
9188 }
9189 doProcessInputEvents();
9190 return consumedBatches;
9191 }
9192
9193 final class TraversalRunnable implements Runnable {
9194 @Override
9195 public void run() {
9196 doTraversal();
9197 }
9198 }
9199 final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
9200
9201 final class WindowInputEventReceiver extends InputEventReceiver {
9202 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
9203 super(inputChannel, looper);
9204 }
9205
9206 @Override
9207 public void onInputEvent(InputEvent event) {
9208 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "processInputEventForCompatibility");
9209 List<InputEvent> processedEvents;
9210 try {
9211 processedEvents =
9212 mInputCompatProcessor.processInputEventForCompatibility(event);
9213 } finally {
9214 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
9215 }
9216 if (processedEvents != null) {
9217 if (processedEvents.isEmpty()) {
9218 // InputEvent consumed by mInputCompatProcessor
9219 finishInputEvent(event, true);
9220 } else {
9221 for (int i = 0; i < processedEvents.size(); i++) {
9222 enqueueInputEvent(
9223 processedEvents.get(i), this,
9224 QueuedInputEvent.FLAG_MODIFIED_FOR_COMPATIBILITY, true);
9225 }
9226 }
9227 } else {
9228 enqueueInputEvent(event, this, 0, true);
9229 }
9230 }
9231
9232 @Override
9233 public void onBatchedInputEventPending(int source) {
9234 final boolean unbuffered = mUnbufferedInputDispatch
9235 || (source & mUnbufferedInputSource) != SOURCE_CLASS_NONE;
9236 if (unbuffered) {
9237 if (mConsumeBatchedInputScheduled) {
9238 unscheduleConsumeBatchedInput();
9239 }
9240 // Consume event immediately if unbuffered input dispatch has been requested.
9241 consumeBatchedInputEvents(-1);
9242 return;
9243 }
9244 scheduleConsumeBatchedInput();
9245 }
9246
9247 @Override
9248 public void onFocusEvent(boolean hasFocus) {
9249 windowFocusChanged(hasFocus);
9250 }
9251
9252 @Override
9253 public void onTouchModeChanged(boolean inTouchMode) {
9254 touchModeChanged(inTouchMode);
9255 }
9256
9257 @Override
9258 public void onPointerCaptureEvent(boolean pointerCaptureEnabled) {
9259 dispatchPointerCaptureChanged(pointerCaptureEnabled);
9260 }
9261
9262 @Override
9263 public void onDragEvent(boolean isExiting, float x, float y) {
9264 // force DRAG_EXITED_EVENT if appropriate
9265 DragEvent event = DragEvent.obtain(
9266 isExiting ? DragEvent.ACTION_DRAG_EXITED : DragEvent.ACTION_DRAG_LOCATION,
9267 x, y, 0 /* offsetX */, 0 /* offsetY */, null/* localState */,
9268 null/* description */, null /* data */, null /* dragSurface */,
9269 null /* dragAndDropPermissions */, false /* result */);
9270 dispatchDragEvent(event);
9271 }
9272
9273 @Override
9274 public void dispose() {
9275 unscheduleConsumeBatchedInput();
9276 super.dispose();
9277 }
9278 }
9279 private WindowInputEventReceiver mInputEventReceiver;
9280
9281 final class InputMetricsListener
9282 implements HardwareRendererObserver.OnFrameMetricsAvailableListener {
9283 public long[] data = new long[FrameMetrics.Index.FRAME_STATS_COUNT];
9284
9285 @Override
9286 public void onFrameMetricsAvailable(int dropCountSinceLastInvocation) {
9287 final int inputEventId = (int) data[FrameMetrics.Index.INPUT_EVENT_ID];
9288 if (inputEventId == INVALID_INPUT_EVENT_ID) {
9289 return;
9290 }
9291 final long presentTime = data[FrameMetrics.Index.DISPLAY_PRESENT_TIME];
9292 if (presentTime <= 0) {
9293 // Present time is not available for this frame. If the present time is not
9294 // available, we cannot compute end-to-end input latency metrics.
9295 return;
9296 }
9297 final long gpuCompletedTime = data[FrameMetrics.Index.GPU_COMPLETED];
9298 if (mInputEventReceiver == null) {
9299 return;
9300 }
9301 if (gpuCompletedTime >= presentTime) {
9302 final double discrepancyMs = (gpuCompletedTime - presentTime) * 1E-6;
9303 final long vsyncId = data[FrameMetrics.Index.FRAME_TIMELINE_VSYNC_ID];
9304 Log.w(TAG, "Not reporting timeline because gpuCompletedTime is " + discrepancyMs
9305 + "ms ahead of presentTime. FRAME_TIMELINE_VSYNC_ID=" + vsyncId
9306 + ", INPUT_EVENT_ID=" + inputEventId);
9307 // TODO(b/186664409): figure out why this sometimes happens
9308 return;
9309 }
9310 mInputEventReceiver.reportTimeline(inputEventId, gpuCompletedTime, presentTime);
9311 }
9312 }
9313 HardwareRendererObserver mHardwareRendererObserver;
9314
9315 final class ConsumeBatchedInputRunnable implements Runnable {
9316 @Override
9317 public void run() {
9318 mConsumeBatchedInputScheduled = false;
9319 if (doConsumeBatchedInput(mChoreographer.getFrameTimeNanos())) {
9320 // If we consumed a batch here, we want to go ahead and schedule the
9321 // consumption of batched input events on the next frame. Otherwise, we would
9322 // wait until we have more input events pending and might get starved by other
9323 // things occurring in the process.
9324 scheduleConsumeBatchedInput();
9325 }
9326 }
9327 }
9328 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
9329 new ConsumeBatchedInputRunnable();
9330 boolean mConsumeBatchedInputScheduled;
9331
9332 final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
9333 @Override
9334 public void run() {
9335 mConsumeBatchedInputImmediatelyScheduled = false;
9336 doConsumeBatchedInput(-1);
9337 }
9338 }
9339 final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
9340 new ConsumeBatchedInputImmediatelyRunnable();
9341 boolean mConsumeBatchedInputImmediatelyScheduled;
9342
9343 final class InvalidateOnAnimationRunnable implements Runnable {
9344 private boolean mPosted;
9345 private final ArrayList<View> mViews = new ArrayList<View>();
9346 private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
9347 new ArrayList<AttachInfo.InvalidateInfo>();
9348 private View[] mTempViews;
9349 private AttachInfo.InvalidateInfo[] mTempViewRects;
9350
9351 public void addView(View view) {
9352 synchronized (this) {
9353 mViews.add(view);
9354 postIfNeededLocked();
9355 }
9356 }
9357
9358 public void addViewRect(AttachInfo.InvalidateInfo info) {
9359 synchronized (this) {
9360 mViewRects.add(info);
9361 postIfNeededLocked();
9362 }
9363 }
9364
9365 public void removeView(View view) {
9366 synchronized (this) {
9367 mViews.remove(view);
9368
9369 for (int i = mViewRects.size(); i-- > 0; ) {
9370 AttachInfo.InvalidateInfo info = mViewRects.get(i);
9371 if (info.target == view) {
9372 mViewRects.remove(i);
9373 info.recycle();
9374 }
9375 }
9376
9377 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
9378 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
9379 mPosted = false;
9380 }
9381 }
9382 }
9383
9384 @Override
9385 public void run() {
9386 final int viewCount;
9387 final int viewRectCount;
9388 synchronized (this) {
9389 mPosted = false;
9390
9391 viewCount = mViews.size();
9392 if (viewCount != 0) {
9393 mTempViews = mViews.toArray(mTempViews != null
9394 ? mTempViews : new View[viewCount]);
9395 mViews.clear();
9396 }
9397
9398 viewRectCount = mViewRects.size();
9399 if (viewRectCount != 0) {
9400 mTempViewRects = mViewRects.toArray(mTempViewRects != null
9401 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
9402 mViewRects.clear();
9403 }
9404 }
9405
9406 for (int i = 0; i < viewCount; i++) {
9407 mTempViews[i].invalidate();
9408 mTempViews[i] = null;
9409 }
9410
9411 for (int i = 0; i < viewRectCount; i++) {
9412 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
9413 info.target.invalidate(info.left, info.top, info.right, info.bottom);
9414 info.recycle();
9415 }
9416 }
9417
9418 private void postIfNeededLocked() {
9419 if (!mPosted) {
9420 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
9421 mPosted = true;
9422 }
9423 }
9424 }
9425 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
9426 new InvalidateOnAnimationRunnable();
9427
9428 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
9429 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
9430 mHandler.sendMessageDelayed(msg, delayMilliseconds);
9431 }
9432
9433 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
9434 long delayMilliseconds) {
9435 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
9436 mHandler.sendMessageDelayed(msg, delayMilliseconds);
9437 }
9438
9439 public void dispatchInvalidateOnAnimation(View view) {
9440 mInvalidateOnAnimationRunnable.addView(view);
9441 }
9442
9443 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
9444 mInvalidateOnAnimationRunnable.addViewRect(info);
9445 }
9446
9447 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9448 public void cancelInvalidate(View view) {
9449 mHandler.removeMessages(MSG_INVALIDATE, view);
9450 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
9451 // them to the pool
9452 mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
9453 mInvalidateOnAnimationRunnable.removeView(view);
9454 }
9455
9456 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9457 public void dispatchInputEvent(InputEvent event) {
9458 dispatchInputEvent(event, null);
9459 }
9460
9461 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9462 public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
9463 SomeArgs args = SomeArgs.obtain();
9464 args.arg1 = event;
9465 args.arg2 = receiver;
9466 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
9467 msg.setAsynchronous(true);
9468 mHandler.sendMessage(msg);
9469 }
9470
9471 public void synthesizeInputEvent(InputEvent event) {
9472 Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
9473 msg.setAsynchronous(true);
9474 mHandler.sendMessage(msg);
9475 }
9476
9477 @UnsupportedAppUsage
9478 public void dispatchKeyFromIme(KeyEvent event) {
9479 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
9480 msg.setAsynchronous(true);
9481 mHandler.sendMessage(msg);
9482 }
9483
9484 public void dispatchKeyFromAutofill(KeyEvent event) {
9485 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_AUTOFILL, event);
9486 msg.setAsynchronous(true);
9487 mHandler.sendMessage(msg);
9488 }
9489
9490 /**
9491 * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
9492 *
9493 * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
9494 * passes in.
9495 */
9496 @UnsupportedAppUsage
9497 public void dispatchUnhandledInputEvent(InputEvent event) {
9498 if (event instanceof MotionEvent) {
9499 event = MotionEvent.obtain((MotionEvent) event);
9500 }
9501 synthesizeInputEvent(event);
9502 }
9503
9504 public void dispatchAppVisibility(boolean visible) {
9505 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
9506 msg.arg1 = visible ? 1 : 0;
9507 mHandler.sendMessage(msg);
9508 }
9509
9510 public void dispatchGetNewSurface() {
9511 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
9512 mHandler.sendMessage(msg);
9513 }
9514
9515 /**
9516 * Notifies this {@link ViewRootImpl} object that window focus has changed.
9517 */
9518 public void windowFocusChanged(boolean hasFocus) {
9519 synchronized (this) {
9520 mWindowFocusChanged = true;
9521 mUpcomingWindowFocus = hasFocus;
9522 }
9523 Message msg = Message.obtain();
9524 msg.what = MSG_WINDOW_FOCUS_CHANGED;
9525 mHandler.sendMessage(msg);
9526 }
9527
9528 /**
9529 * Notifies this {@link ViewRootImpl} object that touch mode state has changed.
9530 */
9531 public void touchModeChanged(boolean inTouchMode) {
9532 synchronized (this) {
9533 mUpcomingInTouchMode = inTouchMode;
9534 }
9535 Message msg = Message.obtain();
9536 msg.what = MSG_WINDOW_TOUCH_MODE_CHANGED;
9537 mHandler.sendMessage(msg);
9538 }
9539
9540 public void dispatchWindowShown() {
9541 mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
9542 }
9543
9544 public void dispatchCloseSystemDialogs(String reason) {
9545 Message msg = Message.obtain();
9546 msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
9547 msg.obj = reason;
9548 mHandler.sendMessage(msg);
9549 }
9550
9551 public void dispatchDragEvent(DragEvent event) {
9552 final int what;
9553 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
9554 what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
9555 mHandler.removeMessages(what);
9556 } else {
9557 what = MSG_DISPATCH_DRAG_EVENT;
9558 }
9559 Message msg = mHandler.obtainMessage(what, event);
9560 mHandler.sendMessage(msg);
9561 }
9562
9563 public void updatePointerIcon(float x, float y) {
9564 final int what = MSG_UPDATE_POINTER_ICON;
9565 mHandler.removeMessages(what);
9566 final long now = SystemClock.uptimeMillis();
9567 final MotionEvent event = MotionEvent.obtain(
9568 0, now, MotionEvent.ACTION_HOVER_MOVE, x, y, 0);
9569 Message msg = mHandler.obtainMessage(what, event);
9570 mHandler.sendMessage(msg);
9571 }
9572
9573 public void dispatchCheckFocus() {
9574 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
9575 // This will result in a call to checkFocus() below.
9576 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
9577 }
9578 }
9579
9580 public void dispatchRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
9581 mHandler.obtainMessage(
9582 MSG_REQUEST_KEYBOARD_SHORTCUTS, deviceId, 0, receiver).sendToTarget();
9583 }
9584
9585 private void dispatchPointerCaptureChanged(boolean on) {
9586 final int what = MSG_POINTER_CAPTURE_CHANGED;
9587 mHandler.removeMessages(what);
9588 Message msg = mHandler.obtainMessage(what);
9589 msg.arg1 = on ? 1 : 0;
9590 mHandler.sendMessage(msg);
9591 }
9592
9593 /**
9594 * Post a callback to send a
9595 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
9596 * This event is send at most once every
9597 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9598 */
9599 private void postSendWindowContentChangedCallback(View source, int changeType) {
9600 if (mSendWindowContentChangedAccessibilityEvent == null) {
9601 mSendWindowContentChangedAccessibilityEvent =
9602 new SendWindowContentChangedAccessibilityEvent();
9603 }
9604 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
9605 }
9606
9607 /**
9608 * Remove a posted callback to send a
9609 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
9610 */
9611 private void removeSendWindowContentChangedCallback() {
9612 if (mSendWindowContentChangedAccessibilityEvent != null) {
9613 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
9614 }
9615 }
9616
9617 @Override
9618 public boolean showContextMenuForChild(View originalView) {
9619 return false;
9620 }
9621
9622 @Override
9623 public boolean showContextMenuForChild(View originalView, float x, float y) {
9624 return false;
9625 }
9626
9627 @Override
9628 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
9629 return null;
9630 }
9631
9632 @Override
9633 public ActionMode startActionModeForChild(
9634 View originalView, ActionMode.Callback callback, int type) {
9635 return null;
9636 }
9637
9638 @Override
9639 public void createContextMenu(ContextMenu menu) {
9640 }
9641
9642 @Override
9643 public void childDrawableStateChanged(View child) {
9644 }
9645
9646 @Override
9647 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
9648 if (mView == null || mStopped || mPausedForTransition) {
9649 return false;
9650 }
9651
9652 // Immediately flush pending content changed event (if any) to preserve event order
9653 if (event.getEventType() != AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
9654 && mSendWindowContentChangedAccessibilityEvent != null
9655 && mSendWindowContentChangedAccessibilityEvent.mSource != null) {
9656 mSendWindowContentChangedAccessibilityEvent.removeCallbacksAndRun();
9657 }
9658
9659 // Intercept accessibility focus events fired by virtual nodes to keep
9660 // track of accessibility focus position in such nodes.
9661 final int eventType = event.getEventType();
9662 final View source = getSourceForAccessibilityEvent(event);
9663 switch (eventType) {
9664 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
9665 if (source != null) {
9666 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
9667 if (provider != null) {
9668 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
9669 event.getSourceNodeId());
9670 final AccessibilityNodeInfo node;
9671 node = provider.createAccessibilityNodeInfo(virtualNodeId);
9672 setAccessibilityFocus(source, node);
9673 }
9674 }
9675 } break;
9676 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
9677 if (source != null && source.getAccessibilityNodeProvider() != null) {
9678 setAccessibilityFocus(null, null);
9679 }
9680 } break;
9681
9682
9683 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
9684 handleWindowContentChangedEvent(event);
9685 } break;
9686 }
9687 mAccessibilityManager.sendAccessibilityEvent(event);
9688 return true;
9689 }
9690
9691 private View getSourceForAccessibilityEvent(AccessibilityEvent event) {
9692 final long sourceNodeId = event.getSourceNodeId();
9693 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
9694 sourceNodeId);
9695 return AccessibilityNodeIdManager.getInstance().findView(accessibilityViewId);
9696 }
9697
9698 /**
9699 * Updates the focused virtual view, when necessary, in response to a
9700 * content changed event.
9701 * <p>
9702 * This is necessary to get updated bounds after a position change.
9703 *
9704 * @param event an accessibility event of type
9705 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
9706 */
9707 private void handleWindowContentChangedEvent(AccessibilityEvent event) {
9708 final View focusedHost = mAccessibilityFocusedHost;
9709 if (focusedHost == null || mAccessibilityFocusedVirtualView == null) {
9710 // No virtual view focused, nothing to do here.
9711 return;
9712 }
9713
9714 final AccessibilityNodeProvider provider = focusedHost.getAccessibilityNodeProvider();
9715 if (provider == null) {
9716 // Error state: virtual view with no provider. Clear focus.
9717 mAccessibilityFocusedHost = null;
9718 mAccessibilityFocusedVirtualView = null;
9719 focusedHost.clearAccessibilityFocusNoCallbacks(0);
9720 return;
9721 }
9722
9723 // We only care about change types that may affect the bounds of the
9724 // focused virtual view.
9725 final int changes = event.getContentChangeTypes();
9726 if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
9727 && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
9728 return;
9729 }
9730
9731 final long eventSourceNodeId = event.getSourceNodeId();
9732 final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
9733
9734 // Search up the tree for subtree containment.
9735 boolean hostInSubtree = false;
9736 View root = mAccessibilityFocusedHost;
9737 while (root != null && !hostInSubtree) {
9738 if (changedViewId == root.getAccessibilityViewId()) {
9739 hostInSubtree = true;
9740 } else {
9741 final ViewParent parent = root.getParent();
9742 if (parent instanceof View) {
9743 root = (View) parent;
9744 } else {
9745 root = null;
9746 }
9747 }
9748 }
9749
9750 // We care only about changes in subtrees containing the host view.
9751 if (!hostInSubtree) {
9752 return;
9753 }
9754
9755 final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
9756 int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
9757
9758 // Refresh the node for the focused virtual view.
9759 final Rect oldBounds = mTempRect;
9760 mAccessibilityFocusedVirtualView.getBoundsInScreen(oldBounds);
9761 mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
9762 if (mAccessibilityFocusedVirtualView == null) {
9763 // Error state: The node no longer exists. Clear focus.
9764 mAccessibilityFocusedHost = null;
9765 focusedHost.clearAccessibilityFocusNoCallbacks(0);
9766
9767 // This will probably fail, but try to keep the provider's internal
9768 // state consistent by clearing focus.
9769 provider.performAction(focusedChildId,
9770 AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS.getId(), null);
9771 invalidateRectOnScreen(oldBounds);
9772 } else {
9773 // The node was refreshed, invalidate bounds if necessary.
9774 final Rect newBounds = mAccessibilityFocusedVirtualView.getBoundsInScreen();
9775 if (!oldBounds.equals(newBounds)) {
9776 oldBounds.union(newBounds);
9777 invalidateRectOnScreen(oldBounds);
9778 }
9779 }
9780 }
9781
9782 @Override
9783 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
9784 postSendWindowContentChangedCallback(Preconditions.checkNotNull(source), changeType);
9785 }
9786
9787 @Override
9788 public boolean canResolveLayoutDirection() {
9789 return true;
9790 }
9791
9792 @Override
9793 public boolean isLayoutDirectionResolved() {
9794 return true;
9795 }
9796
9797 @Override
9798 public int getLayoutDirection() {
9799 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
9800 }
9801
9802 @Override
9803 public boolean canResolveTextDirection() {
9804 return true;
9805 }
9806
9807 @Override
9808 public boolean isTextDirectionResolved() {
9809 return true;
9810 }
9811
9812 @Override
9813 public int getTextDirection() {
9814 return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
9815 }
9816
9817 @Override
9818 public boolean canResolveTextAlignment() {
9819 return true;
9820 }
9821
9822 @Override
9823 public boolean isTextAlignmentResolved() {
9824 return true;
9825 }
9826
9827 @Override
9828 public int getTextAlignment() {
9829 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
9830 }
9831
9832 private View getCommonPredecessor(View first, View second) {
9833 if (mTempHashSet == null) {
9834 mTempHashSet = new HashSet<View>();
9835 }
9836 HashSet<View> seen = mTempHashSet;
9837 seen.clear();
9838 View firstCurrent = first;
9839 while (firstCurrent != null) {
9840 seen.add(firstCurrent);
9841 ViewParent firstCurrentParent = firstCurrent.mParent;
9842 if (firstCurrentParent instanceof View) {
9843 firstCurrent = (View) firstCurrentParent;
9844 } else {
9845 firstCurrent = null;
9846 }
9847 }
9848 View secondCurrent = second;
9849 while (secondCurrent != null) {
9850 if (seen.contains(secondCurrent)) {
9851 seen.clear();
9852 return secondCurrent;
9853 }
9854 ViewParent secondCurrentParent = secondCurrent.mParent;
9855 if (secondCurrentParent instanceof View) {
9856 secondCurrent = (View) secondCurrentParent;
9857 } else {
9858 secondCurrent = null;
9859 }
9860 }
9861 seen.clear();
9862 return null;
9863 }
9864
9865 void checkThread() {
9866 if (mThread != Thread.currentThread()) {
9867 throw new CalledFromWrongThreadException(
9868 "Only the original thread that created a view hierarchy can touch its views.");
9869 }
9870 }
9871
9872 @Override
9873 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
9874 // ViewAncestor never intercepts touch event, so this can be a no-op
9875 }
9876
9877 @Override
9878 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
9879 if (rectangle == null) {
9880 return scrollToRectOrFocus(null, immediate);
9881 }
9882 rectangle.offset(child.getLeft() - child.getScrollX(),
9883 child.getTop() - child.getScrollY());
9884 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
9885 mTempRect.set(rectangle);
9886 mTempRect.offset(0, -mCurScrollY);
9887 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
9888 try {
9889 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
9890 } catch (RemoteException re) {
9891 /* ignore */
9892 }
9893 return scrolled;
9894 }
9895
9896 @Override
9897 public void childHasTransientStateChanged(View child, boolean hasTransientState) {
9898 // Do nothing.
9899 }
9900
9901 @Override
9902 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
9903 return false;
9904 }
9905
9906 @Override
9907 public void onStopNestedScroll(View target) {
9908 }
9909
9910 @Override
9911 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
9912 }
9913
9914 @Override
9915 public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
9916 int dxUnconsumed, int dyUnconsumed) {
9917 }
9918
9919 @Override
9920 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
9921 }
9922
9923 @Override
9924 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
9925 return false;
9926 }
9927
9928 @Override
9929 public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
9930 return false;
9931 }
9932
9933 @Override
9934 public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
9935 return false;
9936 }
9937
9938 /**
9939 * Adds a scroll capture callback to this window.
9940 *
9941 * @param callback the callback to add
9942 */
9943 public void addScrollCaptureCallback(ScrollCaptureCallback callback) {
9944 if (mRootScrollCaptureCallbacks == null) {
9945 mRootScrollCaptureCallbacks = new HashSet<>();
9946 }
9947 mRootScrollCaptureCallbacks.add(callback);
9948 }
9949
9950 /**
9951 * Removes a scroll capture callback from this window.
9952 *
9953 * @param callback the callback to remove
9954 */
9955 public void removeScrollCaptureCallback(ScrollCaptureCallback callback) {
9956 if (mRootScrollCaptureCallbacks != null) {
9957 mRootScrollCaptureCallbacks.remove(callback);
9958 if (mRootScrollCaptureCallbacks.isEmpty()) {
9959 mRootScrollCaptureCallbacks = null;
9960 }
9961 }
9962 }
9963
9964 /**
9965 * Dispatches a scroll capture request to the view hierarchy on the ui thread.
9966 *
9967 * @param listener for the response
9968 */
9969 public void dispatchScrollCaptureRequest(@NonNull IScrollCaptureResponseListener listener) {
9970 mHandler.obtainMessage(MSG_REQUEST_SCROLL_CAPTURE, listener).sendToTarget();
9971 }
9972
9973 /**
9974 * Collect and include any ScrollCaptureCallback instances registered with the window.
9975 *
9976 * @see #addScrollCaptureCallback(ScrollCaptureCallback)
9977 * @param results an object to collect the results of the search
9978 */
9979 private void collectRootScrollCaptureTargets(ScrollCaptureSearchResults results) {
9980 if (mRootScrollCaptureCallbacks == null) {
9981 return;
9982 }
9983 for (ScrollCaptureCallback cb : mRootScrollCaptureCallbacks) {
9984 // Add to the list for consideration
9985 Point offset = new Point(mView.getLeft(), mView.getTop());
9986 Rect rect = new Rect(0, 0, mView.getWidth(), mView.getHeight());
9987 results.addTarget(new ScrollCaptureTarget(mView, rect, offset, cb));
9988 }
9989 }
9990
9991 /**
9992 * Update the timeout for scroll capture requests. Only affects this view root.
9993 * The default value is {@link #SCROLL_CAPTURE_REQUEST_TIMEOUT_MILLIS}.
9994 *
9995 * @param timeMillis the new timeout in milliseconds
9996 */
9997 public void setScrollCaptureRequestTimeout(int timeMillis) {
9998 mScrollCaptureRequestTimeout = timeMillis;
9999 }
10000
10001 /**
10002 * Get the current timeout for scroll capture requests.
10003 *
10004 * @return the timeout in milliseconds
10005 */
10006 public long getScrollCaptureRequestTimeout() {
10007 return mScrollCaptureRequestTimeout;
10008 }
10009
10010 /**
10011 * Handles an inbound request for scroll capture from the system. A search will be
10012 * dispatched through the view tree to locate scrolling content.
10013 * <p>
10014 * A call to
10015 * {@link IScrollCaptureResponseListener#onScrollCaptureResponse} will follow.
10016 *
10017 * @param listener to receive responses
10018 * @see ScrollCaptureSearchResults
10019 */
10020 public void handleScrollCaptureRequest(@NonNull IScrollCaptureResponseListener listener) {
10021 ScrollCaptureSearchResults results =
10022 new ScrollCaptureSearchResults(mContext.getMainExecutor());
10023
10024 // Window (root) level callbacks
10025 collectRootScrollCaptureTargets(results);
10026
10027 // Search through View-tree
10028 View rootView = getView();
10029 if (rootView != null) {
10030 Point point = new Point();
10031 Rect rect = new Rect(0, 0, rootView.getWidth(), rootView.getHeight());
10032 getChildVisibleRect(rootView, rect, point);
10033 rootView.dispatchScrollCaptureSearch(rect, point, results::addTarget);
10034 }
10035 Runnable onComplete = () -> dispatchScrollCaptureSearchResponse(listener, results);
10036 results.setOnCompleteListener(onComplete);
10037 if (!results.isComplete()) {
10038 mHandler.postDelayed(results::finish, getScrollCaptureRequestTimeout());
10039 }
10040 }
10041
10042 /** Called by {@link #handleScrollCaptureRequest} when a result is returned */
10043 private void dispatchScrollCaptureSearchResponse(
10044 @NonNull IScrollCaptureResponseListener listener,
10045 @NonNull ScrollCaptureSearchResults results) {
10046
10047 ScrollCaptureTarget selectedTarget = results.getTopResult();
10048
10049 ScrollCaptureResponse.Builder response = new ScrollCaptureResponse.Builder();
10050 response.setWindowTitle(getTitle().toString());
10051 response.setPackageName(mContext.getPackageName());
10052
10053 StringWriter writer = new StringWriter();
10054 IndentingPrintWriter pw = new IndentingPrintWriter(writer);
10055 results.dump(pw);
10056 pw.flush();
10057 response.addMessage(writer.toString());
10058
10059 if (selectedTarget == null) {
10060 response.setDescription("No scrollable targets found in window");
10061 try {
10062 listener.onScrollCaptureResponse(response.build());
10063 } catch (RemoteException e) {
10064 Log.e(TAG, "Failed to send scroll capture search result", e);
10065 }
10066 return;
10067 }
10068
10069 response.setDescription("Connected");
10070
10071 // Compute area covered by scrolling content within window
10072 Rect boundsInWindow = new Rect();
10073 View containingView = selectedTarget.getContainingView();
10074 containingView.getLocationInWindow(mAttachInfo.mTmpLocation);
10075 boundsInWindow.set(selectedTarget.getScrollBounds());
10076 boundsInWindow.offset(mAttachInfo.mTmpLocation[0], mAttachInfo.mTmpLocation[1]);
10077 response.setBoundsInWindow(boundsInWindow);
10078
10079 // Compute the area on screen covered by the window
10080 Rect boundsOnScreen = new Rect();
10081 mView.getLocationOnScreen(mAttachInfo.mTmpLocation);
10082 boundsOnScreen.set(0, 0, mView.getWidth(), mView.getHeight());
10083 boundsOnScreen.offset(mAttachInfo.mTmpLocation[0], mAttachInfo.mTmpLocation[1]);
10084 response.setWindowBounds(boundsOnScreen);
10085
10086 // Create a connection and return it to the caller
10087 ScrollCaptureConnection connection = new ScrollCaptureConnection(
10088 mView.getContext().getMainExecutor(), selectedTarget);
10089 response.setConnection(connection);
10090
10091 try {
10092 listener.onScrollCaptureResponse(response.build());
10093 } catch (RemoteException e) {
10094 if (DEBUG_SCROLL_CAPTURE) {
10095 Log.w(TAG, "Failed to send scroll capture search response.", e);
10096 }
10097 connection.close();
10098 }
10099 }
10100
10101 private void reportNextDraw(String reason) {
10102 if (DEBUG_BLAST) {
10103 Log.d(mTag, "reportNextDraw " + Debug.getCallers(5));
10104 }
10105 mReportNextDraw = true;
10106 mLastReportNextDrawReason = reason;
10107 }
10108
10109 /**
10110 * Force the window to report its next draw.
10111 * <p>
10112 * This method is only supposed to be used to speed up the interaction from SystemUI and window
10113 * manager when waiting for the first frame to be drawn when turning on the screen. DO NOT USE
10114 * unless you fully understand this interaction.
10115 *
10116 * @param syncBuffer If true, the transaction that contains the buffer from the draw should be
10117 * sent to system to be synced. If false, VRI will not try to sync the buffer,
10118 * but only report back that a buffer was drawn.
10119 * @param reason A debug string indicating the reason for reporting the next draw
10120 * @hide
10121 */
10122 public void setReportNextDraw(boolean syncBuffer, String reason) {
10123 mSyncBuffer = syncBuffer;
10124 reportNextDraw(reason);
10125 invalidate();
10126 }
10127
10128 void changeCanvasOpacity(boolean opaque) {
10129 Log.d(mTag, "changeCanvasOpacity: opaque=" + opaque);
10130 opaque = opaque & ((mView.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0);
10131 if (mAttachInfo.mThreadedRenderer != null) {
10132 mAttachInfo.mThreadedRenderer.setOpaque(opaque);
10133 }
10134 }
10135
10136 /**
10137 * Dispatches a KeyEvent to all registered key fallback handlers.
10138 *
10139 * @param event
10140 * @return {@code true} if the event was handled, {@code false} otherwise.
10141 */
10142 public boolean dispatchUnhandledKeyEvent(KeyEvent event) {
10143 return mUnhandledKeyManager.dispatch(mView, event);
10144 }
10145
10146 class TakenSurfaceHolder extends BaseSurfaceHolder {
10147 @Override
10148 public boolean onAllowLockCanvas() {
10149 return mDrawingAllowed;
10150 }
10151
10152 @Override
10153 public void onRelayoutContainer() {
10154 // Not currently interesting -- from changing between fixed and layout size.
10155 }
10156
10157 @Override
10158 public void setFormat(int format) {
10159 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
10160 }
10161
10162 @Override
10163 public void setType(int type) {
10164 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
10165 }
10166
10167 @Override
10168 public void onUpdateSurface() {
10169 // We take care of format and type changes on our own.
10170 throw new IllegalStateException("Shouldn't be here");
10171 }
10172
10173 @Override
10174 public boolean isCreating() {
10175 return mIsCreating;
10176 }
10177
10178 @Override
10179 public void setFixedSize(int width, int height) {
10180 throw new UnsupportedOperationException(
10181 "Currently only support sizing from layout");
10182 }
10183
10184 @Override
10185 public void setKeepScreenOn(boolean screenOn) {
10186 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
10187 }
10188 }
10189
10190 static class W extends IWindow.Stub {
10191 private final WeakReference<ViewRootImpl> mViewAncestor;
10192 private final IWindowSession mWindowSession;
10193
10194 W(ViewRootImpl viewAncestor) {
10195 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
10196 mWindowSession = viewAncestor.mWindowSession;
10197 }
10198
10199 @Override
10200 public void resized(ClientWindowFrames frames, boolean reportDraw,
10201 MergedConfiguration mergedConfiguration, InsetsState insetsState,
10202 boolean forceLayout, boolean alwaysConsumeSystemBars, int displayId, int syncSeqId,
10203 int resizeMode) {
10204 final ViewRootImpl viewAncestor = mViewAncestor.get();
10205 if (viewAncestor != null) {
10206 viewAncestor.dispatchResized(frames, reportDraw, mergedConfiguration, insetsState,
10207 forceLayout, alwaysConsumeSystemBars, displayId, syncSeqId, resizeMode);
10208 }
10209 }
10210
10211 @Override
10212 public void insetsControlChanged(InsetsState insetsState,
10213 InsetsSourceControl[] activeControls) {
10214 final ViewRootImpl viewAncestor = mViewAncestor.get();
10215 if (viewAncestor != null) {
10216 viewAncestor.dispatchInsetsControlChanged(insetsState, activeControls);
10217 }
10218 }
10219
10220 @Override
10221 public void showInsets(@InsetsType int types, boolean fromIme) {
10222 final ViewRootImpl viewAncestor = mViewAncestor.get();
10223 if (fromIme) {
10224 ImeTracing.getInstance().triggerClientDump("ViewRootImpl.W#showInsets",
10225 viewAncestor.getInsetsController().getHost().getInputMethodManager(),
10226 null /* icProto */);
10227 }
10228 if (viewAncestor != null) {
10229 viewAncestor.showInsets(types, fromIme);
10230 }
10231 }
10232
10233 @Override
10234 public void hideInsets(@InsetsType int types, boolean fromIme) {
10235
10236 final ViewRootImpl viewAncestor = mViewAncestor.get();
10237 if (fromIme) {
10238 ImeTracing.getInstance().triggerClientDump("ViewRootImpl.W#hideInsets",
10239 viewAncestor.getInsetsController().getHost().getInputMethodManager(),
10240 null /* icProto */);
10241 }
10242 if (viewAncestor != null) {
10243 viewAncestor.hideInsets(types, fromIme);
10244 }
10245 }
10246
10247 @Override
10248 public void moved(int newX, int newY) {
10249 final ViewRootImpl viewAncestor = mViewAncestor.get();
10250 if (viewAncestor != null) {
10251 viewAncestor.dispatchMoved(newX, newY);
10252 }
10253 }
10254
10255 @Override
10256 public void dispatchAppVisibility(boolean visible) {
10257 final ViewRootImpl viewAncestor = mViewAncestor.get();
10258 if (viewAncestor != null) {
10259 viewAncestor.dispatchAppVisibility(visible);
10260 }
10261 }
10262
10263 @Override
10264 public void dispatchGetNewSurface() {
10265 final ViewRootImpl viewAncestor = mViewAncestor.get();
10266 if (viewAncestor != null) {
10267 viewAncestor.dispatchGetNewSurface();
10268 }
10269 }
10270
10271 private static int checkCallingPermission(String permission) {
10272 try {
10273 return ActivityManager.getService().checkPermission(
10274 permission, Binder.getCallingPid(), Binder.getCallingUid());
10275 } catch (RemoteException e) {
10276 return PackageManager.PERMISSION_DENIED;
10277 }
10278 }
10279
10280 @Override
10281 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
10282 final ViewRootImpl viewAncestor = mViewAncestor.get();
10283 if (viewAncestor != null) {
10284 final View view = viewAncestor.mView;
10285 if (view != null) {
10286 if (checkCallingPermission(Manifest.permission.DUMP) !=
10287 PackageManager.PERMISSION_GRANTED) {
10288 throw new SecurityException("Insufficient permissions to invoke"
10289 + " executeCommand() from pid=" + Binder.getCallingPid()
10290 + ", uid=" + Binder.getCallingUid());
10291 }
10292
10293 OutputStream clientStream = null;
10294 try {
10295 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
10296 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
10297 } catch (IOException e) {
10298 e.printStackTrace();
10299 } finally {
10300 if (clientStream != null) {
10301 try {
10302 clientStream.close();
10303 } catch (IOException e) {
10304 e.printStackTrace();
10305 }
10306 }
10307 }
10308 }
10309 }
10310 }
10311
10312 @Override
10313 public void closeSystemDialogs(String reason) {
10314 final ViewRootImpl viewAncestor = mViewAncestor.get();
10315 if (viewAncestor != null) {
10316 viewAncestor.dispatchCloseSystemDialogs(reason);
10317 }
10318 }
10319
10320 @Override
10321 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
10322 float zoom, boolean sync) {
10323 if (sync) {
10324 try {
10325 mWindowSession.wallpaperOffsetsComplete(asBinder());
10326 } catch (RemoteException e) {
10327 }
10328 }
10329 }
10330
10331 @Override
10332 public void dispatchWallpaperCommand(String action, int x, int y,
10333 int z, Bundle extras, boolean sync) {
10334 if (sync) {
10335 try {
10336 mWindowSession.wallpaperCommandComplete(asBinder(), null);
10337 } catch (RemoteException e) {
10338 }
10339 }
10340 }
10341
10342 /* Drag/drop */
10343 @Override
10344 public void dispatchDragEvent(DragEvent event) {
10345 final ViewRootImpl viewAncestor = mViewAncestor.get();
10346 if (viewAncestor != null) {
10347 viewAncestor.dispatchDragEvent(event);
10348 }
10349 }
10350
10351 @Override
10352 public void updatePointerIcon(float x, float y) {
10353 final ViewRootImpl viewAncestor = mViewAncestor.get();
10354 if (viewAncestor != null) {
10355 viewAncestor.updatePointerIcon(x, y);
10356 }
10357 }
10358
10359 @Override
10360 public void dispatchWindowShown() {
10361 final ViewRootImpl viewAncestor = mViewAncestor.get();
10362 if (viewAncestor != null) {
10363 viewAncestor.dispatchWindowShown();
10364 }
10365 }
10366
10367 @Override
10368 public void requestAppKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
10369 ViewRootImpl viewAncestor = mViewAncestor.get();
10370 if (viewAncestor != null) {
10371 viewAncestor.dispatchRequestKeyboardShortcuts(receiver, deviceId);
10372 }
10373 }
10374
10375 @Override
10376 public void requestScrollCapture(IScrollCaptureResponseListener listener) {
10377 final ViewRootImpl viewAncestor = mViewAncestor.get();
10378 if (viewAncestor != null) {
10379 viewAncestor.dispatchScrollCaptureRequest(listener);
10380 }
10381 }
10382 }
10383
10384 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
10385 @UnsupportedAppUsage
10386 public CalledFromWrongThreadException(String msg) {
10387 super(msg);
10388 }
10389 }
10390
10391 static HandlerActionQueue getRunQueue() {
10392 HandlerActionQueue rq = sRunQueues.get();
10393 if (rq != null) {
10394 return rq;
10395 }
10396 rq = new HandlerActionQueue();
10397 sRunQueues.set(rq);
10398 return rq;
10399 }
10400
10401 /**
10402 * Start a drag resizing which will inform all listeners that a window resize is taking place.
10403 */
10404 private void startDragResizing(Rect initialBounds, boolean fullscreen, Rect systemInsets,
10405 Rect stableInsets, int resizeMode) {
10406 if (!mDragResizing) {
10407 mDragResizing = true;
10408 if (mUseMTRenderer) {
10409 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
10410 mWindowCallbacks.get(i).onWindowDragResizeStart(
10411 initialBounds, fullscreen, systemInsets, stableInsets, resizeMode);
10412 }
10413 }
10414 mFullRedrawNeeded = true;
10415 }
10416 }
10417
10418 /**
10419 * End a drag resize which will inform all listeners that a window resize has ended.
10420 */
10421 private void endDragResizing() {
10422 if (mDragResizing) {
10423 mDragResizing = false;
10424 if (mUseMTRenderer) {
10425 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
10426 mWindowCallbacks.get(i).onWindowDragResizeEnd();
10427 }
10428 }
10429 mFullRedrawNeeded = true;
10430 }
10431 }
10432
10433 private boolean updateContentDrawBounds() {
10434 boolean updated = false;
10435 if (mUseMTRenderer) {
10436 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
10437 updated |=
10438 mWindowCallbacks.get(i).onContentDrawn(mWindowAttributes.surfaceInsets.left,
10439 mWindowAttributes.surfaceInsets.top, mWidth, mHeight);
10440 }
10441 }
10442 return updated | (mDragResizing && mReportNextDraw);
10443 }
10444
10445 private void requestDrawWindow() {
10446 if (!mUseMTRenderer) {
10447 return;
10448 }
10449 // Only wait if it will report next draw.
10450 if (mReportNextDraw) {
10451 mWindowDrawCountDown = new CountDownLatch(mWindowCallbacks.size());
10452 }
10453 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
10454 mWindowCallbacks.get(i).onRequestDraw(mReportNextDraw);
10455 }
10456 }
10457
10458 /**
10459 * Tells this instance that its corresponding activity has just relaunched. In this case, we
10460 * need to force a relayout of the window to make sure we get the correct bounds from window
10461 * manager.
10462 */
10463 public void reportActivityRelaunched() {
10464 mActivityRelaunched = true;
10465 }
10466
10467 public SurfaceControl getSurfaceControl() {
10468 return mSurfaceControl;
10469 }
10470
10471 /**
10472 * @return Returns a token used to identify the windows input channel.
10473 */
10474 public IBinder getInputToken() {
10475 if (mInputEventReceiver == null) {
10476 return null;
10477 }
10478 return mInputEventReceiver.getToken();
10479 }
10480
10481 @NonNull
10482 public IBinder getWindowToken() {
10483 return mAttachInfo.mWindowToken;
10484 }
10485
10486 /**
10487 * Class for managing the accessibility interaction connection
10488 * based on the global accessibility state.
10489 */
10490 final class AccessibilityInteractionConnectionManager
10491 implements AccessibilityStateChangeListener {
10492 @Override
10493 public void onAccessibilityStateChanged(boolean enabled) {
10494 if (enabled) {
10495 ensureConnection();
10496 if (mAttachInfo.mHasWindowFocus && (mView != null)) {
10497 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
10498 View focusedView = mView.findFocus();
10499 if (focusedView != null && focusedView != mView) {
10500 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
10501 }
10502 }
10503 if (mAttachInfo.mLeashedParentToken != null) {
10504 mAccessibilityManager.associateEmbeddedHierarchy(
10505 mAttachInfo.mLeashedParentToken, mLeashToken);
10506 }
10507 } else {
10508 ensureNoConnection();
10509 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
10510 }
10511 }
10512
10513 public void ensureConnection() {
10514 final boolean registered = mAttachInfo.mAccessibilityWindowId
10515 != AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
10516 if (!registered) {
10517 mAttachInfo.mAccessibilityWindowId =
10518 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
10519 mLeashToken,
10520 mContext.getPackageName(),
10521 new AccessibilityInteractionConnection(ViewRootImpl.this));
10522 }
10523 }
10524
10525 public void ensureNoConnection() {
10526 final boolean registered = mAttachInfo.mAccessibilityWindowId
10527 != AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
10528 if (registered) {
10529 mAttachInfo.mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID;
10530 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
10531 }
10532 }
10533 }
10534
10535 final class HighContrastTextManager implements HighTextContrastChangeListener {
10536 HighContrastTextManager() {
10537 ThreadedRenderer.setHighContrastText(mAccessibilityManager.isHighTextContrastEnabled());
10538 }
10539 @Override
10540 public void onHighTextContrastStateChanged(boolean enabled) {
10541 ThreadedRenderer.setHighContrastText(enabled);
10542
10543 // Destroy Displaylists so they can be recreated with high contrast recordings
10544 destroyHardwareResources();
10545
10546 // Schedule redraw, which will rerecord + redraw all text
10547 invalidate();
10548 }
10549 }
10550
10551 /**
10552 * This class is an interface this ViewAncestor provides to the
10553 * AccessibilityManagerService to the latter can interact with
10554 * the view hierarchy in this ViewAncestor.
10555 */
10556 static final class AccessibilityInteractionConnection
10557 extends IAccessibilityInteractionConnection.Stub {
10558 private final WeakReference<ViewRootImpl> mViewRootImpl;
10559
10560 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
10561 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
10562 }
10563
10564 @Override
10565 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
10566 Region interactiveRegion, int interactionId,
10567 IAccessibilityInteractionConnectionCallback callback, int flags,
10568 int interrogatingPid, long interrogatingTid, MagnificationSpec spec, float[] matrix,
10569 Bundle args) {
10570 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10571 if (viewRootImpl != null && viewRootImpl.mView != null) {
10572 viewRootImpl.getAccessibilityInteractionController()
10573 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
10574 interactiveRegion, interactionId, callback, flags, interrogatingPid,
10575 interrogatingTid, spec, matrix, args);
10576 } else {
10577 // We cannot make the call and notify the caller so it does not wait.
10578 try {
10579 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
10580 } catch (RemoteException re) {
10581 /* best effort - ignore */
10582 }
10583 }
10584 }
10585
10586 @Override
10587 public void performAccessibilityAction(long accessibilityNodeId, int action,
10588 Bundle arguments, int interactionId,
10589 IAccessibilityInteractionConnectionCallback callback, int flags,
10590 int interrogatingPid, long interrogatingTid) {
10591 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10592 if (viewRootImpl != null && viewRootImpl.mView != null) {
10593 viewRootImpl.getAccessibilityInteractionController()
10594 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
10595 interactionId, callback, flags, interrogatingPid, interrogatingTid);
10596 } else {
10597 // We cannot make the call and notify the caller so it does not wait.
10598 try {
10599 callback.setPerformAccessibilityActionResult(false, interactionId);
10600 } catch (RemoteException re) {
10601 /* best effort - ignore */
10602 }
10603 }
10604 }
10605
10606 @Override
10607 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
10608 String viewId, Region interactiveRegion, int interactionId,
10609 IAccessibilityInteractionConnectionCallback callback, int flags,
10610 int interrogatingPid, long interrogatingTid, MagnificationSpec spec,
10611 float[] matrix) {
10612 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10613 if (viewRootImpl != null && viewRootImpl.mView != null) {
10614 viewRootImpl.getAccessibilityInteractionController()
10615 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
10616 viewId, interactiveRegion, interactionId, callback, flags,
10617 interrogatingPid, interrogatingTid, spec, matrix);
10618 } else {
10619 // We cannot make the call and notify the caller so it does not wait.
10620 try {
10621 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
10622 } catch (RemoteException re) {
10623 /* best effort - ignore */
10624 }
10625 }
10626 }
10627
10628 @Override
10629 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
10630 Region interactiveRegion, int interactionId,
10631 IAccessibilityInteractionConnectionCallback callback, int flags,
10632 int interrogatingPid, long interrogatingTid, MagnificationSpec spec,
10633 float[] matrix) {
10634 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10635 if (viewRootImpl != null && viewRootImpl.mView != null) {
10636 viewRootImpl.getAccessibilityInteractionController()
10637 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
10638 interactiveRegion, interactionId, callback, flags, interrogatingPid,
10639 interrogatingTid, spec, matrix);
10640 } else {
10641 // We cannot make the call and notify the caller so it does not wait.
10642 try {
10643 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
10644 } catch (RemoteException re) {
10645 /* best effort - ignore */
10646 }
10647 }
10648 }
10649
10650 @Override
10651 public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
10652 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
10653 int interrogatingPid, long interrogatingTid, MagnificationSpec spec,
10654 float[] matrix) {
10655 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10656 if (viewRootImpl != null && viewRootImpl.mView != null) {
10657 viewRootImpl.getAccessibilityInteractionController()
10658 .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
10659 interactionId, callback, flags, interrogatingPid, interrogatingTid,
10660 spec, matrix);
10661 } else {
10662 // We cannot make the call and notify the caller so it does not wait.
10663 try {
10664 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
10665 } catch (RemoteException re) {
10666 /* best effort - ignore */
10667 }
10668 }
10669 }
10670
10671 @Override
10672 public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
10673 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
10674 int interrogatingPid, long interrogatingTid, MagnificationSpec spec,
10675 float[] matrix) {
10676 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10677 if (viewRootImpl != null && viewRootImpl.mView != null) {
10678 viewRootImpl.getAccessibilityInteractionController()
10679 .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
10680 interactionId, callback, flags, interrogatingPid, interrogatingTid,
10681 spec, matrix);
10682 } else {
10683 // We cannot make the call and notify the caller so it does not wait.
10684 try {
10685 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
10686 } catch (RemoteException re) {
10687 /* best effort - ignore */
10688 }
10689 }
10690 }
10691
10692 @Override
10693 public void clearAccessibilityFocus() {
10694 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10695 if (viewRootImpl != null && viewRootImpl.mView != null) {
10696 viewRootImpl.getAccessibilityInteractionController()
10697 .clearAccessibilityFocusClientThread();
10698 }
10699 }
10700
10701 @Override
10702 public void notifyOutsideTouch() {
10703 ViewRootImpl viewRootImpl = mViewRootImpl.get();
10704 if (viewRootImpl != null && viewRootImpl.mView != null) {
10705 viewRootImpl.getAccessibilityInteractionController()
10706 .notifyOutsideTouchClientThread();
10707 }
10708 }
10709 }
10710
10711 /**
10712 * Gets an accessibility embedded connection interface for this ViewRootImpl.
10713 * @hide
10714 */
10715 public IAccessibilityEmbeddedConnection getAccessibilityEmbeddedConnection() {
10716 if (mAccessibilityEmbeddedConnection == null) {
10717 mAccessibilityEmbeddedConnection = new AccessibilityEmbeddedConnection(
10718 ViewRootImpl.this);
10719 }
10720 return mAccessibilityEmbeddedConnection;
10721 }
10722
10723 private class SendWindowContentChangedAccessibilityEvent implements Runnable {
10724 private int mChangeTypes = 0;
10725
10726 public View mSource;
10727 public long mLastEventTimeMillis;
10728 /**
10729 * Override for {@link AccessibilityEvent#originStackTrace} to provide the stack trace
10730 * of the original {@link #runOrPost} call instead of one for sending the delayed event
10731 * from a looper.
10732 */
10733 public StackTraceElement[] mOrigin;
10734
10735 @Override
10736 public void run() {
10737 // Protect against re-entrant code and attempt to do the right thing in the case that
10738 // we're multithreaded.
10739 View source = mSource;
10740 mSource = null;
10741 if (source == null) {
10742 Log.e(TAG, "Accessibility content change has no source");
10743 return;
10744 }
10745 // The accessibility may be turned off while we were waiting so check again.
10746 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
10747 mLastEventTimeMillis = SystemClock.uptimeMillis();
10748 AccessibilityEvent event = AccessibilityEvent.obtain();
10749 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
10750 event.setContentChangeTypes(mChangeTypes);
10751 if (AccessibilityEvent.DEBUG_ORIGIN) event.originStackTrace = mOrigin;
10752 source.sendAccessibilityEventUnchecked(event);
10753 } else {
10754 mLastEventTimeMillis = 0;
10755 }
10756 // In any case reset to initial state.
10757 source.resetSubtreeAccessibilityStateChanged();
10758 mChangeTypes = 0;
10759 if (AccessibilityEvent.DEBUG_ORIGIN) mOrigin = null;
10760 }
10761
10762 public void runOrPost(View source, int changeType) {
10763 if (mHandler.getLooper() != Looper.myLooper()) {
10764 CalledFromWrongThreadException e = new CalledFromWrongThreadException("Only the "
10765 + "original thread that created a view hierarchy can touch its views.");
10766 // TODO: Throw the exception
10767 Log.e(TAG, "Accessibility content change on non-UI thread. Future Android "
10768 + "versions will throw an exception.", e);
10769 // Attempt to recover. This code does not eliminate the thread safety issue, but
10770 // it should force any issues to happen near the above log.
10771 mHandler.removeCallbacks(this);
10772 if (mSource != null) {
10773 // Dispatch whatever was pending. It's still possible that the runnable started
10774 // just before we removed the callbacks, and bad things will happen, but at
10775 // least they should happen very close to the logged error.
10776 run();
10777 }
10778 }
10779 if (mSource != null) {
10780 // If there is no common predecessor, then mSource points to
10781 // a removed view, hence in this case always prefer the source.
10782 View predecessor = getCommonPredecessor(mSource, source);
10783 if (predecessor != null) {
10784 predecessor = predecessor.getSelfOrParentImportantForA11y();
10785 }
10786 mSource = (predecessor != null) ? predecessor : source;
10787 mChangeTypes |= changeType;
10788 return;
10789 }
10790 mSource = source;
10791 mChangeTypes = changeType;
10792 if (AccessibilityEvent.DEBUG_ORIGIN) {
10793 mOrigin = Thread.currentThread().getStackTrace();
10794 }
10795 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
10796 final long minEventIntevalMillis =
10797 ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
10798 if (timeSinceLastMillis >= minEventIntevalMillis) {
10799 removeCallbacksAndRun();
10800 } else {
10801 mHandler.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
10802 }
10803 }
10804
10805 public void removeCallbacksAndRun() {
10806 mHandler.removeCallbacks(this);
10807 run();
10808 }
10809 }
10810
10811 private static class UnhandledKeyManager {
10812 // This is used to ensure that unhandled events are only dispatched once. We attempt
10813 // to dispatch more than once in order to achieve a certain order. Specifically, if we
10814 // are in an Activity or Dialog (and have a Window.Callback), the unhandled events should
10815 // be dispatched after the view hierarchy, but before the Callback. However, if we aren't
10816 // in an activity, we still want unhandled keys to be dispatched.
10817 private boolean mDispatched = true;
10818
10819 // Keeps track of which Views have unhandled key focus for which keys. This doesn't
10820 // include modifiers.
10821 private final SparseArray<WeakReference<View>> mCapturedKeys = new SparseArray<>();
10822
10823 // The current receiver. This value is transient and used between the pre-dispatch and
10824 // pre-view phase to ensure that other input-stages don't interfere with tracking.
10825 private WeakReference<View> mCurrentReceiver = null;
10826
10827 boolean dispatch(View root, KeyEvent event) {
10828 if (mDispatched) {
10829 return false;
10830 }
10831 View consumer;
10832 try {
10833 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "UnhandledKeyEvent dispatch");
10834 mDispatched = true;
10835
10836 consumer = root.dispatchUnhandledKeyEvent(event);
10837
10838 // If an unhandled listener handles one, then keep track of it so that the
10839 // consuming view is first to receive its repeats and release as well.
10840 if (event.getAction() == KeyEvent.ACTION_DOWN) {
10841 int keycode = event.getKeyCode();
10842 if (consumer != null && !KeyEvent.isModifierKey(keycode)) {
10843 mCapturedKeys.put(keycode, new WeakReference<>(consumer));
10844 }
10845 }
10846 } finally {
10847 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
10848 }
10849 return consumer != null;
10850 }
10851
10852 /**
10853 * Called before the event gets dispatched to anything
10854 */
10855 void preDispatch(KeyEvent event) {
10856 // Always clean-up 'up' events since it's possible for earlier dispatch stages to
10857 // consume them without consuming the corresponding 'down' event.
10858 mCurrentReceiver = null;
10859 if (event.getAction() == KeyEvent.ACTION_UP) {
10860 int idx = mCapturedKeys.indexOfKey(event.getKeyCode());
10861 if (idx >= 0) {
10862 mCurrentReceiver = mCapturedKeys.valueAt(idx);
10863 mCapturedKeys.removeAt(idx);
10864 }
10865 }
10866 }
10867
10868 /**
10869 * Called before the event gets dispatched to the view hierarchy
10870 * @return {@code true} if an unhandled handler has focus and consumed the event
10871 */
10872 boolean preViewDispatch(KeyEvent event) {
10873 mDispatched = false;
10874 if (mCurrentReceiver == null) {
10875 mCurrentReceiver = mCapturedKeys.get(event.getKeyCode());
10876 }
10877 if (mCurrentReceiver != null) {
10878 View target = mCurrentReceiver.get();
10879 if (event.getAction() == KeyEvent.ACTION_UP) {
10880 mCurrentReceiver = null;
10881 }
10882 if (target != null && target.isAttachedToWindow()) {
10883 target.onUnhandledKeyEvent(event);
10884 }
10885 // consume anyways so that we don't feed uncaptured key events to other views
10886 return true;
10887 }
10888 return false;
10889 }
10890 }
10891
10892 /**
10893 * @hide
10894 */
10895 public void setDisplayDecoration(boolean displayDecoration) {
10896 if (displayDecoration == mDisplayDecorationCached) return;
10897
10898 mDisplayDecorationCached = displayDecoration;
10899
10900 if (mSurfaceControl.isValid()) {
10901 updateDisplayDecoration();
10902 }
10903 }
10904
10905 private void updateDisplayDecoration() {
10906 mTransaction.setDisplayDecoration(mSurfaceControl, mDisplayDecorationCached).apply();
10907 }
10908
10909 /**
10910 * Sends a list of blur regions to SurfaceFlinger, tagged with a frame.
10911 *
10912 * @param regionCopy List of regions
10913 * @param frameNumber Frame where it should be applied (or current when using BLAST)
10914 */
10915 public void dispatchBlurRegions(float[][] regionCopy, long frameNumber) {
10916 final SurfaceControl surfaceControl = getSurfaceControl();
10917 if (!surfaceControl.isValid()) {
10918 return;
10919 }
10920
10921 SurfaceControl.Transaction transaction = new SurfaceControl.Transaction();
10922 transaction.setBlurRegions(surfaceControl, regionCopy);
10923
10924 if (useBLAST() && mBlastBufferQueue != null) {
10925 mBlastBufferQueue.mergeWithNextTransaction(transaction, frameNumber);
10926 }
10927 }
10928
10929 /**
10930 * Creates a background blur drawable for the backing {@link Surface}.
10931 */
10932 public BackgroundBlurDrawable createBackgroundBlurDrawable() {
10933 return mBlurRegionAggregator.createBackgroundBlurDrawable(mContext);
10934 }
10935
10936 @Override
10937 public void onDescendantUnbufferedRequested() {
10938 mUnbufferedInputSource = mView.mUnbufferedInputSource;
10939 }
10940
10941 /**
10942 * Force disabling use of the BLAST adapter regardless of the system
10943 * flag. Needs to be called before addView.
10944 */
10945 void forceDisableBLAST() {
10946 mForceDisableBLAST = true;
10947 }
10948
10949 boolean useBLAST() {
10950 return mUseBLASTAdapter && !mForceDisableBLAST;
10951 }
10952
10953 int getSurfaceSequenceId() {
10954 return mSurfaceSequenceId;
10955 }
10956
10957 /**
10958 * Merges the transaction passed in with the next transaction in BLASTBufferQueue. This ensures
10959 * you can add transactions to the upcoming frame.
10960 */
10961 public void mergeWithNextTransaction(Transaction t, long frameNumber) {
10962 if (mBlastBufferQueue != null) {
10963 mBlastBufferQueue.mergeWithNextTransaction(t, frameNumber);
10964 } else {
10965 t.apply();
10966 }
10967 }
10968
10969 @Override
10970 @Nullable public SurfaceControl.Transaction buildReparentTransaction(
10971 @NonNull SurfaceControl child) {
10972 if (mSurfaceControl.isValid()) {
10973 return new SurfaceControl.Transaction().reparent(child, mSurfaceControl);
10974 }
10975 return null;
10976 }
10977
10978 @Override
10979 public boolean applyTransactionOnDraw(@NonNull SurfaceControl.Transaction t) {
10980 if (mRemoved || !isHardwareEnabled()) {
10981 t.apply();
10982 } else {
10983 mHasPendingTransactions = true;
10984 registerRtFrameCallback(frame -> {
10985 mergeWithNextTransaction(t, frame);
10986 });
10987 }
10988 return true;
10989 }
10990
10991 @Override
10992 public @SurfaceControl.BufferTransform int getBufferTransformHint() {
10993 return mSurfaceControl.getTransformHint();
10994 }
10995
10996 @Override
10997 public void addOnBufferTransformHintChangedListener(
10998 OnBufferTransformHintChangedListener listener) {
10999 Objects.requireNonNull(listener);
11000 if (mTransformHintListeners.contains(listener)) {
11001 throw new IllegalArgumentException(
11002 "attempt to call addOnBufferTransformHintChangedListener() "
11003 + "with a previously registered listener");
11004 }
11005 mTransformHintListeners.add(listener);
11006 }
11007
11008 @Override
11009 public void removeOnBufferTransformHintChangedListener(
11010 OnBufferTransformHintChangedListener listener) {
11011 Objects.requireNonNull(listener);
11012 mTransformHintListeners.remove(listener);
11013 }
11014
11015 private void dispatchTransformHintChanged(@SurfaceControl.BufferTransform int hint) {
11016 if (mTransformHintListeners.isEmpty()) {
11017 return;
11018 }
11019 ArrayList<OnBufferTransformHintChangedListener> listeners =
11020 (ArrayList<OnBufferTransformHintChangedListener>) mTransformHintListeners.clone();
11021 for (int i = 0; i < listeners.size(); i++) {
11022 OnBufferTransformHintChangedListener listener = listeners.get(i);
11023 listener.onBufferTransformHintChanged(hint);
11024 }
11025 }
11026
11027 /**
11028 * Shows or hides a Camera app compat toggle for stretched issues with the requested state
11029 * for the corresponding activity.
11030 *
11031 * @param showControl Whether the control should be shown or hidden.
11032 * @param transformationApplied Whether the treatment is already applied.
11033 * @param callback The callback executed when the user clicks on a control.
11034 */
11035 public void requestCompatCameraControl(boolean showControl, boolean transformationApplied,
11036 ICompatCameraControlCallback callback) {
11037 mActivityConfigCallback.requestCompatCameraControl(
11038 showControl, transformationApplied, callback);
11039 }
11040
11041 boolean wasRelayoutRequested() {
11042 return mRelayoutRequested;
11043 }
11044
11045 void forceWmRelayout() {
11046 mForceNextWindowRelayout = true;
11047 scheduleTraversals();
11048 }
11049
11050 /**
11051 * Returns the {@link OnBackInvokedDispatcher} on the decor view if one exists, or the
11052 * fallback {@link OnBackInvokedDispatcher} instance.
11053 */
11054 @NonNull
11055 public WindowOnBackInvokedDispatcher getOnBackInvokedDispatcher() {
11056 return mOnBackInvokedDispatcher;
11057 }
11058
11059 @NonNull
11060 @Override
11061 public OnBackInvokedDispatcher findOnBackInvokedDispatcherForChild(
11062 @NonNull View child, @NonNull View requester) {
11063 return getOnBackInvokedDispatcher();
11064 }
11065
11066 /**
11067 * When this ViewRootImpl is added to the window manager, transfers the first
11068 * {@link OnBackInvokedCallback} to be called to the server.
11069 */
11070 private void registerBackCallbackOnWindow() {
11071 if (OnBackInvokedDispatcher.DEBUG) {
11072 Log.d(OnBackInvokedDispatcher.TAG, TextUtils.formatSimple(
11073 "ViewRootImpl.registerBackCallbackOnWindow. Dispatcher:%s Package:%s "
11074 + "IWindow:%s Session:%s",
11075 mOnBackInvokedDispatcher, mBasePackageName, mWindow, mWindowSession));
11076 }
11077 mOnBackInvokedDispatcher.attachToWindow(mWindowSession, mWindow);
11078 }
11079
11080 private void sendBackKeyEvent(int action) {
11081 long when = SystemClock.uptimeMillis();
11082 final KeyEvent ev = new KeyEvent(when, when, action,
11083 KeyEvent.KEYCODE_BACK, 0 /* repeat */, 0 /* metaState */,
11084 KeyCharacterMap.VIRTUAL_KEYBOARD, 0 /* scancode */,
11085 KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY,
11086 InputDevice.SOURCE_KEYBOARD);
11087 enqueueInputEvent(ev);
11088 }
11089
11090 private void registerCompatOnBackInvokedCallback() {
11091 mCompatOnBackInvokedCallback = () -> {
11092 sendBackKeyEvent(KeyEvent.ACTION_DOWN);
11093 sendBackKeyEvent(KeyEvent.ACTION_UP);
11094 };
11095 mOnBackInvokedDispatcher.registerOnBackInvokedCallback(
11096 OnBackInvokedDispatcher.PRIORITY_DEFAULT, mCompatOnBackInvokedCallback);
11097 }
11098
11099 @Override
11100 public void setTouchableRegion(Region r) {
11101 if (r != null) {
11102 mTouchableRegion = new Region(r);
11103 } else {
11104 mTouchableRegion = null;
11105 }
11106 mLastGivenInsets.reset();
11107 requestLayout();
11108 }
11109
11110 IWindowSession getWindowSession() {
11111 return mWindowSession;
11112 }
11113
11114 private void registerCallbacksForSync(boolean syncBuffer,
11115 final SurfaceSyncer.SyncBufferCallback syncBufferCallback) {
11116 if (!isHardwareEnabled()) {
11117 return;
11118 }
11119
11120 if (DEBUG_BLAST) {
11121 Log.d(mTag, "registerCallbacksForSync syncBuffer=" + syncBuffer);
11122 }
11123 mAttachInfo.mThreadedRenderer.registerRtFrameCallback(new FrameDrawingCallback() {
11124 @Override
11125 public void onFrameDraw(long frame) {
11126 }
11127
11128 @Override
11129 public HardwareRenderer.FrameCommitCallback onFrameDraw(int syncResult, long frame) {
11130 if (DEBUG_BLAST) {
11131 Log.d(mTag,
11132 "Received frameDrawingCallback syncResult=" + syncResult + " frameNum="
11133 + frame + ".");
11134 }
11135
11136 // If the syncResults are SYNC_LOST_SURFACE_REWARD_IF_FOUND or
11137 // SYNC_CONTEXT_IS_STOPPED it means nothing will draw. There's no need to set up
11138 // any blast sync or commit callback, and the code should directly call
11139 // pendingDrawFinished.
11140 if ((syncResult
11141 & (SYNC_LOST_SURFACE_REWARD_IF_FOUND | SYNC_CONTEXT_IS_STOPPED)) != 0) {
11142 syncBufferCallback.onBufferReady(
11143 mBlastBufferQueue.gatherPendingTransactions(frame));
11144 return null;
11145 }
11146
11147 if (DEBUG_BLAST) {
11148 Log.d(mTag, "Setting up sync and frameCommitCallback");
11149 }
11150
11151 if (syncBuffer) {
11152 mBlastBufferQueue.syncNextTransaction(syncBufferCallback::onBufferReady);
11153 }
11154
11155 return didProduceBuffer -> {
11156 if (DEBUG_BLAST) {
11157 Log.d(mTag, "Received frameCommittedCallback"
11158 + " lastAttemptedDrawFrameNum=" + frame
11159 + " didProduceBuffer=" + didProduceBuffer);
11160 }
11161
11162 // If frame wasn't drawn, clear out the next transaction so it doesn't affect
11163 // the next draw attempt. The next transaction and transaction complete callback
11164 // were only set for the current draw attempt.
11165 if (!didProduceBuffer) {
11166 mBlastBufferQueue.syncNextTransaction(null);
11167
11168 // Gather the transactions that were sent to mergeWithNextTransaction
11169 // since the frame didn't draw on this vsync. It's possible the frame will
11170 // draw later, but it's better to not be sync than to block on a frame that
11171 // may never come.
11172 syncBufferCallback.onBufferReady(
11173 mBlastBufferQueue.gatherPendingTransactions(frame));
11174 return;
11175 }
11176
11177 // If we didn't request to sync a buffer, then we won't get the
11178 // syncNextTransaction callback. Instead, just report back to the Syncer so it
11179 // knows that this sync request is complete.
11180 if (!syncBuffer) {
11181 syncBufferCallback.onBufferReady(null);
11182 }
11183 };
11184 }
11185 });
11186 }
11187
11188 public final SurfaceSyncer.SyncTarget mSyncTarget = new SurfaceSyncer.SyncTarget() {
11189 @Override
11190 public void onReadyToSync(SurfaceSyncer.SyncBufferCallback syncBufferCallback) {
11191 readyToSync(syncBufferCallback);
11192 }
11193
11194 @Override
11195 public void onSyncComplete() {
11196 mHandler.postAtFrontOfQueue(() -> {
11197 if (--mNumSyncsInProgress == 0 && mAttachInfo.mThreadedRenderer != null) {
11198 HardwareRenderer.setRtAnimationsEnabled(true);
11199 }
11200 });
11201 }
11202 };
11203
11204 private void readyToSync(SurfaceSyncer.SyncBufferCallback syncBufferCallback) {
11205 mNumSyncsInProgress++;
11206 if (!isInLocalSync()) {
11207 // Always sync the buffer if the sync request did not come from VRI.
11208 mSyncBuffer = true;
11209 }
11210 if (mAttachInfo.mThreadedRenderer != null) {
11211 HardwareRenderer.setRtAnimationsEnabled(false);
11212 }
11213
11214 if (mSyncBufferCallback != null) {
11215 Log.d(mTag, "Already set sync for the next draw.");
11216 mSyncBufferCallback.onBufferReady(null);
11217 }
11218 if (DEBUG_BLAST) {
11219 Log.d(mTag, "Setting syncFrameCallback");
11220 }
11221 mSyncBufferCallback = syncBufferCallback;
11222 if (!mIsInTraversal && !mTraversalScheduled) {
11223 scheduleTraversals();
11224 }
11225 }
11226
11227 void mergeSync(int syncId, SurfaceSyncer otherSyncer) {
11228 if (!isInLocalSync()) {
11229 return;
11230 }
11231 mSurfaceSyncer.merge(mSyncId, syncId, otherSyncer);
11232 }
11233 }