blob: 05177885f3dc9c5fbc177e9dd3abc0195658f8d8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
17package android.view;
18
Jorim Jaggia4a58ef2016-01-27 02:10:08 -080019import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -080020import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
Jorim Jaggi2e95a482016-01-14 17:36:55 -080021import static android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER;
Chong Zhangf6525ce2016-01-14 17:09:56 -080022import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
23import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
24import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -080025
Romain Guy6b7bd242010-10-06 19:49:23 -070026import android.Manifest;
Chet Haasecca2c982011-05-20 14:34:18 -070027import android.animation.LayoutTransition;
Romain Guy6b7bd242010-10-06 19:49:23 -070028import android.app.ActivityManagerNative;
29import android.content.ClipDescription;
30import android.content.ComponentCallbacks;
31import android.content.Context;
32import android.content.pm.PackageManager;
33import android.content.res.CompatibilityInfo;
34import android.content.res.Configuration;
35import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.graphics.Canvas;
Alan Viverettefed3f722013-11-14 14:48:20 -080037import android.graphics.Matrix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.graphics.PixelFormat;
Christopher Tate2c095f32010-10-04 14:13:40 -070039import android.graphics.Point;
Christopher Tatea53146c2010-09-07 11:57:52 -070040import android.graphics.PointF;
Romain Guy6b7bd242010-10-06 19:49:23 -070041import android.graphics.PorterDuff;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.graphics.Rect;
43import android.graphics.Region;
Svetoslav Ganov42138042012-03-20 11:51:39 -070044import android.graphics.drawable.Drawable;
Jeff Brownd912e1f2014-04-11 18:46:22 -070045import android.hardware.display.DisplayManager;
46import android.hardware.display.DisplayManager.DisplayListener;
Jun Mukai347e5d42015-12-03 01:13:31 -080047import android.hardware.input.InputManager;
Romain Guy6b7bd242010-10-06 19:49:23 -070048import android.media.AudioManager;
49import android.os.Binder;
Michael Wright5bd69e62015-05-14 14:48:08 +010050import android.os.Build;
Romain Guy6b7bd242010-10-06 19:49:23 -070051import android.os.Bundle;
52import android.os.Debug;
53import android.os.Handler;
Romain Guy6b7bd242010-10-06 19:49:23 -070054import android.os.Looper;
55import android.os.Message;
56import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Process;
Romain Guy6b7bd242010-10-06 19:49:23 -070058import android.os.RemoteException;
Romain Guy6b7bd242010-10-06 19:49:23 -070059import android.os.SystemClock;
Romain Guy59a12ca2011-06-09 17:48:21 -070060import android.os.SystemProperties;
Jeff Brown481c1572012-03-09 14:41:15 -080061import android.os.Trace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.AndroidRuntimeException;
Mitsuru Oshima9189cab2009-06-03 11:19:12 -070063import android.util.DisplayMetrics;
Romain Guy6b7bd242010-10-06 19:49:23 -070064import android.util.Log;
Chet Haase949dbf72010-08-11 18:41:06 -070065import android.util.Slog;
John Reckba6adf62015-02-19 14:36:50 -080066import android.util.TimeUtils;
Dianne Hackborn711e62a2010-11-29 16:38:22 -080067import android.util.TypedValue;
John Reck44fd8d22014-02-26 11:00:11 -080068import android.view.Surface.OutOfResourcesException;
Jeff Browna175a5b2012-02-15 19:18:31 -080069import android.view.View.AttachInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.view.View.MeasureSpec;
svetoslavganov75986cf2009-05-14 22:28:01 -070071import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityManager;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -070073import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
Chris Craikcce47eb2014-07-16 15:12:15 -070074import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -070075import android.view.accessibility.AccessibilityNodeInfo;
Alan Viverette25acc7e2015-05-19 11:32:08 -070076import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
Svetoslav Ganov02107852011-10-03 17:06:56 -070077import android.view.accessibility.AccessibilityNodeProvider;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -070078import android.view.accessibility.IAccessibilityInteractionConnection;
79import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
Dianne Hackborn0f761d62010-11-30 22:06:10 -080080import android.view.animation.AccelerateDecelerateInterpolator;
81import android.view.animation.Interpolator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.view.inputmethod.InputConnection;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.Scroller;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -070085
Svetoslav Ganov42138042012-03-20 11:51:39 -070086import com.android.internal.R;
Clara Bayarri75e09792015-07-29 16:20:40 +010087import com.android.internal.os.IResultReceiver;
Svetoslav Ganov758143e2012-08-06 16:40:27 -070088import com.android.internal.os.SomeArgs;
Adam Powell6711f3b2015-05-06 15:57:09 -070089import com.android.internal.policy.PhoneFallbackEventHandler;
Romain Guy6b7bd242010-10-06 19:49:23 -070090import com.android.internal.view.BaseSurfaceHolder;
Romain Guy6b7bd242010-10-06 19:49:23 -070091import com.android.internal.view.RootViewSurfaceTaker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Jeff Brown5182c782013-10-15 20:31:52 -070093import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import java.io.IOException;
95import java.io.OutputStream;
Jeff Brown5182c782013-10-15 20:31:52 -070096import java.io.PrintWriter;
Romain Guy6b7bd242010-10-06 19:49:23 -070097import java.lang.ref.WeakReference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.util.ArrayList;
Chong Zhang8dbd9ad2015-10-09 10:06:11 -070099import java.util.concurrent.CountDownLatch;
Svetoslav Ganov42138042012-03-20 11:51:39 -0700100import java.util.HashSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102/**
103 * The top of a view hierarchy, implementing the needed protocol between View
104 * and the WindowManager. This is for the most part an internal implementation
Jeff Brown98365d72012-08-19 20:30:52 -0700105 * detail of {@link WindowManagerGlobal}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 *
107 * {@hide}
108 */
Romain Guy812ccbe2010-06-01 14:07:24 -0700109@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
Jeff Browna175a5b2012-02-15 19:18:31 -0800110public final class ViewRootImpl implements ViewParent,
John Reck51aaf902015-12-02 15:08:07 -0800111 View.AttachInfo.Callbacks, ThreadedRenderer.HardwareDrawCallbacks {
Dianne Hackborn70a3f672011-08-08 14:32:41 -0700112 private static final String TAG = "ViewRootImpl";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private static final boolean DBG = false;
Romain Guy812ccbe2010-06-01 14:07:24 -0700114 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 /** @noinspection PointlessBooleanExpression*/
116 private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
117 private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800118 private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
120 private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
121 private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
122 private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700123 private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
Chet Haase2f2022a2011-10-11 06:41:59 -0700124 private static final boolean DEBUG_FPS = false;
Michael Wright06a79252014-05-05 17:45:29 -0700125 private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
Romain Guy59a12ca2011-06-09 17:48:21 -0700127 /**
Skuhneb8160872015-09-22 09:51:39 -0700128 * Set to false if we do not want to use the multi threaded renderer. Note that by disabling
129 * this, WindowCallbacks will not fire.
130 */
131 private static final boolean USE_MT_RENDERER = true;
132
133 /**
Romain Guy59a12ca2011-06-09 17:48:21 -0700134 * Set this system property to true to force the view hierarchy to render
135 * at 60 Hz. This can be used to measure the potential framerate.
136 */
Romain Guye9bc11f2013-05-23 12:47:26 -0700137 private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
Michael Chan53071d62009-05-13 17:29:48 -0700138
Griff Hazena0938022015-03-13 10:01:41 -0700139 // properties used by emulator to determine display shape
Griff Hazena0938022015-03-13 10:01:41 -0700140 public static final String PROPERTY_EMULATOR_WIN_OUTSET_BOTTOM_PX =
141 "ro.emu.win_outset_bottom_px";
Michael Kolb437d3132014-06-20 13:28:44 -0700142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 /**
144 * Maximum time we allow the user to roll the trackball enough to generate
145 * a key event, before resetting the counters.
146 */
147 static final int MAX_TRACKBALL_DELAY = 250;
148
Jorim Jaggi4846ee32016-01-07 17:39:12 +0100149 private static final int RESIZE_MODE_FREEFORM = 0;
150 private static final int RESIZE_MODE_DOCKED_DIVIDER = 1;
151
Alan Viverettebea0c7da2015-09-01 16:00:20 -0400152 static final ThreadLocal<HandlerActionQueue> sRunQueues = new ThreadLocal<HandlerActionQueue>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Skuhneb8160872015-09-22 09:51:39 -0700154 static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList();
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800155 static boolean sFirstDrawComplete = false;
Craig Mautner8f303ad2013-06-14 11:32:22 -0700156
Skuhneb8160872015-09-22 09:51:39 -0700157 static final ArrayList<ComponentCallbacks> sConfigCallbacks = new ArrayList();
Romain Guy59a12ca2011-06-09 17:48:21 -0700158
Chong Zhangdcee1de2015-10-06 10:26:00 -0700159 final ArrayList<WindowCallbacks> mWindowCallbacks = new ArrayList();
Jeff Brownf9e989d2013-04-04 23:04:03 -0700160 final Context mContext;
Jeff Brown98365d72012-08-19 20:30:52 -0700161 final IWindowSession mWindowSession;
162 final Display mDisplay;
Jeff Brownd912e1f2014-04-11 18:46:22 -0700163 final DisplayManager mDisplayManager;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800164 final String mBasePackageName;
Jeff Brown98365d72012-08-19 20:30:52 -0700165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 final int[] mTmpLocation = new int[2];
Romain Guy8506ab42009-06-11 17:35:47 -0700167
Dianne Hackborn711e62a2010-11-29 16:38:22 -0800168 final TypedValue mTmpValue = new TypedValue();
Jeff Brownf9e989d2013-04-04 23:04:03 -0700169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 final Thread mThread;
171
172 final WindowLeaked mLocation;
173
174 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
175
176 final W mWindow;
177
Dianne Hackborn180c4842011-09-13 12:39:25 -0700178 final int mTargetSdkVersion;
179
Dianne Hackborn9a230e02011-10-06 11:51:27 -0700180 int mSeq;
181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 View mView;
Svetoslav Ganov42138042012-03-20 11:51:39 -0700183
184 View mAccessibilityFocusedHost;
185 AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
186
Jun Mukai347e5d42015-12-03 01:13:31 -0800187 // The view which captures mouse input, or null when no one is capturing.
188 View mCapturingView;
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 int mViewVisibility;
191 boolean mAppVisible = true;
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -0800192 // For recents to freeform transition we need to keep drawing after the app receives information
193 // that it became invisible. This will ignore that information and depend on the decor view
194 // visibility to control drawing. The decor view visibility will get adjusted when the app get
195 // stopped and that's when the app will stop drawing further frames.
196 private boolean mForceDecorViewVisibility = false;
Dianne Hackborn180c4842011-09-13 12:39:25 -0700197 int mOrigWindowType = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Alan Viverette64bf97a2015-09-18 16:42:00 -0400199 /** Whether the window had focus during the most recent traversal. */
200 boolean mHadWindowFocus;
201
202 /**
203 * Whether the window lost focus during a previous traversal and has not
204 * yet gained it back. Used to determine whether a WINDOW_STATE_CHANGE
205 * accessibility events should be sent during traversal.
206 */
207 boolean mLostWindowFocus;
208
Dianne Hackbornce418e62011-03-01 14:31:38 -0800209 // Set to true if the owner of this window is in the stopped state,
210 // so the window should no longer be active.
211 boolean mStopped = false;
Craig Mautner8f303ad2013-06-14 11:32:22 -0700212
Daniel Koulomzin087ae472015-12-16 17:52:25 -0500213 // Set to true if the owner of this window is in ambient mode,
214 // which means it won't receive input events.
215 boolean mIsAmbientMode = false;
216
George Mount41725de2015-04-09 08:23:05 -0700217 // Set to true to stop input during an Activity Transition.
218 boolean mPausedForTransition = false;
219
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700220 boolean mLastInCompatMode = false;
221
Dianne Hackbornd76b67c2010-07-13 17:48:30 -0700222 SurfaceHolder.Callback2 mSurfaceHolderCallback;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700223 BaseSurfaceHolder mSurfaceHolder;
224 boolean mIsCreating;
225 boolean mDrawingAllowed;
Craig Mautner8f303ad2013-06-14 11:32:22 -0700226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 final Region mTransparentRegion;
228 final Region mPreviousTransparentRegion;
229
230 int mWidth;
231 int mHeight;
Romain Guy7d7b5492011-01-24 16:33:45 -0800232 Rect mDirty;
Romain Guybb93d552009-03-24 21:04:15 -0700233 boolean mIsAnimating;
Romain Guy8506ab42009-06-11 17:35:47 -0700234
Chong Zhang0275e392015-09-17 10:41:44 -0700235 private boolean mDragResizing;
Jorim Jaggi4846ee32016-01-07 17:39:12 +0100236 private int mResizeMode;
Chong Zhang0275e392015-09-17 10:41:44 -0700237 private int mCanvasOffsetX;
238 private int mCanvasOffsetY;
Jorim Jaggi4846ee32016-01-07 17:39:12 +0100239 private boolean mActivityRelaunched;
Chong Zhang0275e392015-09-17 10:41:44 -0700240
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700241 CompatibilityInfo.Translator mTranslator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 final View.AttachInfo mAttachInfo;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700244 InputChannel mInputChannel;
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -0700245 InputQueue.Callback mInputQueueCallback;
246 InputQueue mInputQueue;
Joe Onorato86f67862010-11-05 18:57:34 -0700247 FallbackEventHandler mFallbackEventHandler;
Jeff Brown96e942d2011-11-30 19:55:01 -0800248 Choreographer mChoreographer;
Igor Murashkina86ab6402013-08-30 12:58:36 -0700249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 final Rect mTempRect; // used in the transaction to not thrash the heap.
251 final Rect mVisRect; // used to retrieve visible rect of focused view.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 boolean mTraversalScheduled;
Jeff Browne0dbd002012-02-15 19:34:58 -0800254 int mTraversalBarrier;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 boolean mWillDrawSoon;
Craig Mautnerdf2390a2012-08-29 20:59:22 -0700256 /** Set to true while in performTraversals for detecting when die(true) is called from internal
257 * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
258 boolean mIsInTraversal;
Adrian Roosfa104232014-06-20 16:10:14 -0700259 boolean mApplyInsetsRequested;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 boolean mLayoutRequested;
261 boolean mFirst;
262 boolean mReportNextDraw;
263 boolean mFullRedrawNeeded;
264 boolean mNewSurfaceNeeded;
265 boolean mHasHadWindowFocus;
266 boolean mLastWasImTarget;
Jorim Jaggia4a58ef2016-01-27 02:10:08 -0800267 boolean mForceNextWindowRelayout;
Chong Zhang8dbd9ad2015-10-09 10:06:11 -0700268 CountDownLatch mWindowDrawCountDown;
Jorim Jaggi827e0fa2015-05-07 11:41:41 -0700269
Romain Guy1f59e5c2012-05-06 14:11:16 -0700270 boolean mIsDrawing;
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -0700271 int mLastSystemUiVisibility;
Dianne Hackborn9d090892012-06-11 18:35:41 -0700272 int mClientWindowLayoutFlags;
Dianne Hackbornc4aad012013-02-22 15:05:25 -0800273 boolean mLastOverscanRequested;
Jeff Brown4952dfd2011-11-30 19:23:22 -0800274
275 // Pool of queued input events.
276 private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
277 private QueuedInputEvent mQueuedInputEventPool;
278 private int mQueuedInputEventPoolSize;
Jeff Brown4952dfd2011-11-30 19:23:22 -0800279
Michael Wrightc8a7e542013-03-20 17:58:33 -0700280 /* Input event queue.
Jeff Brownf9e989d2013-04-04 23:04:03 -0700281 * Pending input events are input events waiting to be delivered to the input stages
282 * and handled by the application.
Michael Wrightc8a7e542013-03-20 17:58:33 -0700283 */
284 QueuedInputEvent mPendingInputEventHead;
285 QueuedInputEvent mPendingInputEventTail;
Michael Wright95ae9422013-03-14 10:58:50 -0700286 int mPendingInputEventCount;
Jeff Brown96e942d2011-11-30 19:55:01 -0800287 boolean mProcessInputEventsScheduled;
Michael Wright9d744c72014-02-18 21:27:42 -0800288 boolean mUnbufferedInputDispatch;
Michael Wright95ae9422013-03-14 10:58:50 -0700289 String mPendingInputEventQueueLengthCounterName = "pq";
Jeff Brownf9e989d2013-04-04 23:04:03 -0700290
291 InputStage mFirstInputStage;
292 InputStage mFirstPostImeInputStage;
Michael Wright899d7052014-04-23 17:23:39 -0700293 InputStage mSyntheticInputStage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
295 boolean mWindowAttributesChanged = false;
Romain Guyf21c9b02011-09-06 16:56:54 -0700296 int mWindowAttributesChangesFlag = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
298 // These can be accessed by any thread, must be protected with a lock.
Mathias Agopian5583dc62009-07-09 16:28:11 -0700299 // Surface can never be reassigned or cleared (use Surface.clear()).
John Reckb13de072014-11-19 16:33:47 -0800300 final Surface mSurface = new Surface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
302 boolean mAdded;
303 boolean mAddedTouchMode;
304
Craig Mautner48d0d182013-06-11 07:53:06 -0700305 final DisplayAdjustments mDisplayAdjustments;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 // These are accessed by multiple threads.
308 final Rect mWinFrame; // frame given by window manager.
309
Dianne Hackbornc4aad012013-02-22 15:05:25 -0800310 final Rect mPendingOverscanInsets = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 final Rect mPendingVisibleInsets = new Rect();
Adrian Roosfa104232014-06-20 16:10:14 -0700312 final Rect mPendingStableInsets = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 final Rect mPendingContentInsets = new Rect();
Filip Gruszczynski2217f612015-05-26 11:32:08 -0700314 final Rect mPendingOutsets = new Rect();
Jorim Jaggia7262a82015-11-03 15:15:40 +0100315 final Rect mPendingBackDropFrame = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
317 = new ViewTreeObserver.InternalInsetsInfo();
318
Adrian Roosfa104232014-06-20 16:10:14 -0700319 final Rect mDispatchContentInsets = new Rect();
320 final Rect mDispatchStableInsets = new Rect();
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -0700321
Filip Gruszczynski954289d2015-02-26 15:46:47 -0800322 private WindowInsets mLastWindowInsets;
323
Dianne Hackborn694f79b2010-03-17 19:44:59 -0700324 final Configuration mLastConfiguration = new Configuration();
325 final Configuration mPendingConfiguration = new Configuration();
Romain Guy59a12ca2011-06-09 17:48:21 -0700326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 boolean mScrollMayChange;
328 int mSoftInputMode;
Svetoslav Ganov149567f2013-01-08 15:23:34 -0800329 WeakReference<View> mLastScrolledFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 int mScrollY;
331 int mCurScrollY;
332 Scroller mScroller;
John Recke56e9df2014-02-21 15:45:10 -0800333 static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
Chet Haasecca2c982011-05-20 14:34:18 -0700334 private ArrayList<LayoutTransition> mPendingTransitions;
Romain Guy8506ab42009-06-11 17:35:47 -0700335
Romain Guy8506ab42009-06-11 17:35:47 -0700336 final ViewConfiguration mViewConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337
Christopher Tatea53146c2010-09-07 11:57:52 -0700338 /* Drag/drop */
339 ClipDescription mDragDescription;
340 View mCurrentDragView;
Christopher Tate7fb8b562011-01-20 13:46:41 -0800341 volatile Object mLocalDragState;
Christopher Tatea53146c2010-09-07 11:57:52 -0700342 final PointF mDragPoint = new PointF();
Christopher Tate2c095f32010-10-04 14:13:40 -0700343 final PointF mLastTouchPoint = new PointF();
Vladislav Kaznacheevba761122016-01-22 12:09:45 -0800344 int mLastTouchSource;
Igor Murashkina86ab6402013-08-30 12:58:36 -0700345
346 private boolean mProfileRendering;
Romain Guyd0750312012-11-29 11:34:43 -0800347 private Choreographer.FrameCallback mRenderProfiler;
348 private boolean mRenderProfilingEnabled;
Christopher Tatea53146c2010-09-07 11:57:52 -0700349
Chet Haase2f2022a2011-10-11 06:41:59 -0700350 // Variables to track frames per second, enabled via DEBUG_FPS flag
351 private long mFpsStartTime = -1;
352 private long mFpsPrevTime = -1;
353 private int mFpsNumFrames;
354
Jun Mukai1db53972015-09-11 18:08:31 -0700355 private int mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
Jun Mukaid4eaef72015-10-30 15:54:33 -0700356 private PointerIcon mCustomPointerIcon = null;
Jun Mukai1db53972015-09-11 18:08:31 -0700357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 /**
359 * see {@link #playSoundEffect(int)}
360 */
361 AudioManager mAudioManager;
362
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700363 final AccessibilityManager mAccessibilityManager;
364
Gilles Debunne5ac84422011-10-19 09:35:58 -0700365 AccessibilityInteractionController mAccessibilityInteractionController;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700366
367 AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
Chris Craikcce47eb2014-07-16 15:12:15 -0700368 HighContrastTextManager mHighContrastTextManager;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700369
Svetoslav Ganova0156172011-06-26 17:55:44 -0700370 SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -0700371
Svetoslav Ganov42138042012-03-20 11:51:39 -0700372 HashSet<View> mTempHashSet;
Svetoslav Ganov79311c42012-01-17 20:24:26 -0800373
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700374 private final int mDensity;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700375 private final int mNoncompatDensity;
Adam Powellb08013c2010-09-16 16:28:11 -0700376
Chet Haase97140572012-09-13 14:56:47 -0700377 private boolean mInLayout = false;
378 ArrayList<View> mLayoutRequesters = new ArrayList<View>();
379 boolean mHandlingLayoutInLayoutRequest = false;
380
Fabrice Di Megliob003e282012-10-17 17:20:19 -0700381 private int mViewLayoutDirectionInitial;
Chet Haase97140572012-09-13 14:56:47 -0700382
Craig Mautner8f303ad2013-06-14 11:32:22 -0700383 /** Set to true once doDie() has been called. */
384 private boolean mRemoved;
385
Jeff Brown21bc5c92011-02-28 18:27:14 -0800386 /**
387 * Consistency verifier for debugging purposes.
388 */
389 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
390 InputEventConsistencyVerifier.isInstrumentationEnabled() ?
391 new InputEventConsistencyVerifier(this, 0) : null;
392
Dianne Hackborn9a230e02011-10-06 11:51:27 -0700393 static final class SystemUiVisibilityInfo {
394 int seq;
395 int globalVisibility;
396 int localValue;
397 int localChanges;
398 }
Igor Murashkina86ab6402013-08-30 12:58:36 -0700399
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -0800400 private String mTag = TAG;
401
Jeff Brown98365d72012-08-19 20:30:52 -0700402 public ViewRootImpl(Context context, Display display) {
Jeff Brownf9e989d2013-04-04 23:04:03 -0700403 mContext = context;
404 mWindowSession = WindowManagerGlobal.getWindowSession();
Jeff Brown98365d72012-08-19 20:30:52 -0700405 mDisplay = display;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800406 mBasePackageName = context.getBasePackageName();
Jeff Brown98365d72012-08-19 20:30:52 -0700407
Craig Mautner48d0d182013-06-11 07:53:06 -0700408 mDisplayAdjustments = display.getDisplayAdjustments();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 mThread = Thread.currentThread();
411 mLocation = new WindowLeaked(null);
412 mLocation.fillInStackTrace();
413 mWidth = -1;
414 mHeight = -1;
415 mDirty = new Rect();
416 mTempRect = new Rect();
417 mVisRect = new Rect();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 mWinFrame = new Rect();
Romain Guyfb8b7632010-08-23 21:05:08 -0700419 mWindow = new W(this);
Dianne Hackborn180c4842011-09-13 12:39:25 -0700420 mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 mViewVisibility = View.GONE;
422 mTransparentRegion = new Region();
423 mPreviousTransparentRegion = new Region();
424 mFirst = true; // true for the first time the view is added
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 mAdded = false;
Chris Craikcce47eb2014-07-16 15:12:15 -0700426 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700427 mAccessibilityManager = AccessibilityManager.getInstance(context);
428 mAccessibilityInteractionConnectionManager =
429 new AccessibilityInteractionConnectionManager();
Svetoslav Ganov00d0c142012-02-24 11:30:49 -0800430 mAccessibilityManager.addAccessibilityStateChangeListener(
431 mAccessibilityInteractionConnectionManager);
Chris Craikcce47eb2014-07-16 15:12:15 -0700432 mHighContrastTextManager = new HighContrastTextManager();
433 mAccessibilityManager.addHighTextContrastStateChangeListener(
434 mHighContrastTextManager);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 mViewConfiguration = ViewConfiguration.get(context);
Dianne Hackborn11ea3342009-07-22 21:48:55 -0700436 mDensity = context.getResources().getDisplayMetrics().densityDpi;
Dianne Hackborn908aecc2012-07-31 16:37:34 -0700437 mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
Jorim Jaggib10e33f2015-02-04 21:57:40 +0100438 mFallbackEventHandler = new PhoneFallbackEventHandler(context);
Jeff Brown96e942d2011-11-30 19:55:01 -0800439 mChoreographer = Choreographer.getInstance();
Jeff Brownd912e1f2014-04-11 18:46:22 -0700440 mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
Dianne Hackborna53de062012-05-08 18:53:51 -0700441 loadSystemProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
443
Dianne Hackborn2a9094d2010-02-03 19:20:09 -0800444 public static void addFirstDrawHandler(Runnable callback) {
445 synchronized (sFirstDrawHandlers) {
446 if (!sFirstDrawComplete) {
447 sFirstDrawHandlers.add(callback);
448 }
449 }
450 }
Igor Murashkina86ab6402013-08-30 12:58:36 -0700451
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800452 public static void addConfigCallback(ComponentCallbacks callback) {
453 synchronized (sConfigCallbacks) {
454 sConfigCallbacks.add(callback);
455 }
456 }
Igor Murashkina86ab6402013-08-30 12:58:36 -0700457
Chong Zhangdcee1de2015-10-06 10:26:00 -0700458 public void addWindowCallbacks(WindowCallbacks callback) {
Skuhneb8160872015-09-22 09:51:39 -0700459 if (USE_MT_RENDERER) {
Chong Zhangdcee1de2015-10-06 10:26:00 -0700460 synchronized (mWindowCallbacks) {
461 mWindowCallbacks.add(callback);
Skuhneb8160872015-09-22 09:51:39 -0700462 }
463 }
464 }
465
Chong Zhangdcee1de2015-10-06 10:26:00 -0700466 public void removeWindowCallbacks(WindowCallbacks callback) {
Skuhneb8160872015-09-22 09:51:39 -0700467 if (USE_MT_RENDERER) {
Chong Zhangdcee1de2015-10-06 10:26:00 -0700468 synchronized (mWindowCallbacks) {
469 mWindowCallbacks.remove(callback);
Skuhneb8160872015-09-22 09:51:39 -0700470 }
471 }
472 }
473
Chong Zhang8dbd9ad2015-10-09 10:06:11 -0700474 public void reportDrawFinish() {
475 if (mWindowDrawCountDown != null) {
476 mWindowDrawCountDown.countDown();
477 }
478 }
479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 // FIXME for perf testing only
481 private boolean mProfile = false;
482
483 /**
484 * Call this to profile the next traversal call.
485 * FIXME for perf testing only. Remove eventually
486 */
487 public void profile() {
488 mProfile = true;
489 }
490
491 /**
492 * Indicates whether we are in touch mode. Calling this method triggers an IPC
493 * call and should be avoided whenever possible.
494 *
495 * @return True, if the device is in touch mode, false otherwise.
496 *
497 * @hide
498 */
499 static boolean isInTouchMode() {
Jeff Brown98365d72012-08-19 20:30:52 -0700500 IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
501 if (windowSession != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 try {
Jeff Brown98365d72012-08-19 20:30:52 -0700503 return windowSession.getInTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 } catch (RemoteException e) {
505 }
506 }
507 return false;
508 }
509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 /**
511 * We have one child
512 */
Romain Guye4d01122010-06-16 18:44:05 -0700513 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 synchronized (this) {
515 if (mView == null) {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -0700516 mView = view;
Jeff Brownd912e1f2014-04-11 18:46:22 -0700517
518 mAttachInfo.mDisplayState = mDisplay.getState();
519 mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
520
Fabrice Di Megliob003e282012-10-17 17:20:19 -0700521 mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
Joe Onorato86f67862010-11-05 18:57:34 -0700522 mFallbackEventHandler.setView(view);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700523 mWindowAttributes.copyFrom(attrs);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800524 if (mWindowAttributes.packageName == null) {
525 mWindowAttributes.packageName = mBasePackageName;
526 }
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700527 attrs = mWindowAttributes;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -0800528 setTag();
Dianne Hackborn9d090892012-06-11 18:35:41 -0700529 // Keep track of the actual window flags supplied by the client.
530 mClientWindowLayoutFlags = attrs.flags;
Svetoslav Ganov791fd312012-05-14 15:12:30 -0700531
Svetoslav Ganov45a02e02012-06-17 15:07:29 -0700532 setAccessibilityFocus(null, null);
Svetoslav Ganov791fd312012-05-14 15:12:30 -0700533
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700534 if (view instanceof RootViewSurfaceTaker) {
535 mSurfaceHolderCallback =
536 ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
537 if (mSurfaceHolderCallback != null) {
538 mSurfaceHolder = new TakenSurfaceHolder();
Dianne Hackborn289b9b62010-07-09 11:44:11 -0700539 mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -0700540 }
541 }
Romain Guy1aec9a22011-01-05 09:37:12 -0800542
Alan Viverette49a22e82014-07-12 20:01:27 -0700543 // Compute surface insets required to draw at specified Z value.
544 // TODO: Use real shadow insets for a constant max Z.
Alan Viverette5435a302015-01-29 10:25:34 -0800545 if (!attrs.hasManualSurfaceInsets) {
546 final int surfaceInset = (int) Math.ceil(view.getZ() * 2);
547 attrs.surfaceInsets.set(surfaceInset, surfaceInset, surfaceInset, surfaceInset);
548 }
Alan Viverette49a22e82014-07-12 20:01:27 -0700549
Craig Mautner48d0d182013-06-11 07:53:06 -0700550 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
Romain Guy856d4e12011-10-14 15:47:55 -0700551 mTranslator = compatibilityInfo.getTranslator();
552
Romain Guy1aec9a22011-01-05 09:37:12 -0800553 // If the application owns the surface, don't enable hardware acceleration
554 if (mSurfaceHolder == null) {
Romain Guy3b748a42013-04-17 18:54:38 -0700555 enableHardwareAcceleration(attrs);
Romain Guy1aec9a22011-01-05 09:37:12 -0800556 }
557
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700558 boolean restore = false;
Romain Guy35b38ce2009-10-07 13:38:55 -0700559 if (mTranslator != null) {
Romain Guy856d4e12011-10-14 15:47:55 -0700560 mSurface.setCompatibilityTranslator(mTranslator);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700561 restore = true;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700562 attrs.backup();
563 mTranslator.translateWindowLayout(attrs);
Mitsuru Oshima3d914922009-05-13 22:29:15 -0700564 }
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -0800565 if (DEBUG_LAYOUT) Log.d(mTag, "WindowLayout in setView:" + attrs);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700566
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700567 if (!compatibilityInfo.supportsScreen()) {
Adam Lesinski95c42972013-10-02 10:13:27 -0700568 attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700569 mLastInCompatMode = true;
Mitsuru Oshima1ecf5d22009-07-06 17:20:38 -0700570 }
571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 mSoftInputMode = attrs.softInputMode;
573 mWindowAttributesChanged = true;
Romain Guyf21c9b02011-09-06 16:56:54 -0700574 mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 mAttachInfo.mRootView = view;
Romain Guy35b38ce2009-10-07 13:38:55 -0700576 mAttachInfo.mScalingRequired = mTranslator != null;
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700577 mAttachInfo.mApplicationScale =
578 mTranslator == null ? 1.0f : mTranslator.applicationScale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 if (panelParentView != null) {
580 mAttachInfo.mPanelParentWindowToken
581 = panelParentView.getApplicationWindowToken();
582 }
583 mAdded = true;
584 int res; /* = WindowManagerImpl.ADD_OKAY; */
Romain Guy8506ab42009-06-11 17:35:47 -0700585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 // Schedule the first layout -before- adding to the window
587 // manager, to make sure we do the relayout before receiving
588 // any other events from the system.
589 requestLayout();
Jeff Browncc4f7db2011-08-30 20:34:48 -0700590 if ((mWindowAttributes.inputFeatures
591 & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
592 mInputChannel = new InputChannel();
593 }
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -0800594 mForceDecorViewVisibility = (mWindowAttributes.privateFlags
595 & PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 try {
Dianne Hackborn180c4842011-09-13 12:39:25 -0700597 mOrigWindowType = mWindowAttributes.type;
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -0700598 mAttachInfo.mRecomputeGlobalAttributes = true;
599 collectViewAttributes();
Jeff Brown98365d72012-08-19 20:30:52 -0700600 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
601 getHostVisibility(), mDisplay.getDisplayId(),
Filip Gruszczynski0ec13282015-06-25 11:26:01 -0700602 mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
603 mAttachInfo.mOutsets, mInputChannel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 } catch (RemoteException e) {
605 mAdded = false;
606 mView = null;
607 mAttachInfo.mRootView = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700608 mInputChannel = null;
Joe Onorato86f67862010-11-05 18:57:34 -0700609 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 unscheduleTraversals();
Svetoslav Ganov45a02e02012-06-17 15:07:29 -0700611 setAccessibilityFocus(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 throw new RuntimeException("Adding window failed", e);
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700613 } finally {
614 if (restore) {
615 attrs.restore();
616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
Igor Murashkina86ab6402013-08-30 12:58:36 -0700618
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700619 if (mTranslator != null) {
620 mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -0700621 }
Dianne Hackbornc4aad012013-02-22 15:05:25 -0800622 mPendingOverscanInsets.set(0, 0, 0, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 mPendingContentInsets.set(mAttachInfo.mContentInsets);
Adrian Roosfa104232014-06-20 16:10:14 -0700624 mPendingStableInsets.set(mAttachInfo.mStableInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 mPendingVisibleInsets.set(0, 0, 0, 0);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -0800626 if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);
Jeff Brown98365d72012-08-19 20:30:52 -0700627 if (res < WindowManagerGlobal.ADD_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 mAttachInfo.mRootView = null;
629 mAdded = false;
Joe Onorato86f67862010-11-05 18:57:34 -0700630 mFallbackEventHandler.setView(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 unscheduleTraversals();
Svetoslav Ganov45a02e02012-06-17 15:07:29 -0700632 setAccessibilityFocus(null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 switch (res) {
Jeff Brown98365d72012-08-19 20:30:52 -0700634 case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
635 case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
636 throw new WindowManager.BadTokenException(
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800637 "Unable to add window -- token " + attrs.token
638 + " is not valid; is your activity running?");
Jeff Brown98365d72012-08-19 20:30:52 -0700639 case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
640 throw new WindowManager.BadTokenException(
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800641 "Unable to add window -- token " + attrs.token
642 + " is not for an application");
Jeff Brown98365d72012-08-19 20:30:52 -0700643 case WindowManagerGlobal.ADD_APP_EXITING:
644 throw new WindowManager.BadTokenException(
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800645 "Unable to add window -- app for token " + attrs.token
646 + " is exiting");
Jeff Brown98365d72012-08-19 20:30:52 -0700647 case WindowManagerGlobal.ADD_DUPLICATE_ADD:
648 throw new WindowManager.BadTokenException(
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800649 "Unable to add window -- window " + mWindow
650 + " has already been added");
Jeff Brown98365d72012-08-19 20:30:52 -0700651 case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 // Silently ignore -- we would have just removed it
653 // right away, anyway.
654 return;
Jeff Brown98365d72012-08-19 20:30:52 -0700655 case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
Alan Viverette73f6d602015-09-14 16:01:19 -0400656 throw new WindowManager.BadTokenException("Unable to add window "
657 + mWindow + " -- another window of type "
658 + mWindowAttributes.type + " already exists");
Jeff Brown98365d72012-08-19 20:30:52 -0700659 case WindowManagerGlobal.ADD_PERMISSION_DENIED:
Alan Viverette73f6d602015-09-14 16:01:19 -0400660 throw new WindowManager.BadTokenException("Unable to add window "
661 + mWindow + " -- permission denied for window type "
662 + mWindowAttributes.type);
Craig Mautner6018aee2012-10-23 14:27:49 -0700663 case WindowManagerGlobal.ADD_INVALID_DISPLAY:
Alan Viverette73f6d602015-09-14 16:01:19 -0400664 throw new WindowManager.InvalidDisplayException("Unable to add window "
665 + mWindow + " -- the specified display can not be found");
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800666 case WindowManagerGlobal.ADD_INVALID_TYPE:
Alan Viverette73f6d602015-09-14 16:01:19 -0400667 throw new WindowManager.InvalidDisplayException("Unable to add window "
668 + mWindow + " -- the specified window type "
669 + mWindowAttributes.type + " is not valid");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671 throw new RuntimeException(
Wale Ogunwale74bf0652015-01-12 10:24:36 -0800672 "Unable to add window -- unknown error code " + res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700674
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700675 if (view instanceof RootViewSurfaceTaker) {
676 mInputQueueCallback =
677 ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
678 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700679 if (mInputChannel != null) {
680 if (mInputQueueCallback != null) {
Michael Wrighta44dd262013-04-10 21:12:00 -0700681 mInputQueue = new InputQueue();
Jeff Browncc4f7db2011-08-30 20:34:48 -0700682 mInputQueueCallback.onInputQueueCreated(mInputQueue);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700683 }
Michael Wrighta44dd262013-04-10 21:12:00 -0700684 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
685 Looper.myLooper());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700686 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 view.assignParent(this);
Jeff Brown98365d72012-08-19 20:30:52 -0700689 mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
690 mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -0700691
692 if (mAccessibilityManager.isEnabled()) {
693 mAccessibilityInteractionConnectionManager.ensureConnection();
694 }
Svetoslav Ganov42138042012-03-20 11:51:39 -0700695
696 if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
697 view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
698 }
Michael Wright95ae9422013-03-14 10:58:50 -0700699
Jeff Brownf9e989d2013-04-04 23:04:03 -0700700 // Set up the input pipeline.
701 CharSequence counterSuffix = attrs.getTitle();
Michael Wright899d7052014-04-23 17:23:39 -0700702 mSyntheticInputStage = new SyntheticInputStage();
703 InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
Jeff Brownf9e989d2013-04-04 23:04:03 -0700704 InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
705 "aq:native-post-ime:" + counterSuffix);
706 InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
707 InputStage imeStage = new ImeInputStage(earlyPostImeStage,
708 "aq:ime:" + counterSuffix);
709 InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
710 InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
711 "aq:native-pre-ime:" + counterSuffix);
712
713 mFirstInputStage = nativePreImeStage;
714 mFirstPostImeInputStage = earlyPostImeStage;
715 mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717 }
718 }
719
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -0800720 private void setTag() {
721 final String[] split = mWindowAttributes.getTitle().toString().split("\\.");
722 if (split.length > 0) {
723 mTag = TAG + "[" + split[split.length - 1] + "]";
724 }
725 }
726
keunyoung30f420f2013-08-02 14:23:10 -0700727 /** Whether the window is in local focus mode or not */
728 private boolean isInLocalFocusMode() {
729 return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0;
730 }
731
Dianne Hackborn49b043f2015-05-07 14:21:38 -0700732 public int getWindowFlags() {
733 return mWindowAttributes.flags;
734 }
735
Dianne Hackbornece0f4f2015-06-11 13:29:01 -0700736 public int getDisplayId() {
737 return mDisplay.getDisplayId();
738 }
739
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -0800740 public CharSequence getTitle() {
741 return mWindowAttributes.getTitle();
742 }
743
Romain Guy8ff6b9e2011-11-09 20:10:18 -0800744 void destroyHardwareResources() {
Romain Guy31f2c2e2011-11-21 10:55:41 -0800745 if (mAttachInfo.mHardwareRenderer != null) {
746 mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
John Reckf47a5942014-06-30 16:20:04 -0700747 mAttachInfo.mHardwareRenderer.destroy();
Romain Guy31f2c2e2011-11-21 10:55:41 -0800748 }
749 }
750
Bo Liu845535a2014-03-21 12:06:23 -0700751 public void detachFunctor(long functor) {
John Reck44ac42a2014-05-16 14:46:07 -0700752 if (mAttachInfo.mHardwareRenderer != null) {
753 // Fence so that any pending invokeFunctor() messages will be processed
754 // before we return from detachFunctor.
John Reckf47a5942014-06-30 16:20:04 -0700755 mAttachInfo.mHardwareRenderer.stopDrawing();
John Reck44ac42a2014-05-16 14:46:07 -0700756 }
Romain Guyba6be8a2012-04-23 18:22:09 -0700757 }
758
John Reck3b202512014-06-23 13:13:08 -0700759 /**
760 * Schedules the functor for execution in either kModeProcess or
761 * kModeProcessNoContext, depending on whether or not there is an EGLContext.
762 *
763 * @param functor The native functor to invoke
764 * @param waitForCompletion If true, this will not return until the functor
765 * has invoked. If false, the functor may be invoked
766 * asynchronously.
767 */
Hui Shu9970aee2014-06-23 17:10:30 -0700768 public void invokeFunctor(long functor, boolean waitForCompletion) {
John Reck3b202512014-06-23 13:13:08 -0700769 ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
Bo Liuae738a72014-04-27 16:22:04 -0700770 }
771
John Reck119907c2014-08-14 09:02:01 -0700772 public void registerAnimatingRenderNode(RenderNode animator) {
773 if (mAttachInfo.mHardwareRenderer != null) {
774 mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
775 } else {
776 if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
777 mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
778 }
779 mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
780 }
781 }
782
Romain Guy3b748a42013-04-17 18:54:38 -0700783 private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800784 mAttachInfo.mHardwareAccelerated = false;
785 mAttachInfo.mHardwareAccelerationRequested = false;
Romain Guy4f6aff32011-01-12 16:21:41 -0800786
Romain Guy856d4e12011-10-14 15:47:55 -0700787 // Don't enable hardware acceleration when the application is in compatibility mode
John Reckdd58e792014-04-02 16:54:28 +0000788 if (mTranslator != null) return;
Romain Guy856d4e12011-10-14 15:47:55 -0700789
Dianne Hackborn7eec10e2010-11-12 18:03:47 -0800790 // Try to enable hardware acceleration if requested
Igor Murashkina86ab6402013-08-30 12:58:36 -0700791 final boolean hardwareAccelerated =
Jim Miller1b365922011-03-09 19:38:07 -0800792 (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
793
John Reckdd58e792014-04-02 16:54:28 +0000794 if (hardwareAccelerated) {
John Reck51aaf902015-12-02 15:08:07 -0800795 if (!ThreadedRenderer.isAvailable()) {
Romain Guy1af23a32011-03-24 16:03:55 -0700796 return;
797 }
798
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700799 // Persistent processes (including the system) should not do
800 // accelerated rendering on low-end devices. In that case,
801 // sRendererDisabled will be set. In addition, the system process
802 // itself should never do accelerated rendering. In that case, both
803 // sRendererDisabled and sSystemRendererDisabled are set. When
804 // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
805 // can be used by code on the system process to escape that and enable
806 // HW accelerated drawing. (This is basically for the lock screen.)
Jim Miller1b365922011-03-09 19:38:07 -0800807
John Reck61375a82014-09-18 19:27:48 +0000808 final boolean fakeHwAccelerated = (attrs.privateFlags &
809 WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
Dianne Hackborn5d927c22011-09-02 12:22:18 -0700810 final boolean forceHwAccelerated = (attrs.privateFlags &
811 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
Jim Miller1b365922011-03-09 19:38:07 -0800812
John Reck61375a82014-09-18 19:27:48 +0000813 if (fakeHwAccelerated) {
814 // This is exclusively for the preview windows the window manager
815 // shows for launching applications, so they will look more like
816 // the app being launched.
817 mAttachInfo.mHardwareAccelerationRequested = true;
John Reck51aaf902015-12-02 15:08:07 -0800818 } else if (!ThreadedRenderer.sRendererDisabled
819 || (ThreadedRenderer.sSystemRendererDisabled && forceHwAccelerated)) {
Romain Guyb051e892010-09-28 19:09:36 -0700820 if (mAttachInfo.mHardwareRenderer != null) {
John Reckf47a5942014-06-30 16:20:04 -0700821 mAttachInfo.mHardwareRenderer.destroy();
Romain Guy211370f2012-02-01 16:10:55 -0800822 }
823
Alan Viverette2b12b582014-10-29 11:11:40 -0700824 final Rect insets = attrs.surfaceInsets;
Alan Viverette2cd23e62014-11-04 17:04:02 -0800825 final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
826 || insets.top != 0 || insets.bottom != 0;
Alan Viverette2b12b582014-10-29 11:11:40 -0700827 final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
John Reck51aaf902015-12-02 15:08:07 -0800828 mAttachInfo.mHardwareRenderer = ThreadedRenderer.create(mContext, translucent);
Romain Guye55945e2013-04-04 15:26:04 -0700829 if (mAttachInfo.mHardwareRenderer != null) {
830 mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
831 mAttachInfo.mHardwareAccelerated =
832 mAttachInfo.mHardwareAccelerationRequested = true;
833 }
Romain Guye4d01122010-06-16 18:44:05 -0700834 }
835 }
836 }
837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 public View getView() {
839 return mView;
840 }
841
842 final WindowLeaked getLocation() {
843 return mLocation;
844 }
845
846 void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
847 synchronized (this) {
Alan Viverettedbed8932014-08-06 17:54:52 -0700848 final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
849 final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
850 final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
851 final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
852 final int oldSoftInputMode = mWindowAttributes.softInputMode;
Alan Viverette5435a302015-01-29 10:25:34 -0800853 final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
Alan Viverettedbed8932014-08-06 17:54:52 -0700854
Dianne Hackborn9d090892012-06-11 18:35:41 -0700855 // Keep track of the actual window flags supplied by the client.
856 mClientWindowLayoutFlags = attrs.flags;
Alan Viverettedbed8932014-08-06 17:54:52 -0700857
858 // Preserve compatible window flag if exists.
859 final int compatibleWindowFlag = mWindowAttributes.privateFlags
Adam Lesinski95c42972013-10-02 10:13:27 -0700860 & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
Alan Viverettedbed8932014-08-06 17:54:52 -0700861
862 // Transfer over system UI visibility values as they carry current state.
Craig Mautner3fe38c02012-05-03 17:28:09 -0700863 attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
864 attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
Alan Viverettedbed8932014-08-06 17:54:52 -0700865
Romain Guyf21c9b02011-09-06 16:56:54 -0700866 mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
John Spurlockbd957402013-10-03 11:38:39 -0400867 if ((mWindowAttributesChangesFlag
868 & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
869 // Recompute system ui visibility.
870 mAttachInfo.mRecomputeGlobalAttributes = true;
871 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800872 if (mWindowAttributes.packageName == null) {
873 mWindowAttributes.packageName = mBasePackageName;
874 }
Adam Lesinski95c42972013-10-02 10:13:27 -0700875 mWindowAttributes.privateFlags |= compatibleWindowFlag;
Dianne Hackborn9d090892012-06-11 18:35:41 -0700876
Alan Viverettedbed8932014-08-06 17:54:52 -0700877 // Restore old surface insets.
878 mWindowAttributes.surfaceInsets.set(
879 oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
Alan Viverette5435a302015-01-29 10:25:34 -0800880 mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
Alan Viverettedbed8932014-08-06 17:54:52 -0700881
Dianne Hackborn9d090892012-06-11 18:35:41 -0700882 applyKeepScreenOnFlag(mWindowAttributes);
883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 if (newView) {
885 mSoftInputMode = attrs.softInputMode;
886 requestLayout();
887 }
Alan Viverettedbed8932014-08-06 17:54:52 -0700888
The Android Open Source Project10592532009-03-18 17:39:46 -0700889 // Don't lose the mode we last auto-computed.
Alan Viverettedbed8932014-08-06 17:54:52 -0700890 if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
The Android Open Source Project10592532009-03-18 17:39:46 -0700891 == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
892 mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
893 & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
Alan Viverettedbed8932014-08-06 17:54:52 -0700894 | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
The Android Open Source Project10592532009-03-18 17:39:46 -0700895 }
Alan Viverettedbed8932014-08-06 17:54:52 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 mWindowAttributesChanged = true;
898 scheduleTraversals();
899 }
900 }
901
902 void handleAppVisibility(boolean visible) {
903 if (mAppVisible != visible) {
904 mAppVisible = visible;
905 scheduleTraversals();
John Reck73840ea2014-09-22 07:39:18 -0700906 if (!mAppVisible) {
907 WindowManagerGlobal.trimForeground();
908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 }
910 }
911
912 void handleGetNewSurface() {
913 mNewSurfaceNeeded = true;
914 mFullRedrawNeeded = true;
915 scheduleTraversals();
916 }
917
Jeff Brownd912e1f2014-04-11 18:46:22 -0700918 private final DisplayListener mDisplayListener = new DisplayListener() {
919 @Override
920 public void onDisplayChanged(int displayId) {
921 if (mView != null && mDisplay.getDisplayId() == displayId) {
922 final int oldDisplayState = mAttachInfo.mDisplayState;
923 final int newDisplayState = mDisplay.getState();
924 if (oldDisplayState != newDisplayState) {
925 mAttachInfo.mDisplayState = newDisplayState;
Jeff Brownc2932a12014-11-20 18:04:05 -0800926 pokeDrawLockIfNeeded();
Jeff Brownd912e1f2014-04-11 18:46:22 -0700927 if (oldDisplayState != Display.STATE_UNKNOWN) {
928 final int oldScreenState = toViewScreenState(oldDisplayState);
929 final int newScreenState = toViewScreenState(newDisplayState);
930 if (oldScreenState != newScreenState) {
931 mView.dispatchScreenStateChanged(newScreenState);
932 }
933 if (oldDisplayState == Display.STATE_OFF) {
934 // Draw was suppressed so we need to for it to happen here.
935 mFullRedrawNeeded = true;
936 scheduleTraversals();
937 }
938 }
939 }
Romain Guy7e4e5612012-03-05 14:37:29 -0800940 }
941 }
Jeff Brownd912e1f2014-04-11 18:46:22 -0700942
943 @Override
944 public void onDisplayRemoved(int displayId) {
945 }
946
947 @Override
948 public void onDisplayAdded(int displayId) {
949 }
950
951 private int toViewScreenState(int displayState) {
952 return displayState == Display.STATE_OFF ?
953 View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
954 }
955 };
Romain Guy7e4e5612012-03-05 14:37:29 -0800956
Jeff Brownc2932a12014-11-20 18:04:05 -0800957 void pokeDrawLockIfNeeded() {
958 final int displayState = mAttachInfo.mDisplayState;
959 if (mView != null && mAdded && mTraversalScheduled
960 && (displayState == Display.STATE_DOZE
961 || displayState == Display.STATE_DOZE_SUSPEND)) {
962 try {
963 mWindowSession.pokeDrawLock(mWindow);
964 } catch (RemoteException ex) {
965 // System server died, oh well.
966 }
967 }
968 }
969
Craig Mautner6018aee2012-10-23 14:27:49 -0700970 @Override
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -0700971 public void requestFitSystemWindows() {
972 checkThread();
Adrian Roosfa104232014-06-20 16:10:14 -0700973 mApplyInsetsRequested = true;
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -0700974 scheduleTraversals();
975 }
976
Craig Mautner6018aee2012-10-23 14:27:49 -0700977 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 public void requestLayout() {
Chet Haase3efa7b52012-12-03 08:33:17 -0800979 if (!mHandlingLayoutInLayoutRequest) {
980 checkThread();
981 mLayoutRequested = true;
982 scheduleTraversals();
983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
Craig Mautner6018aee2012-10-23 14:27:49 -0700986 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public boolean isLayoutRequested() {
988 return mLayoutRequested;
989 }
990
Romain Guycfef1232012-02-23 13:50:37 -0800991 void invalidate() {
992 mDirty.set(0, 0, mWidth, mHeight);
John Recke4267ea2014-06-03 15:53:15 -0700993 if (!mWillDrawSoon) {
994 scheduleTraversals();
995 }
Romain Guycfef1232012-02-23 13:50:37 -0800996 }
997
Dianne Hackborna53de062012-05-08 18:53:51 -0700998 void invalidateWorld(View view) {
999 view.invalidate();
1000 if (view instanceof ViewGroup) {
Romain Guyf84208f2012-09-13 22:50:18 -07001001 ViewGroup parent = (ViewGroup) view;
1002 for (int i = 0; i < parent.getChildCount(); i++) {
Dianne Hackborna53de062012-05-08 18:53:51 -07001003 invalidateWorld(parent.getChildAt(i));
1004 }
1005 }
1006 }
1007
Craig Mautner6018aee2012-10-23 14:27:49 -07001008 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 public void invalidateChild(View child, Rect dirty) {
Romain Guycfef1232012-02-23 13:50:37 -08001010 invalidateChildInParent(null, dirty);
1011 }
1012
Craig Mautner8f303ad2013-06-14 11:32:22 -07001013 @Override
Romain Guycfef1232012-02-23 13:50:37 -08001014 public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 checkThread();
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001016 if (DEBUG_DRAW) Log.v(mTag, "Invalidate child: " + dirty);
Romain Guycfef1232012-02-23 13:50:37 -08001017
Chet Haase70d4ba12010-10-06 09:46:45 -07001018 if (dirty == null) {
Chet Haase70d4ba12010-10-06 09:46:45 -07001019 invalidate();
Romain Guycfef1232012-02-23 13:50:37 -08001020 return null;
Chet Haase3561d062012-10-23 12:54:51 -07001021 } else if (dirty.isEmpty() && !mIsAnimating) {
Chet Haase05e91ed2012-07-03 14:17:57 -07001022 return null;
Chet Haase70d4ba12010-10-06 09:46:45 -07001023 }
Romain Guycfef1232012-02-23 13:50:37 -08001024
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001025 if (mCurScrollY != 0 || mTranslator != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 mTempRect.set(dirty);
Romain Guy1e095972009-07-07 11:22:45 -07001027 dirty = mTempRect;
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001028 if (mCurScrollY != 0) {
Romain Guycfef1232012-02-23 13:50:37 -08001029 dirty.offset(0, -mCurScrollY);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001030 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001031 if (mTranslator != null) {
Romain Guy1e095972009-07-07 11:22:45 -07001032 mTranslator.translateRectInAppWindowToScreen(dirty);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001033 }
Romain Guy1e095972009-07-07 11:22:45 -07001034 if (mAttachInfo.mScalingRequired) {
1035 dirty.inset(-1, -1);
1036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Romain Guycfef1232012-02-23 13:50:37 -08001038
Alan Viverettea7ea65e2015-05-15 11:30:21 -07001039 invalidateRectOnScreen(dirty);
1040
1041 return null;
1042 }
1043
1044 private void invalidateRectOnScreen(Rect dirty) {
Romain Guycfef1232012-02-23 13:50:37 -08001045 final Rect localDirty = mDirty;
1046 if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
Romain Guy02ccac62011-06-24 13:20:23 -07001047 mAttachInfo.mSetIgnoreDirtyState = true;
Romain Guy7d695942010-12-01 17:22:29 -08001048 mAttachInfo.mIgnoreDirtyState = true;
1049 }
Romain Guycfef1232012-02-23 13:50:37 -08001050
1051 // Add the new dirty rect to the current one
1052 localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
1053 // Intersect with the bounds of the window to skip
1054 // updates that lie outside of the visible region
Romain Guy7b2f8b82012-03-19 17:18:54 -07001055 final float appScale = mAttachInfo.mApplicationScale;
Chet Haase3561d062012-10-23 12:54:51 -07001056 final boolean intersected = localDirty.intersect(0, 0,
1057 (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1058 if (!intersected) {
Chet Haaseb78ee0e2012-10-17 11:32:01 -07001059 localDirty.setEmpty();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
Chet Haase3561d062012-10-23 12:54:51 -07001061 if (!mWillDrawSoon && (intersected || mIsAnimating)) {
1062 scheduleTraversals();
1063 }
Romain Guy0d9275e2010-10-26 14:22:30 -07001064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065
Daniel Koulomzin087ae472015-12-16 17:52:25 -05001066 public void setIsAmbientMode(boolean ambient) {
1067 mIsAmbientMode = ambient;
1068 }
1069
George Mount41725de2015-04-09 08:23:05 -07001070 void setWindowStopped(boolean stopped) {
Dianne Hackbornce418e62011-03-01 14:31:38 -08001071 if (mStopped != stopped) {
1072 mStopped = stopped;
George Mount41725de2015-04-09 08:23:05 -07001073 if (!mStopped) {
Dianne Hackbornce418e62011-03-01 14:31:38 -08001074 scheduleTraversals();
1075 }
1076 }
1077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078
George Mount41725de2015-04-09 08:23:05 -07001079 /**
1080 * Block the input events during an Activity Transition. The KEYCODE_BACK event is allowed
1081 * through to allow quick reversal of the Activity Transition.
1082 *
1083 * @param paused true to pause, false to resume.
1084 */
1085 public void setPausedForTransition(boolean paused) {
1086 mPausedForTransition = paused;
1087 }
1088
Craig Mautner8f303ad2013-06-14 11:32:22 -07001089 @Override
Romain Guycfef1232012-02-23 13:50:37 -08001090 public ViewParent getParent() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 return null;
1092 }
1093
Craig Mautner8f303ad2013-06-14 11:32:22 -07001094 @Override
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001095 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 if (child != mView) {
1097 throw new RuntimeException("child is not mine, honest!");
1098 }
1099 // Note: don't apply scroll offset, because we want to know its
1100 // visibility in the virtual canvas being given to the view hierarchy.
1101 return r.intersect(0, 0, mWidth, mHeight);
1102 }
1103
Igor Murashkina86ab6402013-08-30 12:58:36 -07001104 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 public void bringChildToFront(View child) {
1106 }
1107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 int getHostVisibility() {
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -08001109 return (mAppVisible || mForceDecorViewVisibility) ? mView.getVisibility() : View.GONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
Romain Guy8506ab42009-06-11 17:35:47 -07001111
Chet Haasecca2c982011-05-20 14:34:18 -07001112 /**
1113 * Add LayoutTransition to the list of transitions to be started in the next traversal.
1114 * This list will be cleared after the transitions on the list are start()'ed. These
1115 * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
1116 * happens during the layout phase of traversal, which we want to complete before any of the
1117 * animations are started (because those animations may side-effect properties that layout
1118 * depends upon, like the bounding rectangles of the affected views). So we add the transition
1119 * to the list and it is started just prior to starting the drawing phase of traversal.
1120 *
1121 * @param transition The LayoutTransition to be started on the next traversal.
1122 *
1123 * @hide
1124 */
1125 public void requestTransitionStart(LayoutTransition transition) {
1126 if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1127 if (mPendingTransitions == null) {
1128 mPendingTransitions = new ArrayList<LayoutTransition>();
1129 }
1130 mPendingTransitions.add(transition);
1131 }
1132 }
1133
John Recka5dda642014-05-22 15:43:54 -07001134 /**
1135 * Notifies the HardwareRenderer that a new frame will be coming soon.
1136 * Currently only {@link ThreadedRenderer} cares about this, and uses
1137 * this knowledge to adjust the scheduling of off-thread animations
1138 */
1139 void notifyRendererOfFramePending() {
1140 if (mAttachInfo.mHardwareRenderer != null) {
1141 mAttachInfo.mHardwareRenderer.notifyFramePending();
1142 }
1143 }
1144
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001145 void scheduleTraversals() {
1146 if (!mTraversalScheduled) {
1147 mTraversalScheduled = true;
Jeff Brown3d4e7efe2015-02-26 15:34:16 -08001148 mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001149 mChoreographer.postCallback(
1150 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
Michael Wright9d744c72014-02-18 21:27:42 -08001151 if (!mUnbufferedInputDispatch) {
1152 scheduleConsumeBatchedInput();
1153 }
John Recka5dda642014-05-22 15:43:54 -07001154 notifyRendererOfFramePending();
Jeff Brownc2932a12014-11-20 18:04:05 -08001155 pokeDrawLockIfNeeded();
Jeff Brown96e942d2011-11-30 19:55:01 -08001156 }
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001157 }
Jeff Brown96e942d2011-11-30 19:55:01 -08001158
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001159 void unscheduleTraversals() {
1160 if (mTraversalScheduled) {
1161 mTraversalScheduled = false;
Jeff Brown3d4e7efe2015-02-26 15:34:16 -08001162 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001163 mChoreographer.removeCallbacks(
1164 Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1165 }
1166 }
1167
1168 void doTraversal() {
1169 if (mTraversalScheduled) {
1170 mTraversalScheduled = false;
Jeff Brown3d4e7efe2015-02-26 15:34:16 -08001171 mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001172
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001173 if (mProfile) {
1174 Debug.startMethodTracing("ViewAncestor");
Jeff Brown96e942d2011-11-30 19:55:01 -08001175 }
Jeff Brown96e942d2011-11-30 19:55:01 -08001176
Chris Craike22c59b2015-05-21 18:33:37 -07001177 performTraversals();
Jeff Brown96e942d2011-11-30 19:55:01 -08001178
Jeff Brownebb2d8d2012-03-23 17:14:34 -07001179 if (mProfile) {
1180 Debug.stopMethodTracing();
1181 mProfile = false;
1182 }
Jeff Brown96e942d2011-11-30 19:55:01 -08001183 }
1184 }
1185
Dianne Hackborn9d090892012-06-11 18:35:41 -07001186 private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1187 // Update window's global keep screen on flag: if a view has requested
1188 // that the screen be kept on, then it is always set; otherwise, it is
1189 // set to whatever the client last requested for the global state.
1190 if (mAttachInfo.mKeepScreenOn) {
1191 params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1192 } else {
1193 params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1194 | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1195 }
1196 }
1197
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001198 private boolean collectViewAttributes() {
Chris Craikd36a81f2014-07-17 10:16:51 -07001199 if (mAttachInfo.mRecomputeGlobalAttributes) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001200 //Log.i(mTag, "Computing view hierarchy attributes!");
Chris Craikd36a81f2014-07-17 10:16:51 -07001201 mAttachInfo.mRecomputeGlobalAttributes = false;
1202 boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
1203 mAttachInfo.mKeepScreenOn = false;
1204 mAttachInfo.mSystemUiVisibility = 0;
1205 mAttachInfo.mHasSystemUiListeners = false;
1206 mView.dispatchCollectViewAttributes(mAttachInfo, 0);
1207 mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
Craig Mautner7eac0f52012-09-13 13:14:14 -07001208 WindowManager.LayoutParams params = mWindowAttributes;
Chris Craikd36a81f2014-07-17 10:16:51 -07001209 mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
1210 if (mAttachInfo.mKeepScreenOn != oldScreenOn
1211 || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1212 || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
Dianne Hackborn9d090892012-06-11 18:35:41 -07001213 applyKeepScreenOnFlag(params);
Chris Craikd36a81f2014-07-17 10:16:51 -07001214 params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1215 params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
1216 mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001217 return true;
1218 }
1219 }
1220 return false;
1221 }
1222
John Spurlockbd957402013-10-03 11:38:39 -04001223 private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
1224 int vis = 0;
1225 // Translucent decor window flags imply stable system ui visibility.
1226 if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
1227 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
1228 }
1229 if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
1230 vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
1231 }
1232 return vis;
1233 }
1234
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001235 private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1236 final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1237 int childWidthMeasureSpec;
1238 int childHeightMeasureSpec;
1239 boolean windowSizeMayChange = false;
1240
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001241 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(mTag,
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001242 "Measuring " + host + " in display " + desiredWindowWidth
1243 + "x" + desiredWindowHeight + "...");
1244
1245 boolean goodMeasure = false;
1246 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1247 // On large screens, we don't want to allow dialogs to just
1248 // stretch to fill the entire width of the screen to display
1249 // one line of text. First try doing the layout at a smaller
1250 // size to see if it will fit.
1251 final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1252 res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1253 int baseSize = 0;
1254 if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1255 baseSize = (int)mTmpValue.getDimension(packageMetrics);
1256 }
Filip Gruszczynski1937a4c2016-01-19 16:17:13 -08001257 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": baseSize=" + baseSize
1258 + ", desiredWindowWidth=" + desiredWindowWidth);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001259 if (baseSize != 0 && desiredWindowWidth > baseSize) {
1260 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1261 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
Jeff Brownc8d2668b2012-05-16 17:23:59 -07001262 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001263 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
Filip Gruszczynski1937a4c2016-01-19 16:17:13 -08001264 + host.getMeasuredWidth() + "," + host.getMeasuredHeight()
1265 + ") from width spec: " + MeasureSpec.toString(childWidthMeasureSpec)
1266 + " and height spec: " + MeasureSpec.toString(childHeightMeasureSpec));
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001267 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1268 goodMeasure = true;
1269 } else {
1270 // Didn't fit in that size... try expanding a bit.
1271 baseSize = (baseSize+desiredWindowWidth)/2;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001272 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": next baseSize="
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001273 + baseSize);
1274 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
Jeff Brownc8d2668b2012-05-16 17:23:59 -07001275 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001276 if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001277 + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1278 if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001279 if (DEBUG_DIALOG) Log.v(mTag, "Good!");
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001280 goodMeasure = true;
1281 }
1282 }
1283 }
1284 }
1285
1286 if (!goodMeasure) {
1287 childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1288 childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
Jeff Brownc8d2668b2012-05-16 17:23:59 -07001289 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001290 if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1291 windowSizeMayChange = true;
1292 }
1293 }
1294
1295 if (DBG) {
1296 System.out.println("======================================");
1297 System.out.println("performTraversals -- after measure");
1298 host.debug();
1299 }
1300
1301 return windowSizeMayChange;
1302 }
1303
Alan Viverettefed3f722013-11-14 14:48:20 -08001304 /**
1305 * Modifies the input matrix such that it maps view-local coordinates to
1306 * on-screen coordinates.
1307 *
1308 * @param m input matrix to modify
1309 */
1310 void transformMatrixToGlobal(Matrix m) {
Dake Gu7bf379c2014-07-15 16:29:38 -07001311 m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
Alan Viverettefed3f722013-11-14 14:48:20 -08001312 }
1313
1314 /**
1315 * Modifies the input matrix such that it maps on-screen coordinates to
1316 * view-local coordinates.
1317 *
1318 * @param m input matrix to modify
1319 */
1320 void transformMatrixToLocal(Matrix m) {
Dake Gu7bf379c2014-07-15 16:29:38 -07001321 m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
Alan Viverettefed3f722013-11-14 14:48:20 -08001322 }
1323
Filip Gruszczynski954289d2015-02-26 15:46:47 -08001324 /* package */ WindowInsets getWindowInsets(boolean forceConstruct) {
1325 if (mLastWindowInsets == null || forceConstruct) {
1326 mDispatchContentInsets.set(mAttachInfo.mContentInsets);
1327 mDispatchStableInsets.set(mAttachInfo.mStableInsets);
1328 Rect contentInsets = mDispatchContentInsets;
1329 Rect stableInsets = mDispatchStableInsets;
1330 // For dispatch we preserve old logic, but for direct requests from Views we allow to
1331 // immediately use pending insets.
1332 if (!forceConstruct
1333 && (!mPendingContentInsets.equals(contentInsets) ||
1334 !mPendingStableInsets.equals(stableInsets))) {
1335 contentInsets = mPendingContentInsets;
1336 stableInsets = mPendingStableInsets;
1337 }
Filip Gruszczynski2217f612015-05-26 11:32:08 -07001338 Rect outsets = mAttachInfo.mOutsets;
1339 if (outsets.left > 0 || outsets.top > 0 || outsets.right > 0 || outsets.bottom > 0) {
1340 contentInsets = new Rect(contentInsets.left + outsets.left,
1341 contentInsets.top + outsets.top, contentInsets.right + outsets.right,
1342 contentInsets.bottom + outsets.bottom);
1343 }
Filip Gruszczynski954289d2015-02-26 15:46:47 -08001344 mLastWindowInsets = new WindowInsets(contentInsets,
Adam Powell01f280d2015-05-18 16:07:42 -07001345 null /* windowDecorInsets */, stableInsets,
1346 mContext.getResources().getConfiguration().isScreenRound());
Filip Gruszczynski954289d2015-02-26 15:46:47 -08001347 }
1348 return mLastWindowInsets;
1349 }
1350
Adam Powell2accbf92014-04-16 23:14:57 +00001351 void dispatchApplyInsets(View host) {
Filip Gruszczynski954289d2015-02-26 15:46:47 -08001352 host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
Adam Powell2accbf92014-04-16 23:14:57 +00001353 }
1354
Chong Zhangf6525ce2016-01-14 17:09:56 -08001355 private static boolean shouldUseDisplaySize(final WindowManager.LayoutParams lp) {
1356 return lp.type == TYPE_STATUS_BAR_PANEL
1357 || lp.type == TYPE_INPUT_METHOD
1358 || lp.type == TYPE_VOLUME_OVERLAY;
1359 }
1360
1361 private int dipToPx(int dip) {
1362 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
1363 return (int) (displayMetrics.density * dip + 0.5f);
1364 }
1365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 private void performTraversals() {
1367 // cache mView since it is used so much below...
1368 final View host = mView;
1369
1370 if (DBG) {
1371 System.out.println("======================================");
1372 System.out.println("performTraversals");
1373 host.debug();
1374 }
1375
1376 if (host == null || !mAdded)
1377 return;
1378
Craig Mautnerdf2390a2012-08-29 20:59:22 -07001379 mIsInTraversal = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 mWillDrawSoon = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -08001381 boolean windowSizeMayChange = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 boolean newSurface = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001383 boolean surfaceChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 WindowManager.LayoutParams lp = mWindowAttributes;
1385
1386 int desiredWindowWidth;
1387 int desiredWindowHeight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 final int viewVisibility = getHostVisibility();
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001390 final boolean viewVisibilityChanged = !mFirst
1391 && (mViewVisibility != viewVisibility || mNewSurfaceNeeded);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392
1393 WindowManager.LayoutParams params = null;
1394 if (mWindowAttributesChanged) {
1395 mWindowAttributesChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001396 surfaceChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 params = lp;
1398 }
Craig Mautner48d0d182013-06-11 07:53:06 -07001399 CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001400 if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1401 params = lp;
Jeff Brown96e942d2011-11-30 19:55:01 -08001402 mFullRedrawNeeded = true;
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001403 mLayoutRequested = true;
1404 if (mLastInCompatMode) {
Adam Lesinski95c42972013-10-02 10:13:27 -07001405 params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001406 mLastInCompatMode = false;
1407 } else {
Adam Lesinski95c42972013-10-02 10:13:27 -07001408 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
Dianne Hackborn5fd21692011-06-07 14:09:47 -07001409 mLastInCompatMode = true;
1410 }
1411 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07001412
Romain Guyf21c9b02011-09-06 16:56:54 -07001413 mWindowAttributesChangesFlag = 0;
Igor Murashkina86ab6402013-08-30 12:58:36 -07001414
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001415 Rect frame = mWinFrame;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (mFirst) {
Jeff Brown96e942d2011-11-30 19:55:01 -08001417 mFullRedrawNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 mLayoutRequested = true;
1419
Chong Zhangf6525ce2016-01-14 17:09:56 -08001420 if (shouldUseDisplaySize(lp)) {
Dianne Hackborna239c842011-06-01 12:28:20 -07001421 // NOTE -- system code, won't try to do compat mode.
Jeff Brownbc68a592011-07-25 12:58:12 -07001422 Point size = new Point();
Jeff Brown98365d72012-08-19 20:30:52 -07001423 mDisplay.getRealSize(size);
Jeff Brownbc68a592011-07-25 12:58:12 -07001424 desiredWindowWidth = size.x;
1425 desiredWindowHeight = size.y;
Dianne Hackborna239c842011-06-01 12:28:20 -07001426 } else {
Chong Zhangf6525ce2016-01-14 17:09:56 -08001427 Configuration config = mContext.getResources().getConfiguration();
1428 desiredWindowWidth = dipToPx(config.screenWidthDp);
1429 desiredWindowHeight = dipToPx(config.screenHeightDp);
Dianne Hackborna239c842011-06-01 12:28:20 -07001430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431
Romain Guyc5d55862011-01-21 19:01:46 -08001432 // We used to use the following condition to choose 32 bits drawing caches:
1433 // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1434 // However, windows are now always 32 bits by default, so choose 32 bits
Chris Craikd36a81f2014-07-17 10:16:51 -07001435 mAttachInfo.mUse32BitDrawingCache = true;
1436 mAttachInfo.mHasWindowFocus = false;
1437 mAttachInfo.mWindowVisibility = viewVisibility;
1438 mAttachInfo.mRecomputeGlobalAttributes = false;
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001439 mLastConfiguration.setTo(host.getResources().getConfiguration());
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001440 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
Fabrice Di Megliob003e282012-10-17 17:20:19 -07001441 // Set the layout direction if it has not been set before (inherit is the default)
1442 if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1443 host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1444 }
Chris Craikd36a81f2014-07-17 10:16:51 -07001445 host.dispatchAttachedToWindow(mAttachInfo, 0);
1446 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
Adam Powell2accbf92014-04-16 23:14:57 +00001447 dispatchApplyInsets(host);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001448 //Log.i(mTag, "Screen on initialized: " + attachInfo.mKeepScreenOn);
svetoslavganov75986cf2009-05-14 22:28:01 -07001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 } else {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001451 desiredWindowWidth = frame.width();
1452 desiredWindowHeight = frame.height();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001454 if (DEBUG_ORIENTATION) Log.v(mTag, "View " + host + " resized to: " + frame);
Jeff Brown96e942d2011-11-30 19:55:01 -08001455 mFullRedrawNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 mLayoutRequested = true;
Dianne Hackborn711e62a2010-11-29 16:38:22 -08001457 windowSizeMayChange = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459 }
1460
1461 if (viewVisibilityChanged) {
Chris Craikd36a81f2014-07-17 10:16:51 -07001462 mAttachInfo.mWindowVisibility = viewVisibility;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 host.dispatchWindowVisibilityChanged(viewVisibility);
1464 if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
Skuhneb8160872015-09-22 09:51:39 -07001465 endDragResizing();
Romain Guy65b345f2011-07-27 18:51:50 -07001466 destroyHardwareResources();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 if (viewVisibility == View.GONE) {
1469 // After making a window gone, we will count it as being
1470 // shown for the first time the next time it gets focus.
1471 mHasHadWindowFocus = false;
1472 }
1473 }
1474
Alan Viverette7dbc3bf2015-01-28 16:14:36 -08001475 // Non-visible windows can't hold accessibility focus.
1476 if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1477 host.clearAccessibilityFocus();
1478 }
1479
Chet Haaseb78c2842012-04-19 13:39:50 -07001480 // Execute enqueued actions on every traversal in case a detached view enqueued an action
Chris Craikd36a81f2014-07-17 10:16:51 -07001481 getRunQueue().executeActions(mAttachInfo.mHandler);
Chet Haaseb78c2842012-04-19 13:39:50 -07001482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 boolean insetsChanged = false;
Romain Guy8506ab42009-06-11 17:35:47 -07001484
Craig Mautner72d6f212015-02-19 16:33:09 -08001485 boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001486 if (layoutRequested) {
Romain Guy15df6702009-08-17 20:17:30 -07001487
Dianne Hackborn711e62a2010-11-29 16:38:22 -08001488 final Resources res = mView.getContext().getResources();
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 if (mFirst) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 // make sure touch mode code executes by setting cached value
1492 // to opposite of the added touch mode.
1493 mAttachInfo.mInTouchMode = !mAddedTouchMode;
Romain Guy2d4cff62010-04-09 15:39:00 -07001494 ensureTouchModeLocally(mAddedTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 } else {
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001496 if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1497 insetsChanged = true;
1498 }
Dianne Hackbornfa6b35b2011-08-24 17:03:54 -07001499 if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 insetsChanged = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
Adrian Roosfa104232014-06-20 16:10:14 -07001502 if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) {
1503 insetsChanged = true;
1504 }
Dianne Hackbornfa6b35b2011-08-24 17:03:54 -07001505 if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001507 if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 + mAttachInfo.mVisibleInsets);
1509 }
Filip Gruszczynski2217f612015-05-26 11:32:08 -07001510 if (!mPendingOutsets.equals(mAttachInfo.mOutsets)) {
1511 insetsChanged = true;
1512 }
Chong Zhangf6525ce2016-01-14 17:09:56 -08001513 if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1514 || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
Dianne Hackborn711e62a2010-11-29 16:38:22 -08001515 windowSizeMayChange = true;
Chong Zhangf6525ce2016-01-14 17:09:56 -08001516
1517 if (shouldUseDisplaySize(lp)) {
1518 // NOTE -- system code, won't try to do compat mode.
1519 Point size = new Point();
1520 mDisplay.getRealSize(size);
1521 desiredWindowWidth = size.x;
1522 desiredWindowHeight = size.y;
1523 } else {
1524 Configuration config = res.getConfiguration();
1525 desiredWindowWidth = dipToPx(config.screenWidthDp);
1526 desiredWindowHeight = dipToPx(config.screenHeightDp);
1527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529 }
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 // Ask host how big it wants to be
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001532 windowSizeMayChange |= measureHierarchy(host, lp, res,
1533 desiredWindowWidth, desiredWindowHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001536 if (collectViewAttributes()) {
1537 params = lp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
Chris Craikd36a81f2014-07-17 10:16:51 -07001539 if (mAttachInfo.mForceReportNewAttributes) {
1540 mAttachInfo.mForceReportNewAttributes = false;
Dianne Hackborn9a230e02011-10-06 11:51:27 -07001541 params = lp;
1542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543
Chris Craikd36a81f2014-07-17 10:16:51 -07001544 if (mFirst || mAttachInfo.mViewVisibilityChanged) {
1545 mAttachInfo.mViewVisibilityChanged = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 int resizeMode = mSoftInputMode &
1547 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1548 // If we are in auto resize mode, then we need to determine
1549 // what mode to use now.
1550 if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
Chris Craikd36a81f2014-07-17 10:16:51 -07001551 final int N = mAttachInfo.mScrollContainers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 for (int i=0; i<N; i++) {
Chris Craikd36a81f2014-07-17 10:16:51 -07001553 if (mAttachInfo.mScrollContainers.get(i).isShown()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1555 }
1556 }
1557 if (resizeMode == 0) {
1558 resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1559 }
1560 if ((lp.softInputMode &
1561 WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1562 lp.softInputMode = (lp.softInputMode &
1563 ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1564 resizeMode;
1565 params = lp;
1566 }
1567 }
1568 }
Romain Guy8506ab42009-06-11 17:35:47 -07001569
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001570 if (params != null) {
1571 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1572 if (!PixelFormat.formatHasAlpha(params.format)) {
1573 params.format = PixelFormat.TRANSLUCENT;
1574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001576 mAttachInfo.mOverscanRequested = (params.flags
1577 & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579
Adrian Roosfa104232014-06-20 16:10:14 -07001580 if (mApplyInsetsRequested) {
1581 mApplyInsetsRequested = false;
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001582 mLastOverscanRequested = mAttachInfo.mOverscanRequested;
Adam Powell2accbf92014-04-16 23:14:57 +00001583 dispatchApplyInsets(host);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001584 if (mLayoutRequested) {
1585 // Short-circuit catching a new layout request here, so
1586 // we don't need to go through two layout passes when things
1587 // change due to fitting system windows, which can happen a lot.
1588 windowSizeMayChange |= measureHierarchy(host, lp,
1589 mView.getContext().getResources(),
1590 desiredWindowWidth, desiredWindowHeight);
1591 }
1592 }
1593
1594 if (layoutRequested) {
1595 // Clear this now, so that if anything requests a layout in the
1596 // rest of this function we will catch it and re-run a full
1597 // layout pass.
1598 mLayoutRequested = false;
1599 }
1600
1601 boolean windowShouldResize = layoutRequested && windowSizeMayChange
Dianne Hackborn189ee182010-12-02 21:48:53 -08001602 && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
Romain Guy2e4f4262010-04-06 11:07:52 -07001603 || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1604 frame.width() < desiredWindowWidth && frame.width() != mWidth)
1605 || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1606 frame.height() < desiredWindowHeight && frame.height() != mHeight));
Jorim Jaggi4846ee32016-01-07 17:39:12 +01001607 windowShouldResize |= mDragResizing && mResizeMode == RESIZE_MODE_FREEFORM;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608
Jorim Jaggi4846ee32016-01-07 17:39:12 +01001609 // If the activity was just relaunched, it might have unfrozen the task bounds (while
1610 // relaunching), so we need to force a call into window manager to pick up the latest
1611 // bounds.
1612 windowShouldResize |= mActivityRelaunched;
1613
Jeff Brown2e05ec32013-09-30 15:57:43 -07001614 // Determine whether to compute insets.
1615 // If there are no inset listeners remaining then we may still need to compute
1616 // insets in case the old insets were non-empty and must be reset.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 final boolean computesInternalInsets =
Chris Craikd36a81f2014-07-17 10:16:51 -07001618 mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners()
1619 || mAttachInfo.mHasNonEmptyGivenInternalInsets;
Romain Guy812ccbe2010-06-01 14:07:24 -07001620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 boolean insetsPending = false;
1622 int relayoutResult = 0;
Romain Guy812ccbe2010-06-01 14:07:24 -07001623
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -08001624 final boolean isViewVisible = viewVisibility == View.VISIBLE;
Romain Guy812ccbe2010-06-01 14:07:24 -07001625 if (mFirst || windowShouldResize || insetsChanged ||
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08001626 viewVisibilityChanged || params != null || mForceNextWindowRelayout) {
1627 mForceNextWindowRelayout = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628
Alan Viverette64bf97a2015-09-18 16:42:00 -04001629 if (isViewVisible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 // If this window is giving internal insets to the window
1631 // manager, and it is being added or changing its visibility,
1632 // then we want to first give the window manager "fake"
1633 // insets to cause it to effectively ignore the content of
1634 // the window during layout. This avoids it briefly causing
1635 // other windows to resize/move based on the raw frame of the
1636 // window, waiting until we can finish laying out this window
1637 // and get back to the window manager with the ultimately
1638 // computed insets.
Romain Guy812ccbe2010-06-01 14:07:24 -07001639 insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001642 if (mSurfaceHolder != null) {
1643 mSurfaceHolder.mSurfaceLock.lock();
1644 mDrawingAllowed = true;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001645 }
Romain Guy812ccbe2010-06-01 14:07:24 -07001646
Romain Guyc361da82010-10-25 15:29:10 -07001647 boolean hwInitialized = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 boolean contentInsetsChanged = false;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001649 boolean hadSurface = mSurface.isValid();
Romain Guy812ccbe2010-06-01 14:07:24 -07001650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 try {
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001652 if (DEBUG_LAYOUT) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001653 Log.i(mTag, "host=w:" + host.getMeasuredWidth() + ", h:" +
Dianne Hackborn189ee182010-12-02 21:48:53 -08001654 host.getMeasuredHeight() + ", params=" + params);
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001655 }
Romain Guy2a83f002011-01-18 18:28:21 -08001656
John Reckf7d9c1d2014-04-09 10:01:03 -07001657 if (mAttachInfo.mHardwareRenderer != null) {
1658 // relayoutWindow may decide to destroy mSurface. As that decision
1659 // happens in WindowManager service, we need to be defensive here
1660 // and stop using the surface in case it gets destroyed.
John Reck01a5ea32014-12-03 13:01:07 -08001661 if (mAttachInfo.mHardwareRenderer.pauseSurface(mSurface)) {
1662 // Animations were running so we need to push a frame
1663 // to resume them
1664 mDirty.set(0, 0, mWidth, mHeight);
1665 }
John Reckba6adf62015-02-19 14:36:50 -08001666 mChoreographer.mFrameInfo.addFlags(FrameInfo.FLAG_WINDOW_LAYOUT_CHANGED);
John Reckf7d9c1d2014-04-09 10:01:03 -07001667 }
Romain Guy2a83f002011-01-18 18:28:21 -08001668 final int surfaceGenerationId = mSurface.getGenerationId();
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07001669 relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1670
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001671 if (DEBUG_LAYOUT) Log.v(mTag, "relayout: frame=" + frame.toShortString()
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001672 + " overscan=" + mPendingOverscanInsets.toShortString()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 + " content=" + mPendingContentInsets.toShortString()
1674 + " visible=" + mPendingVisibleInsets.toShortString()
Adrian Roosfa104232014-06-20 16:10:14 -07001675 + " visible=" + mPendingStableInsets.toShortString()
Filip Gruszczynski0ec13282015-06-25 11:26:01 -07001676 + " outsets=" + mPendingOutsets.toShortString()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 + " surface=" + mSurface);
Romain Guy8506ab42009-06-11 17:35:47 -07001678
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001679 if (mPendingConfiguration.seq != 0) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001680 if (DEBUG_CONFIGURATION) Log.v(mTag, "Visible with new config: "
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001681 + mPendingConfiguration);
riddle_hsu164725c2015-11-12 14:07:12 +08001682 updateConfiguration(new Configuration(mPendingConfiguration), !mFirst);
Dianne Hackborn694f79b2010-03-17 19:44:59 -07001683 mPendingConfiguration.seq = 0;
1684 }
Dianne Hackborn3556c9a2012-05-04 16:31:25 -07001685
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001686 final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals(
1687 mAttachInfo.mOverscanInsets);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 contentInsetsChanged = !mPendingContentInsets.equals(
1689 mAttachInfo.mContentInsets);
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001690 final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 mAttachInfo.mVisibleInsets);
Adrian Roosfa104232014-06-20 16:10:14 -07001692 final boolean stableInsetsChanged = !mPendingStableInsets.equals(
1693 mAttachInfo.mStableInsets);
Filip Gruszczynski2217f612015-05-26 11:32:08 -07001694 final boolean outsetsChanged = !mPendingOutsets.equals(mAttachInfo.mOutsets);
Chong Zhangf4abc2b2015-11-12 23:40:58 -08001695 final boolean surfaceSizeChanged = (relayoutResult
1696 & WindowManagerGlobal.RELAYOUT_RES_SURFACE_RESIZED) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (contentInsetsChanged) {
1698 mAttachInfo.mContentInsets.set(mPendingContentInsets);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001699 if (DEBUG_LAYOUT) Log.v(mTag, "Content insets changing to: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 + mAttachInfo.mContentInsets);
1701 }
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001702 if (overscanInsetsChanged) {
1703 mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001704 if (DEBUG_LAYOUT) Log.v(mTag, "Overscan insets changing to: "
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001705 + mAttachInfo.mOverscanInsets);
1706 // Need to relayout with content insets.
1707 contentInsetsChanged = true;
1708 }
Adrian Roosfa104232014-06-20 16:10:14 -07001709 if (stableInsetsChanged) {
1710 mAttachInfo.mStableInsets.set(mPendingStableInsets);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001711 if (DEBUG_LAYOUT) Log.v(mTag, "Decor insets changing to: "
Adrian Roosfa104232014-06-20 16:10:14 -07001712 + mAttachInfo.mStableInsets);
1713 // Need to relayout with content insets.
1714 contentInsetsChanged = true;
1715 }
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001716 if (contentInsetsChanged || mLastSystemUiVisibility !=
Adrian Roosfa104232014-06-20 16:10:14 -07001717 mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested
Filip Gruszczynski2217f612015-05-26 11:32:08 -07001718 || mLastOverscanRequested != mAttachInfo.mOverscanRequested
1719 || outsetsChanged) {
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001720 mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
Dianne Hackbornc4aad012013-02-22 15:05:25 -08001721 mLastOverscanRequested = mAttachInfo.mOverscanRequested;
Filip Gruszczynski2217f612015-05-26 11:32:08 -07001722 mAttachInfo.mOutsets.set(mPendingOutsets);
Adrian Roosfa104232014-06-20 16:10:14 -07001723 mApplyInsetsRequested = false;
Adam Powell2accbf92014-04-16 23:14:57 +00001724 dispatchApplyInsets(host);
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (visibleInsetsChanged) {
1727 mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001728 if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 + mAttachInfo.mVisibleInsets);
1730 }
1731
1732 if (!hadSurface) {
1733 if (mSurface.isValid()) {
1734 // If we are creating a new surface, then we need to
1735 // completely redraw it. Also, when we get to the
1736 // point of drawing it we will hold off and schedule
1737 // a new traversal instead. This is so we can tell the
1738 // window manager about all of the windows being displayed
1739 // before actually drawing them, so it can display then
1740 // all at once.
1741 newSurface = true;
Jeff Brown96e942d2011-11-30 19:55:01 -08001742 mFullRedrawNeeded = true;
Jack Palevich61a6e682009-10-09 17:37:50 -07001743 mPreviousTransparentRegion.setEmpty();
Romain Guy8506ab42009-06-11 17:35:47 -07001744
John Reck63005e62015-05-19 15:00:13 -07001745 // Only initialize up-front if transparent regions are not
1746 // requested, otherwise defer to see if the entire window
1747 // will be transparent
Romain Guyb051e892010-09-28 19:09:36 -07001748 if (mAttachInfo.mHardwareRenderer != null) {
Dianne Hackborn64825172011-03-02 21:32:58 -08001749 try {
Romain Guy786fc932012-07-24 16:24:56 -07001750 hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
John Reck79d81e62013-11-05 13:26:57 -08001751 mSurface);
John Reck63005e62015-05-19 15:00:13 -07001752 if (hwInitialized && (host.mPrivateFlags
1753 & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) {
1754 // Don't pre-allocate if transparent regions
1755 // are requested as they may not be needed
1756 mSurface.allocateBuffers();
1757 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07001758 } catch (OutOfResourcesException e) {
Romain Guy3696779b2013-01-28 14:04:07 -08001759 handleOutOfResourcesException(e);
Dianne Hackborn64825172011-03-02 21:32:58 -08001760 return;
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763 }
1764 } else if (!mSurface.isValid()) {
1765 // If the surface has been removed, then reset the scroll
1766 // positions.
Svetoslav Ganov149567f2013-01-08 15:23:34 -08001767 if (mLastScrolledFocus != null) {
1768 mLastScrolledFocus.clear();
1769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 mScrollY = mCurScrollY = 0;
Adrian Roos0e7ae4e2014-10-01 15:33:22 +02001771 if (mView instanceof RootViewSurfaceTaker) {
1772 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
1773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 if (mScroller != null) {
1775 mScroller.abortAnimation();
1776 }
Romain Guy1d0c7082011-08-03 16:22:24 -07001777 // Our surface is gone
1778 if (mAttachInfo.mHardwareRenderer != null &&
1779 mAttachInfo.mHardwareRenderer.isEnabled()) {
John Reckf47a5942014-06-30 16:20:04 -07001780 mAttachInfo.mHardwareRenderer.destroy();
Romain Guy1d0c7082011-08-03 16:22:24 -07001781 }
Chong Zhangf4abc2b2015-11-12 23:40:58 -08001782 } else if ((surfaceGenerationId != mSurface.getGenerationId()
1783 || surfaceSizeChanged)
1784 && mSurfaceHolder == null
1785 && mAttachInfo.mHardwareRenderer != null) {
Jeff Brown96e942d2011-11-30 19:55:01 -08001786 mFullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08001787 try {
Chong Zhangf4abc2b2015-11-12 23:40:58 -08001788 // Need to do updateSurface (which leads to CanvasContext::setSurface and
1789 // re-create the EGLSurface) if either the Surface changed (as indicated by
1790 // generation id), or WindowManager changed the surface size. The latter is
1791 // because on some chips, changing the consumer side's BufferQueue size may
1792 // not take effect immediately unless we create a new EGLSurface.
1793 // Note that frame size change doesn't always imply surface size change (eg.
1794 // drag resizing uses fullscreen surface), need to check surfaceSizeChanged
1795 // flag from WindowManager.
John Reck79d81e62013-11-05 13:26:57 -08001796 mAttachInfo.mHardwareRenderer.updateSurface(mSurface);
Igor Murashkina86ab6402013-08-30 12:58:36 -07001797 } catch (OutOfResourcesException e) {
Romain Guy3696779b2013-01-28 14:04:07 -08001798 handleOutOfResourcesException(e);
Dianne Hackborn64825172011-03-02 21:32:58 -08001799 return;
1800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
Chong Zhang0275e392015-09-17 10:41:44 -07001802
Jorim Jaggi4846ee32016-01-07 17:39:12 +01001803 final boolean freeformResizing = (relayoutResult
1804 & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_FREEFORM) != 0;
1805 final boolean dockedResizing = (relayoutResult
1806 & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_DOCKED) != 0;
1807 final boolean dragResizing = freeformResizing || dockedResizing;
Chong Zhang0275e392015-09-17 10:41:44 -07001808 if (mDragResizing != dragResizing) {
Skuhneb8160872015-09-22 09:51:39 -07001809 if (dragResizing) {
Jorim Jaggi9511b0f2016-01-29 19:12:44 -08001810 startDragResizing(mPendingBackDropFrame,
1811 mWinFrame.equals(mPendingBackDropFrame), mPendingVisibleInsets,
1812 mPendingStableInsets);
Jorim Jaggi4846ee32016-01-07 17:39:12 +01001813 mResizeMode = freeformResizing
1814 ? RESIZE_MODE_FREEFORM
1815 : RESIZE_MODE_DOCKED_DIVIDER;
Skuhneb8160872015-09-22 09:51:39 -07001816 } else {
1817 // We shouldn't come here, but if we come we should end the resize.
1818 endDragResizing();
1819 }
Chong Zhang0275e392015-09-17 10:41:44 -07001820 }
Skuhneb8160872015-09-22 09:51:39 -07001821 if (!USE_MT_RENDERER) {
1822 if (dragResizing) {
1823 mCanvasOffsetX = mWinFrame.left;
1824 mCanvasOffsetY = mWinFrame.top;
1825 } else {
1826 mCanvasOffsetX = mCanvasOffsetY = 0;
1827 }
Chong Zhang0275e392015-09-17 10:41:44 -07001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 } catch (RemoteException e) {
1830 }
Romain Guy1d0c7082011-08-03 16:22:24 -07001831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 if (DEBUG_ORIENTATION) Log.v(
Jeff Brownc5ed5912010-07-14 18:48:53 -07001833 TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834
Chris Craikd36a81f2014-07-17 10:16:51 -07001835 mAttachInfo.mWindowLeft = frame.left;
1836 mAttachInfo.mWindowTop = frame.top;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837
1838 // !!FIXME!! This next section handles the case where we did not get the
1839 // window size we asked for. We should avoid this by getting a maximum size from
1840 // the window session beforehand.
Dianne Hackborn3556c9a2012-05-04 16:31:25 -07001841 if (mWidth != frame.width() || mHeight != frame.height()) {
Dianne Hackborn3556c9a2012-05-04 16:31:25 -07001842 mWidth = frame.width();
1843 mHeight = frame.height();
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001846 if (mSurfaceHolder != null) {
1847 // The app owns the surface; tell it about what is going on.
1848 if (mSurface.isValid()) {
1849 // XXX .copyFrom() doesn't work!
1850 //mSurfaceHolder.mSurface.copyFrom(mSurface);
1851 mSurfaceHolder.mSurface = mSurface;
1852 }
Jeff Brown30bc34f2011-01-25 12:56:56 -08001853 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001854 mSurfaceHolder.mSurfaceLock.unlock();
1855 if (mSurface.isValid()) {
1856 if (!hadSurface) {
1857 mSurfaceHolder.ungetCallbacks();
1858
1859 mIsCreating = true;
1860 mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1861 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1862 if (callbacks != null) {
1863 for (SurfaceHolder.Callback c : callbacks) {
1864 c.surfaceCreated(mSurfaceHolder);
1865 }
1866 }
1867 surfaceChanged = true;
1868 }
1869 if (surfaceChanged) {
1870 mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1871 lp.format, mWidth, mHeight);
1872 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1873 if (callbacks != null) {
1874 for (SurfaceHolder.Callback c : callbacks) {
1875 c.surfaceChanged(mSurfaceHolder, lp.format,
1876 mWidth, mHeight);
1877 }
1878 }
1879 }
1880 mIsCreating = false;
1881 } else if (hadSurface) {
1882 mSurfaceHolder.ungetCallbacks();
1883 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1884 mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1885 if (callbacks != null) {
1886 for (SurfaceHolder.Callback c : callbacks) {
1887 c.surfaceDestroyed(mSurfaceHolder);
1888 }
1889 }
1890 mSurfaceHolder.mSurfaceLock.lock();
Jozef BABJAK93c5b6a2011-02-22 09:33:19 +01001891 try {
1892 mSurfaceHolder.mSurface = new Surface();
1893 } finally {
1894 mSurfaceHolder.mSurfaceLock.unlock();
1895 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07001896 }
1897 }
Romain Guy53389bd2010-09-07 17:16:32 -07001898
John Reck51aaf902015-12-02 15:08:07 -08001899 final ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
Alan Viverette50210d92015-05-14 18:05:36 -07001900 if (hardwareRenderer != null && hardwareRenderer.isEnabled()) {
1901 if (hwInitialized
1902 || mWidth != hardwareRenderer.getWidth()
1903 || mHeight != hardwareRenderer.getHeight()) {
1904 hardwareRenderer.setup(mWidth, mHeight, mAttachInfo,
1905 mWindowAttributes.surfaceInsets);
Romain Guy03985752011-07-11 15:33:51 -07001906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908
Craig Mautner72d6f212015-02-19 16:33:09 -08001909 if (!mStopped || mReportNextDraw) {
Dianne Hackbornce418e62011-03-01 14:31:38 -08001910 boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
Jeff Brown98365d72012-08-19 20:30:52 -07001911 (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
Dianne Hackbornce418e62011-03-01 14:31:38 -08001912 if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1913 || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001914 int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1915 int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
Igor Murashkina86ab6402013-08-30 12:58:36 -07001916
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001917 if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed! mWidth="
Dianne Hackbornce418e62011-03-01 14:31:38 -08001918 + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1919 + " mHeight=" + mHeight
1920 + " measuredHeight=" + host.getMeasuredHeight()
1921 + " coveredInsetsChanged=" + contentInsetsChanged);
Igor Murashkina86ab6402013-08-30 12:58:36 -07001922
Dianne Hackbornce418e62011-03-01 14:31:38 -08001923 // Ask host how big it wants to be
Jeff Brownc8d2668b2012-05-16 17:23:59 -07001924 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
Igor Murashkina86ab6402013-08-30 12:58:36 -07001925
Dianne Hackbornce418e62011-03-01 14:31:38 -08001926 // Implementation of weights from WindowManager.LayoutParams
1927 // We just grow the dimensions as needed and re-measure if
1928 // needs be
1929 int width = host.getMeasuredWidth();
1930 int height = host.getMeasuredHeight();
1931 boolean measureAgain = false;
Igor Murashkina86ab6402013-08-30 12:58:36 -07001932
Dianne Hackbornce418e62011-03-01 14:31:38 -08001933 if (lp.horizontalWeight > 0.0f) {
1934 width += (int) ((mWidth - width) * lp.horizontalWeight);
1935 childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1936 MeasureSpec.EXACTLY);
1937 measureAgain = true;
1938 }
1939 if (lp.verticalWeight > 0.0f) {
1940 height += (int) ((mHeight - height) * lp.verticalWeight);
1941 childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1942 MeasureSpec.EXACTLY);
1943 measureAgain = true;
1944 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07001945
Dianne Hackbornce418e62011-03-01 14:31:38 -08001946 if (measureAgain) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08001947 if (DEBUG_LAYOUT) Log.v(mTag,
Dianne Hackbornce418e62011-03-01 14:31:38 -08001948 "And hey let's measure once more: width=" + width
1949 + " height=" + height);
Jeff Brownc8d2668b2012-05-16 17:23:59 -07001950 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
Dianne Hackbornce418e62011-03-01 14:31:38 -08001951 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07001952
Dianne Hackborn3a3a6cf2012-03-26 10:24:04 -07001953 layoutRequested = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001956 } else {
1957 // Not the first pass and no window/insets/visibility change but the window
1958 // may have moved and we need check that and if so to update the left and right
1959 // in the attach info. We translate only the window frame since on window move
1960 // the window manager tells us only for the new frame but the insets are the
1961 // same and we do not want to translate them more than once.
Jorim Jaggi2e95a482016-01-14 17:36:55 -08001962 maybeHandleWindowMove(frame);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
1964
Craig Mautner72d6f212015-02-19 16:33:09 -08001965 final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 boolean triggerGlobalLayoutListener = didLayout
Chris Craikd36a81f2014-07-17 10:16:51 -07001967 || mAttachInfo.mRecomputeGlobalAttributes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 if (didLayout) {
Chet Haase3efa7b52012-12-03 08:33:17 -08001969 performLayout(lp, desiredWindowWidth, desiredWindowHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970
Mathias Agopian54e3d3842013-04-12 15:13:12 -07001971 // By this point all views have been sized and positioned
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 // We can compute the transparent area
1973
Dianne Hackborn4702a852012-08-17 15:18:29 -07001974 if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 // start out transparent
1976 // TODO: AVOID THAT CALL BY CACHING THE RESULT?
1977 host.getLocationInWindow(mTmpLocation);
1978 mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
1979 mTmpLocation[0] + host.mRight - host.mLeft,
1980 mTmpLocation[1] + host.mBottom - host.mTop);
1981
1982 host.gatherTransparentRegion(mTransparentRegion);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001983 if (mTranslator != null) {
1984 mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
1985 }
1986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
1988 mPreviousTransparentRegion.set(mTransparentRegion);
Mathias Agopian54e3d3842013-04-12 15:13:12 -07001989 mFullRedrawNeeded = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 // reconfigure window manager
1991 try {
Jeff Brown98365d72012-08-19 20:30:52 -07001992 mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 } catch (RemoteException e) {
1994 }
1995 }
1996 }
1997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 if (DBG) {
1999 System.out.println("======================================");
Chet Haase4610eef2015-12-03 07:38:11 -08002000 System.out.println("performTraversals -- after setFrame");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 host.debug();
2002 }
2003 }
2004
2005 if (triggerGlobalLayoutListener) {
Chris Craikd36a81f2014-07-17 10:16:51 -07002006 mAttachInfo.mRecomputeGlobalAttributes = false;
2007 mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
2009
2010 if (computesInternalInsets) {
Jeff Brownfbf09772011-01-16 14:06:57 -08002011 // Clear the original insets.
Chris Craikd36a81f2014-07-17 10:16:51 -07002012 final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
Jeff Brownfbf09772011-01-16 14:06:57 -08002013 insets.reset();
2014
2015 // Compute new insets in place.
Chris Craikd36a81f2014-07-17 10:16:51 -07002016 mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
2017 mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
Jeff Brownfbf09772011-01-16 14:06:57 -08002018
2019 // Tell the window manager.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 if (insetsPending || !mLastGivenInsets.equals(insets)) {
2021 mLastGivenInsets.set(insets);
Jeff Brownfbf09772011-01-16 14:06:57 -08002022
2023 // Translate insets to screen coordinates if needed.
2024 final Rect contentInsets;
2025 final Rect visibleInsets;
2026 final Region touchableRegion;
2027 if (mTranslator != null) {
2028 contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
2029 visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
2030 touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
2031 } else {
2032 contentInsets = insets.contentInsets;
2033 visibleInsets = insets.visibleInsets;
2034 touchableRegion = insets.touchableRegion;
2035 }
2036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 try {
Jeff Brown98365d72012-08-19 20:30:52 -07002038 mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
Jeff Brownfbf09772011-01-16 14:06:57 -08002039 contentInsets, visibleInsets, touchableRegion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 } catch (RemoteException e) {
2041 }
2042 }
2043 }
Romain Guy8506ab42009-06-11 17:35:47 -07002044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 if (mFirst) {
2046 // handle first focus request
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002047 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: mView.hasFocus()="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 + mView.hasFocus());
2049 if (mView != null) {
2050 if (!mView.hasFocus()) {
2051 mView.requestFocus(View.FOCUS_FORWARD);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002052 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: requested focused view="
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002053 + mView.findFocus());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 } else {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002055 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: existing focused view="
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002056 + mView.findFocus());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058 }
2059 }
2060
Alan Viverette64bf97a2015-09-18 16:42:00 -04002061 final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible;
2062 final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible;
2063 final boolean regainedFocus = hasWindowFocus && mLostWindowFocus;
2064 if (regainedFocus) {
2065 mLostWindowFocus = false;
2066 } else if (!hasWindowFocus && mHadWindowFocus) {
2067 mLostWindowFocus = true;
2068 }
2069
2070 if (changedVisibility || regainedFocus) {
2071 host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2072 }
2073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 mFirst = false;
2075 mWillDrawSoon = false;
2076 mNewSurfaceNeeded = false;
Jorim Jaggi4846ee32016-01-07 17:39:12 +01002077 mActivityRelaunched = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 mViewVisibility = viewVisibility;
Alan Viverette64bf97a2015-09-18 16:42:00 -04002079 mHadWindowFocus = hasWindowFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080
Alan Viverette64bf97a2015-09-18 16:42:00 -04002081 if (hasWindowFocus && !isInLocalFocusMode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 final boolean imTarget = WindowManager.LayoutParams
2083 .mayUseInputMethod(mWindowAttributes.flags);
2084 if (imTarget != mLastWasImTarget) {
2085 mLastWasImTarget = imTarget;
2086 InputMethodManager imm = InputMethodManager.peekInstance();
2087 if (imm != null && imTarget) {
Alan Viverette64bf97a2015-09-18 16:42:00 -04002088 imm.onPreWindowFocus(mView, hasWindowFocus);
Yohei Yukawa5f059652015-05-14 22:16:41 -07002089 imm.onPostWindowFocus(mView, mView.findFocus(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 mWindowAttributes.softInputMode,
2091 !mHasHadWindowFocus, mWindowAttributes.flags);
2092 }
2093 }
2094 }
Romain Guy8506ab42009-06-11 17:35:47 -07002095
Jeff Brown96e942d2011-11-30 19:55:01 -08002096 // Remember if we must report the next draw.
Jeff Brown98365d72012-08-19 20:30:52 -07002097 if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
Jeff Brown96e942d2011-11-30 19:55:01 -08002098 mReportNextDraw = true;
2099 }
2100
Alan Viverette64bf97a2015-09-18 16:42:00 -04002101 boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102
Jorim Jaggi3127c2a42016-01-26 18:48:44 -08002103 if (!cancelDraw) {
Chet Haase9c450412015-10-01 13:25:58 -07002104 if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2105 for (int i = 0; i < mPendingTransitions.size(); ++i) {
2106 mPendingTransitions.get(i).startChangingAnimations();
Chet Haased56c6952011-09-07 08:46:23 -07002107 }
Chet Haase9c450412015-10-01 13:25:58 -07002108 mPendingTransitions.clear();
Chet Haased56c6952011-09-07 08:46:23 -07002109 }
Chet Haase9c450412015-10-01 13:25:58 -07002110
2111 performDraw();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 } else {
Alan Viverette64bf97a2015-09-18 16:42:00 -04002113 if (isViewVisible) {
Chris Wren78cb7cf2012-05-15 12:36:44 -04002114 // Try again
2115 scheduleTraversals();
2116 } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
Chet Haased56c6952011-09-07 08:46:23 -07002117 for (int i = 0; i < mPendingTransitions.size(); ++i) {
2118 mPendingTransitions.get(i).endChangingAnimations();
2119 }
2120 mPendingTransitions.clear();
2121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
Craig Mautnerdf2390a2012-08-29 20:59:22 -07002123
2124 mIsInTraversal = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
2126
Jorim Jaggi2e95a482016-01-14 17:36:55 -08002127 private void maybeHandleWindowMove(Rect frame) {
2128
2129 // TODO: Well, we are checking whether the frame has changed similarly
2130 // to how this is done for the insets. This is however incorrect since
2131 // the insets and the frame are translated. For example, the old frame
2132 // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
2133 // reported frame is (2, 2 - 2, 2) which implies no change but this is not
2134 // true since we are comparing a not translated value to a translated one.
2135 // This scenario is rare but we may want to fix that.
2136
2137 final boolean windowMoved = mAttachInfo.mWindowLeft != frame.left
2138 || mAttachInfo.mWindowTop != frame.top;
2139 if (windowMoved) {
2140 if (mTranslator != null) {
2141 mTranslator.translateRectInScreenToAppWinFrame(frame);
2142 }
2143 mAttachInfo.mWindowLeft = frame.left;
2144 mAttachInfo.mWindowTop = frame.top;
2145
2146 // Update the light position for the new window offsets.
2147 if (mAttachInfo.mHardwareRenderer != null) {
2148 mAttachInfo.mHardwareRenderer.setLightCenter(mAttachInfo);
2149 }
2150 }
2151 }
Jorim Jaggi3127c2a42016-01-26 18:48:44 -08002152
Romain Guy3696779b2013-01-28 14:04:07 -08002153 private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002154 Log.e(mTag, "OutOfResourcesException initializing HW surface", e);
Romain Guy3696779b2013-01-28 14:04:07 -08002155 try {
2156 if (!mWindowSession.outOfMemory(mWindow) &&
2157 Process.myUid() != Process.SYSTEM_UID) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002158 Slog.w(mTag, "No processes killed for memory; killing self");
Romain Guy3696779b2013-01-28 14:04:07 -08002159 Process.killProcess(Process.myPid());
2160 }
2161 } catch (RemoteException ex) {
2162 }
2163 mLayoutRequested = true; // ask wm for a new surface next time.
2164 }
2165
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002166 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2167 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2168 try {
2169 mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2170 } finally {
2171 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2172 }
2173 }
2174
Chet Haase97140572012-09-13 14:56:47 -07002175 /**
2176 * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2177 * is currently undergoing a layout pass.
2178 *
2179 * @return whether the view hierarchy is currently undergoing a layout pass
2180 */
2181 boolean isInLayout() {
2182 return mInLayout;
2183 }
2184
2185 /**
Chet Haasecc699b42012-12-13 09:06:55 -08002186 * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
2187 * undergoing a layout pass. requestLayout() should not generally be called during layout,
2188 * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
2189 * all children in that container hierarchy are measured and laid out at the end of the layout
2190 * pass for that container). If requestLayout() is called anyway, we handle it correctly
2191 * by registering all requesters during a frame as it proceeds. At the end of the frame,
2192 * we check all of those views to see if any still have pending layout requests, which
2193 * indicates that they were not correctly handled by their container hierarchy. If that is
2194 * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
2195 * to blank containers, and force a second request/measure/layout pass in this frame. If
Chet Haase97140572012-09-13 14:56:47 -07002196 * more requestLayout() calls are received during that second layout pass, we post those
Chet Haasecc699b42012-12-13 09:06:55 -08002197 * requests to the next frame to avoid possible infinite loops.
2198 *
2199 * <p>The return value from this method indicates whether the request should proceed
2200 * (if it is a request during the first layout pass) or should be skipped and posted to the
2201 * next frame (if it is a request during the second layout pass).</p>
Chet Haase97140572012-09-13 14:56:47 -07002202 *
2203 * @param view the view that requested the layout.
Chet Haasecc699b42012-12-13 09:06:55 -08002204 *
2205 * @return true if request should proceed, false otherwise.
Chet Haase97140572012-09-13 14:56:47 -07002206 */
Chet Haasecc699b42012-12-13 09:06:55 -08002207 boolean requestLayoutDuringLayout(final View view) {
2208 if (view.mParent == null || view.mAttachInfo == null) {
2209 // Would not normally trigger another layout, so just let it pass through as usual
2210 return true;
2211 }
Chet Haase107a4822013-03-13 06:46:50 -07002212 if (!mLayoutRequesters.contains(view)) {
2213 mLayoutRequesters.add(view);
2214 }
Chet Haase97140572012-09-13 14:56:47 -07002215 if (!mHandlingLayoutInLayoutRequest) {
Chet Haase107a4822013-03-13 06:46:50 -07002216 // Let the request proceed normally; it will be processed in a second layout pass
2217 // if necessary
Chet Haasecc699b42012-12-13 09:06:55 -08002218 return true;
Chet Haase97140572012-09-13 14:56:47 -07002219 } else {
Chet Haase107a4822013-03-13 06:46:50 -07002220 // Don't let the request proceed during the second layout pass.
2221 // It will post to the next frame instead.
Chet Haasecc699b42012-12-13 09:06:55 -08002222 return false;
Chet Haase97140572012-09-13 14:56:47 -07002223 }
2224 }
2225
Chet Haase3efa7b52012-12-03 08:33:17 -08002226 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2227 int desiredWindowHeight) {
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002228 mLayoutRequested = false;
2229 mScrollMayChange = true;
Chet Haase97140572012-09-13 14:56:47 -07002230 mInLayout = true;
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002231
2232 final View host = mView;
2233 if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002234 Log.v(mTag, "Laying out " + host + " to (" +
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002235 host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2236 }
2237
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002238 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2239 try {
2240 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
Chet Haasecc699b42012-12-13 09:06:55 -08002241
Chet Haased5a83522012-11-21 16:24:44 -08002242 mInLayout = false;
Chet Haase97140572012-09-13 14:56:47 -07002243 int numViewsRequestingLayout = mLayoutRequesters.size();
2244 if (numViewsRequestingLayout > 0) {
Chet Haasecc699b42012-12-13 09:06:55 -08002245 // requestLayout() was called during layout.
2246 // If no layout-request flags are set on the requesting views, there is no problem.
2247 // If some requests are still pending, then we need to clear those flags and do
2248 // a full request/measure/layout pass to handle this situation.
Chet Haase107a4822013-03-13 06:46:50 -07002249 ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
2250 false);
2251 if (validLayoutRequesters != null) {
2252 // Set this flag to indicate that any further requests are happening during
2253 // the second pass, which may result in posting those requests to the next
2254 // frame instead
Chet Haasecc699b42012-12-13 09:06:55 -08002255 mHandlingLayoutInLayoutRequest = true;
Chet Haase107a4822013-03-13 06:46:50 -07002256
2257 // Process fresh layout requests, then measure and layout
2258 int numValidRequests = validLayoutRequesters.size();
Chet Haasecc699b42012-12-13 09:06:55 -08002259 for (int i = 0; i < numValidRequests; ++i) {
Chet Haase107a4822013-03-13 06:46:50 -07002260 final View view = validLayoutRequesters.get(i);
2261 Log.w("View", "requestLayout() improperly called by " + view +
2262 " during layout: running second layout pass");
2263 view.requestLayout();
Chet Haasecc699b42012-12-13 09:06:55 -08002264 }
2265 measureHierarchy(host, lp, mView.getContext().getResources(),
2266 desiredWindowWidth, desiredWindowHeight);
2267 mInLayout = true;
2268 host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
Chet Haase107a4822013-03-13 06:46:50 -07002269
Chet Haasecc699b42012-12-13 09:06:55 -08002270 mHandlingLayoutInLayoutRequest = false;
Chet Haase107a4822013-03-13 06:46:50 -07002271
2272 // Check the valid requests again, this time without checking/clearing the
2273 // layout flags, since requests happening during the second pass get noop'd
2274 validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
2275 if (validLayoutRequesters != null) {
2276 final ArrayList<View> finalRequesters = validLayoutRequesters;
2277 // Post second-pass requests to the next frame
2278 getRunQueue().post(new Runnable() {
2279 @Override
2280 public void run() {
2281 int numValidRequests = finalRequesters.size();
2282 for (int i = 0; i < numValidRequests; ++i) {
2283 final View view = finalRequesters.get(i);
2284 Log.w("View", "requestLayout() improperly called by " + view +
2285 " during second layout pass: posting in next frame");
2286 view.requestLayout();
2287 }
2288 }
2289 });
2290 }
Chet Haasecc699b42012-12-13 09:06:55 -08002291 }
Chet Haase107a4822013-03-13 06:46:50 -07002292
Chet Haase97140572012-09-13 14:56:47 -07002293 }
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002294 } finally {
2295 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2296 }
Chet Haase97140572012-09-13 14:56:47 -07002297 mInLayout = false;
Jeff Brownc8d2668b2012-05-16 17:23:59 -07002298 }
2299
Chet Haase107a4822013-03-13 06:46:50 -07002300 /**
2301 * This method is called during layout when there have been calls to requestLayout() during
2302 * layout. It walks through the list of views that requested layout to determine which ones
2303 * still need it, based on visibility in the hierarchy and whether they have already been
2304 * handled (as is usually the case with ListView children).
2305 *
2306 * @param layoutRequesters The list of views that requested layout during layout
2307 * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
2308 * If so, the FORCE_LAYOUT flag was not set on requesters.
2309 * @return A list of the actual views that still need to be laid out.
2310 */
2311 private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2312 boolean secondLayoutRequests) {
2313
2314 int numViewsRequestingLayout = layoutRequesters.size();
2315 ArrayList<View> validLayoutRequesters = null;
2316 for (int i = 0; i < numViewsRequestingLayout; ++i) {
2317 View view = layoutRequesters.get(i);
2318 if (view != null && view.mAttachInfo != null && view.mParent != null &&
2319 (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
2320 View.PFLAG_FORCE_LAYOUT)) {
2321 boolean gone = false;
2322 View parent = view;
2323 // Only trigger new requests for views in a non-GONE hierarchy
2324 while (parent != null) {
2325 if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
2326 gone = true;
2327 break;
2328 }
2329 if (parent.mParent instanceof View) {
2330 parent = (View) parent.mParent;
2331 } else {
2332 parent = null;
2333 }
2334 }
2335 if (!gone) {
2336 if (validLayoutRequesters == null) {
2337 validLayoutRequesters = new ArrayList<View>();
2338 }
2339 validLayoutRequesters.add(view);
2340 }
2341 }
2342 }
2343 if (!secondLayoutRequests) {
2344 // If we're checking the layout flags, then we need to clean them up also
2345 for (int i = 0; i < numViewsRequestingLayout; ++i) {
2346 View view = layoutRequesters.get(i);
2347 while (view != null &&
2348 (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2349 view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2350 if (view.mParent instanceof View) {
2351 view = (View) view.mParent;
2352 } else {
2353 view = null;
2354 }
2355 }
2356 }
2357 }
2358 layoutRequesters.clear();
2359 return validLayoutRequesters;
2360 }
2361
Igor Murashkina86ab6402013-08-30 12:58:36 -07002362 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 public void requestTransparentRegion(View child) {
2364 // the test below should not fail unless someone is messing with us
2365 checkThread();
2366 if (mView == child) {
Dianne Hackborn4702a852012-08-17 15:18:29 -07002367 mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 // Need to make sure we re-evaluate the window attributes next
2369 // time around, to ensure the window has the correct format.
2370 mWindowAttributesChanged = true;
Romain Guyf21c9b02011-09-06 16:56:54 -07002371 mWindowAttributesChangesFlag = 0;
Mathias Agopian1bd80ad2010-11-04 17:13:39 -07002372 requestLayout();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 }
2374 }
2375
2376 /**
2377 * Figures out the measure spec for the root view in a window based on it's
2378 * layout params.
2379 *
2380 * @param windowSize
2381 * The available width or height of the window
2382 *
2383 * @param rootDimension
2384 * The layout params for one dimension (width or height) of the
2385 * window.
2386 *
2387 * @return The measure spec to use to measure the root view.
2388 */
Romain Guya998dff2012-03-23 18:58:36 -07002389 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 int measureSpec;
2391 switch (rootDimension) {
2392
Romain Guy980a9382010-01-08 15:06:28 -08002393 case ViewGroup.LayoutParams.MATCH_PARENT:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 // Window can't resize. Force root view to be windowSize.
2395 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2396 break;
2397 case ViewGroup.LayoutParams.WRAP_CONTENT:
2398 // Window can resize. Set max size for root view.
2399 measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2400 break;
2401 default:
2402 // Window wants to be an exact size. Force root view to be that size.
2403 measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2404 break;
2405 }
2406 return measureSpec;
2407 }
2408
Alan Viveretteccb11e12014-07-08 16:04:02 -07002409 int mHardwareXOffset;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002410 int mHardwareYOffset;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002411
Igor Murashkina86ab6402013-08-30 12:58:36 -07002412 @Override
Chris Craikf6829a02015-03-10 10:28:59 -07002413 public void onHardwarePreDraw(DisplayListCanvas canvas) {
Alan Viveretteccb11e12014-07-08 16:04:02 -07002414 canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002415 }
2416
Igor Murashkina86ab6402013-08-30 12:58:36 -07002417 @Override
Chris Craikf6829a02015-03-10 10:28:59 -07002418 public void onHardwarePostDraw(DisplayListCanvas canvas) {
Alan Viverette632af842014-10-28 13:45:11 -07002419 drawAccessibilityFocusedDrawableIfNeeded(canvas);
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002420 }
2421
Chet Haaseed30fd82011-04-22 16:18:45 -07002422 /**
2423 * @hide
2424 */
2425 void outputDisplayList(View view) {
Chris Craik356b5fe2015-07-07 10:39:36 -07002426 view.mRenderNode.output();
John Recke248bd12015-08-05 13:53:53 -07002427 if (mAttachInfo.mHardwareRenderer != null) {
2428 ((ThreadedRenderer)mAttachInfo.mHardwareRenderer).serializeDisplayListTree();
2429 }
Romain Guy59a12ca2011-06-09 17:48:21 -07002430 }
2431
2432 /**
2433 * @see #PROPERTY_PROFILE_RENDERING
2434 */
2435 private void profileRendering(boolean enabled) {
2436 if (mProfileRendering) {
2437 mRenderProfilingEnabled = enabled;
Chris Craikae4f32042013-02-07 12:57:10 -08002438
2439 if (mRenderProfiler != null) {
2440 mChoreographer.removeFrameCallback(mRenderProfiler);
2441 }
2442 if (mRenderProfilingEnabled) {
2443 if (mRenderProfiler == null) {
2444 mRenderProfiler = new Choreographer.FrameCallback() {
2445 @Override
2446 public void doFrame(long frameTimeNanos) {
2447 mDirty.set(0, 0, mWidth, mHeight);
2448 scheduleTraversals();
2449 if (mRenderProfilingEnabled) {
2450 mChoreographer.postFrameCallback(mRenderProfiler);
2451 }
Romain Guy59a12ca2011-06-09 17:48:21 -07002452 }
Chris Craikae4f32042013-02-07 12:57:10 -08002453 };
2454 }
Romain Guy5bb3c732012-11-29 17:52:58 -08002455 mChoreographer.postFrameCallback(mRenderProfiler);
Romain Guy59a12ca2011-06-09 17:48:21 -07002456 } else {
Romain Guy59a12ca2011-06-09 17:48:21 -07002457 mRenderProfiler = null;
Chet Haaseed30fd82011-04-22 16:18:45 -07002458 }
2459 }
2460 }
2461
Chet Haase2f2022a2011-10-11 06:41:59 -07002462 /**
2463 * Called from draw() when DEBUG_FPS is enabled
2464 */
2465 private void trackFPS() {
2466 // Tracks frames per second drawn. First value in a series of draws may be bogus
2467 // because it down not account for the intervening idle time
2468 long nowTime = System.currentTimeMillis();
2469 if (mFpsStartTime < 0) {
2470 mFpsStartTime = mFpsPrevTime = nowTime;
2471 mFpsNumFrames = 0;
2472 } else {
2473 ++mFpsNumFrames;
2474 String thisHash = Integer.toHexString(System.identityHashCode(this));
2475 long frameTime = nowTime - mFpsPrevTime;
2476 long totalTime = nowTime - mFpsStartTime;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002477 Log.v(mTag, "0x" + thisHash + "\tFrame time:\t" + frameTime);
Chet Haase2f2022a2011-10-11 06:41:59 -07002478 mFpsPrevTime = nowTime;
2479 if (totalTime > 1000) {
2480 float fps = (float) mFpsNumFrames * 1000 / totalTime;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002481 Log.v(mTag, "0x" + thisHash + "\tFPS:\t" + fps);
Chet Haase2f2022a2011-10-11 06:41:59 -07002482 mFpsStartTime = nowTime;
2483 mFpsNumFrames = 0;
2484 }
2485 }
2486 }
2487
Jeff Brown96e942d2011-11-30 19:55:01 -08002488 private void performDraw() {
Jeff Brownd912e1f2014-04-11 18:46:22 -07002489 if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
Craig Mautner006f0e42012-03-21 11:00:32 -07002490 return;
2491 }
Romain Guy7e4e5612012-03-05 14:37:29 -08002492
Jeff Brown96e942d2011-11-30 19:55:01 -08002493 final boolean fullRedrawNeeded = mFullRedrawNeeded;
2494 mFullRedrawNeeded = false;
Jeff Brown481c1572012-03-09 14:41:15 -08002495
Romain Guy1f59e5c2012-05-06 14:11:16 -07002496 mIsDrawing = true;
Jeff Brown481c1572012-03-09 14:41:15 -08002497 Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2498 try {
2499 draw(fullRedrawNeeded);
2500 } finally {
Romain Guy1f59e5c2012-05-06 14:11:16 -07002501 mIsDrawing = false;
Jeff Brown481c1572012-03-09 14:41:15 -08002502 Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2503 }
Jeff Brown96e942d2011-11-30 19:55:01 -08002504
John Reck119907c2014-08-14 09:02:01 -07002505 // For whatever reason we didn't create a HardwareRenderer, end any
2506 // hardware animations that are now dangling
2507 if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
2508 final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
2509 for (int i = 0; i < count; i++) {
2510 mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
2511 }
2512 mAttachInfo.mPendingAnimatingRenderNodes.clear();
2513 }
2514
Jeff Brown96e942d2011-11-30 19:55:01 -08002515 if (mReportNextDraw) {
2516 mReportNextDraw = false;
Chong Zhang8dbd9ad2015-10-09 10:06:11 -07002517
2518 // if we're using multi-thread renderer, wait for the window frame draws
2519 if (mWindowDrawCountDown != null) {
2520 try {
2521 mWindowDrawCountDown.await();
2522 } catch (InterruptedException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002523 Log.e(mTag, "Window redraw count down interruped!");
Chong Zhang8dbd9ad2015-10-09 10:06:11 -07002524 }
2525 mWindowDrawCountDown = null;
2526 }
2527
John Reck28ad7b52014-04-07 16:59:25 -07002528 if (mAttachInfo.mHardwareRenderer != null) {
2529 mAttachInfo.mHardwareRenderer.fence();
2530 }
Jeff Brown96e942d2011-11-30 19:55:01 -08002531
2532 if (LOCAL_LOGV) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002533 Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
Jeff Brown96e942d2011-11-30 19:55:01 -08002534 }
2535 if (mSurfaceHolder != null && mSurface.isValid()) {
2536 mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2537 SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2538 if (callbacks != null) {
2539 for (SurfaceHolder.Callback c : callbacks) {
2540 if (c instanceof SurfaceHolder.Callback2) {
Filip Gruszczynski1a4dfe52015-11-15 10:58:57 -08002541 ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(mSurfaceHolder);
Jeff Brown96e942d2011-11-30 19:55:01 -08002542 }
2543 }
2544 }
2545 }
2546 try {
Jeff Brown98365d72012-08-19 20:30:52 -07002547 mWindowSession.finishDrawing(mWindow);
Jeff Brown96e942d2011-11-30 19:55:01 -08002548 } catch (RemoteException e) {
2549 }
2550 }
2551 }
2552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 private void draw(boolean fullRedrawNeeded) {
2554 Surface surface = mSurface;
Romain Guyfbb93fa2012-12-03 18:50:35 -08002555 if (!surface.isValid()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 return;
2557 }
2558
Chet Haase2f2022a2011-10-11 06:41:59 -07002559 if (DEBUG_FPS) {
2560 trackFPS();
2561 }
2562
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002563 if (!sFirstDrawComplete) {
2564 synchronized (sFirstDrawHandlers) {
2565 sFirstDrawComplete = true;
Romain Guy812ccbe2010-06-01 14:07:24 -07002566 final int count = sFirstDrawHandlers.size();
2567 for (int i = 0; i< count; i++) {
Jeff Browna175a5b2012-02-15 19:18:31 -08002568 mHandler.post(sFirstDrawHandlers.get(i));
Dianne Hackborn2a9094d2010-02-03 19:20:09 -08002569 }
2570 }
2571 }
Romain Guy59a12ca2011-06-09 17:48:21 -07002572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 scrollToRectOrFocus(null, false);
2574
Chris Craikd36a81f2014-07-17 10:16:51 -07002575 if (mAttachInfo.mViewScrollChanged) {
2576 mAttachInfo.mViewScrollChanged = false;
2577 mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
Romain Guy8506ab42009-06-11 17:35:47 -07002579
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002580 boolean animating = mScroller != null && mScroller.computeScrollOffset();
Alan Viveretteccb11e12014-07-08 16:04:02 -07002581 final int curScrollY;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002582 if (animating) {
Alan Viveretteccb11e12014-07-08 16:04:02 -07002583 curScrollY = mScroller.getCurrY();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 } else {
Alan Viveretteccb11e12014-07-08 16:04:02 -07002585 curScrollY = mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
Alan Viveretteccb11e12014-07-08 16:04:02 -07002587 if (mCurScrollY != curScrollY) {
2588 mCurScrollY = curScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 fullRedrawNeeded = true;
Adrian Roos0e7ae4e2014-10-01 15:33:22 +02002590 if (mView instanceof RootViewSurfaceTaker) {
2591 ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 }
Jeff Brown96e942d2011-11-30 19:55:01 -08002594
Chris Craikd36a81f2014-07-17 10:16:51 -07002595 final float appScale = mAttachInfo.mApplicationScale;
2596 final boolean scalingRequired = mAttachInfo.mScalingRequired;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002598 int resizeAlpha = 0;
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002599
Jeff Brown96e942d2011-11-30 19:55:01 -08002600 final Rect dirty = mDirty;
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002601 if (mSurfaceHolder != null) {
2602 // The app owns the surface, we won't draw.
2603 dirty.setEmpty();
Derek Sollenberger8d948352015-07-16 09:27:59 -04002604 if (animating && mScroller != null) {
2605 mScroller.abortAnimation();
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002606 }
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07002607 return;
2608 }
Romain Guy58ef7fb2010-09-13 12:52:37 -07002609
2610 if (fullRedrawNeeded) {
Chris Craikd36a81f2014-07-17 10:16:51 -07002611 mAttachInfo.mIgnoreDirtyState = true;
Romain Guyc3166e12011-08-08 15:00:03 -07002612 dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
Romain Guy58ef7fb2010-09-13 12:52:37 -07002613 }
Chet Haasead4f7032011-06-22 09:18:31 -07002614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002616 Log.v(mTag, "Draw " + mView + "/"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 + mWindowAttributes.getTitle()
2618 + ": dirty={" + dirty.left + "," + dirty.top
2619 + "," + dirty.right + "," + dirty.bottom + "} surface="
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07002620 + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2621 appScale + ", width=" + mWidth + ", height=" + mHeight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 }
2623
Chris Craikd36a81f2014-07-17 10:16:51 -07002624 mAttachInfo.mTreeObserver.dispatchOnDraw();
Romain Guy25eba5c2012-04-04 17:29:03 -07002625
Chong Zhang0275e392015-09-17 10:41:44 -07002626 int xOffset = -mCanvasOffsetX;
2627 int yOffset = -mCanvasOffsetY + curScrollY;
Alan Viverettea51cab92014-07-16 15:15:49 -07002628 final WindowManager.LayoutParams params = mWindowAttributes;
2629 final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
2630 if (surfaceInsets != null) {
2631 xOffset -= surfaceInsets.left;
2632 yOffset -= surfaceInsets.top;
2633
2634 // Offset dirty rect for surface insets.
2635 dirty.offset(surfaceInsets.left, surfaceInsets.right);
2636 }
2637
Alan Viverette632af842014-10-28 13:45:11 -07002638 boolean accessibilityFocusDirty = false;
2639 final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
2640 if (drawable != null) {
2641 final Rect bounds = mAttachInfo.mTmpInvalRect;
2642 final boolean hasFocus = getAccessibilityFocusedRect(bounds);
2643 if (!hasFocus) {
2644 bounds.setEmpty();
2645 }
2646 if (!bounds.equals(drawable.getBounds())) {
2647 accessibilityFocusDirty = true;
2648 }
2649 }
2650
John Reckba6adf62015-02-19 14:36:50 -08002651 mAttachInfo.mDrawingTime =
2652 mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
2653
Alan Viverette632af842014-10-28 13:45:11 -07002654 if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
Chris Craikd36a81f2014-07-17 10:16:51 -07002655 if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
Alan Viverette632af842014-10-28 13:45:11 -07002656 // If accessibility focus moved, always invalidate the root.
2657 boolean invalidateRoot = accessibilityFocusDirty;
2658
Jeff Brown96e942d2011-11-30 19:55:01 -08002659 // Draw with hardware renderer.
2660 mIsAnimating = false;
Alan Viverette632af842014-10-28 13:45:11 -07002661
John Reck0a973302014-07-16 13:29:45 -07002662 if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2663 mHardwareYOffset = yOffset;
2664 mHardwareXOffset = xOffset;
Alan Viverette632af842014-10-28 13:45:11 -07002665 invalidateRoot = true;
Alan Viverettef6cf1a02014-08-11 14:13:02 -07002666 }
2667
Alan Viverette632af842014-10-28 13:45:11 -07002668 if (invalidateRoot) {
2669 mAttachInfo.mHardwareRenderer.invalidateRoot();
2670 }
2671
Jeff Brown96e942d2011-11-30 19:55:01 -08002672 dirty.setEmpty();
2673
Skuhne980ee472015-10-06 11:31:31 -07002674 // Stage the content drawn size now. It will be transferred to the renderer
2675 // shortly before the draw commands get send to the renderer.
Chong Zhang8dbd9ad2015-10-09 10:06:11 -07002676 final boolean updated = updateContentDrawBounds();
2677
John Reck61375a82014-09-18 19:27:48 +00002678 mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
Chong Zhang8dbd9ad2015-10-09 10:06:11 -07002679
2680 if (updated) {
2681 requestDrawWindow();
2682 }
Romain Guy3696779b2013-01-28 14:04:07 -08002683 } else {
2684 // If we get here with a disabled & requested hardware renderer, something went
2685 // wrong (an invalidate posted right before we destroyed the hardware surface
2686 // for instance) so we should just bail out. Locking the surface with software
2687 // rendering at this point would lock it forever and prevent hardware renderer
2688 // from doing its job when it comes back.
2689 // Before we request a new frame we must however attempt to reinitiliaze the
2690 // hardware renderer if it's in requested state. This would happen after an
2691 // eglTerminate() for instance.
Chris Craikd36a81f2014-07-17 10:16:51 -07002692 if (mAttachInfo.mHardwareRenderer != null &&
2693 !mAttachInfo.mHardwareRenderer.isEnabled() &&
2694 mAttachInfo.mHardwareRenderer.isRequested()) {
Romain Guy3696779b2013-01-28 14:04:07 -08002695
2696 try {
Chris Craikd36a81f2014-07-17 10:16:51 -07002697 mAttachInfo.mHardwareRenderer.initializeIfNeeded(
Alan Viverette50210d92015-05-14 18:05:36 -07002698 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
Igor Murashkina86ab6402013-08-30 12:58:36 -07002699 } catch (OutOfResourcesException e) {
Romain Guy3696779b2013-01-28 14:04:07 -08002700 handleOutOfResourcesException(e);
2701 return;
2702 }
2703
2704 mFullRedrawNeeded = true;
2705 scheduleTraversals();
2706 return;
2707 }
2708
Chris Craikd36a81f2014-07-17 10:16:51 -07002709 if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
Romain Guy3696779b2013-01-28 14:04:07 -08002710 return;
2711 }
Jeff Brown95db2b22011-11-30 19:54:41 -08002712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
Romain Guy8506ab42009-06-11 17:35:47 -07002714
Dianne Hackborn0f761d62010-11-30 22:06:10 -08002715 if (animating) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 mFullRedrawNeeded = true;
2717 scheduleTraversals();
2718 }
2719 }
2720
Romain Guy25eba5c2012-04-04 17:29:03 -07002721 /**
Alan Viveretteccb11e12014-07-08 16:04:02 -07002722 * @return true if drawing was successful, false if an error occurred
Romain Guy25eba5c2012-04-04 17:29:03 -07002723 */
Alan Viveretteccb11e12014-07-08 16:04:02 -07002724 private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
Romain Guy25eba5c2012-04-04 17:29:03 -07002725 boolean scalingRequired, Rect dirty) {
2726
2727 // Draw with software renderer.
Alan Viverettea51cab92014-07-16 15:15:49 -07002728 final Canvas canvas;
Romain Guy25eba5c2012-04-04 17:29:03 -07002729 try {
Alan Viverettea51cab92014-07-16 15:15:49 -07002730 final int left = dirty.left;
2731 final int top = dirty.top;
2732 final int right = dirty.right;
2733 final int bottom = dirty.bottom;
Romain Guy25eba5c2012-04-04 17:29:03 -07002734
Romain Guy25eba5c2012-04-04 17:29:03 -07002735 canvas = mSurface.lockCanvas(dirty);
2736
Romain Guye55945e2013-04-04 15:26:04 -07002737 // The dirty rectangle can be modified by Surface.lockCanvas()
2738 //noinspection ConstantConditions
Alan Viverettea51cab92014-07-16 15:15:49 -07002739 if (left != dirty.left || top != dirty.top || right != dirty.right
2740 || bottom != dirty.bottom) {
Romain Guy25eba5c2012-04-04 17:29:03 -07002741 attachInfo.mIgnoreDirtyState = true;
2742 }
2743
2744 // TODO: Do this in native
2745 canvas.setDensity(mDensity);
2746 } catch (Surface.OutOfResourcesException e) {
Romain Guy3696779b2013-01-28 14:04:07 -08002747 handleOutOfResourcesException(e);
Romain Guy25eba5c2012-04-04 17:29:03 -07002748 return false;
2749 } catch (IllegalArgumentException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002750 Log.e(mTag, "Could not lock surface", e);
Romain Guy25eba5c2012-04-04 17:29:03 -07002751 // Don't assume this is due to out of memory, it could be
2752 // something else, and if it is something else then we could
2753 // kill stuff (or ourself) for no reason.
2754 mLayoutRequested = true; // ask wm for a new surface next time.
2755 return false;
2756 }
2757
2758 try {
2759 if (DEBUG_ORIENTATION || DEBUG_DRAW) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002760 Log.v(mTag, "Surface " + surface + " drawing to bitmap w="
Romain Guy25eba5c2012-04-04 17:29:03 -07002761 + canvas.getWidth() + ", h=" + canvas.getHeight());
2762 //canvas.drawARGB(255, 255, 0, 0);
2763 }
2764
Romain Guy25eba5c2012-04-04 17:29:03 -07002765 // If this bitmap's format includes an alpha channel, we
2766 // need to clear it before drawing so that the child will
2767 // properly re-composite its drawing on a transparent
2768 // background. This automatically respects the clip/dirty region
2769 // or
2770 // If we are applying an offset, we need to clear the area
2771 // where the offset doesn't appear to avoid having garbage
2772 // left in the blank areas.
Alan Viveretteccb11e12014-07-08 16:04:02 -07002773 if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
Romain Guy25eba5c2012-04-04 17:29:03 -07002774 canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2775 }
2776
2777 dirty.setEmpty();
2778 mIsAnimating = false;
Dianne Hackborn4702a852012-08-17 15:18:29 -07002779 mView.mPrivateFlags |= View.PFLAG_DRAWN;
Romain Guy25eba5c2012-04-04 17:29:03 -07002780
2781 if (DEBUG_DRAW) {
2782 Context cxt = mView.getContext();
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002783 Log.i(mTag, "Drawing: package:" + cxt.getPackageName() +
Romain Guy25eba5c2012-04-04 17:29:03 -07002784 ", metrics=" + cxt.getResources().getDisplayMetrics() +
2785 ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2786 }
2787 try {
Alan Viveretteccb11e12014-07-08 16:04:02 -07002788 canvas.translate(-xoff, -yoff);
Romain Guy25eba5c2012-04-04 17:29:03 -07002789 if (mTranslator != null) {
2790 mTranslator.translateCanvas(canvas);
2791 }
Dianne Hackborn908aecc2012-07-31 16:37:34 -07002792 canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
Romain Guy25eba5c2012-04-04 17:29:03 -07002793 attachInfo.mSetIgnoreDirtyState = false;
2794
Romain Guy25eba5c2012-04-04 17:29:03 -07002795 mView.draw(canvas);
Alan Viverette632af842014-10-28 13:45:11 -07002796
2797 drawAccessibilityFocusedDrawableIfNeeded(canvas);
Romain Guy25eba5c2012-04-04 17:29:03 -07002798 } finally {
2799 if (!attachInfo.mSetIgnoreDirtyState) {
2800 // Only clear the flag if it was not set during the mView.draw() call
2801 attachInfo.mIgnoreDirtyState = false;
2802 }
2803 }
Romain Guy25eba5c2012-04-04 17:29:03 -07002804 } finally {
Romain Guydddcd222012-05-18 15:33:57 -07002805 try {
2806 surface.unlockCanvasAndPost(canvas);
2807 } catch (IllegalArgumentException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002808 Log.e(mTag, "Could not unlock surface", e);
Romain Guydddcd222012-05-18 15:33:57 -07002809 mLayoutRequested = true; // ask wm for a new surface next time.
2810 //noinspection ReturnInsideFinallyBlock
2811 return false;
2812 }
Romain Guy25eba5c2012-04-04 17:29:03 -07002813
Romain Guy25eba5c2012-04-04 17:29:03 -07002814 if (LOCAL_LOGV) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002815 Log.v(mTag, "Surface " + surface + " unlockCanvasAndPost");
Romain Guy25eba5c2012-04-04 17:29:03 -07002816 }
2817 }
2818 return true;
2819 }
2820
Alan Viverette632af842014-10-28 13:45:11 -07002821 /**
2822 * We want to draw a highlight around the current accessibility focused.
2823 * Since adding a style for all possible view is not a viable option we
2824 * have this specialized drawing method.
2825 *
2826 * Note: We are doing this here to be able to draw the highlight for
2827 * virtual views in addition to real ones.
2828 *
2829 * @param canvas The canvas on which to draw.
2830 */
2831 private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2832 final Rect bounds = mAttachInfo.mTmpInvalRect;
2833 if (getAccessibilityFocusedRect(bounds)) {
2834 final Drawable drawable = getAccessibilityFocusedDrawable();
2835 if (drawable != null) {
2836 drawable.setBounds(bounds);
2837 drawable.draw(canvas);
2838 }
2839 } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2840 mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2841 }
2842 }
2843
2844 private boolean getAccessibilityFocusedRect(Rect bounds) {
2845 final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2846 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2847 return false;
2848 }
2849
2850 final View host = mAccessibilityFocusedHost;
2851 if (host == null || host.mAttachInfo == null) {
2852 return false;
2853 }
2854
2855 final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2856 if (provider == null) {
Svetoslavded133c2015-01-30 20:28:41 -08002857 host.getBoundsOnScreen(bounds, true);
Alan Viverette632af842014-10-28 13:45:11 -07002858 } else if (mAccessibilityFocusedVirtualView != null) {
2859 mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2860 } else {
2861 return false;
2862 }
2863
Alan Viverette2232add2015-05-26 15:24:18 -07002864 // Transform the rect into window-relative coordinates.
Alan Viverette632af842014-10-28 13:45:11 -07002865 final AttachInfo attachInfo = mAttachInfo;
Alan Viverette2232add2015-05-26 15:24:18 -07002866 bounds.offset(0, attachInfo.mViewRootImpl.mScrollY);
Alan Viverette632af842014-10-28 13:45:11 -07002867 bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
Doris Liu9607fbe2015-05-28 17:17:28 -07002868 if (!bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth,
2869 attachInfo.mViewRootImpl.mHeight)) {
2870 // If no intersection, set bounds to empty.
2871 bounds.setEmpty();
2872 }
Alan Viverette632af842014-10-28 13:45:11 -07002873 return !bounds.isEmpty();
2874 }
2875
2876 private Drawable getAccessibilityFocusedDrawable() {
Chris Craikd36a81f2014-07-17 10:16:51 -07002877 // Lazily load the accessibility focus drawable.
2878 if (mAttachInfo.mAccessibilityFocusDrawable == null) {
Alan Viverettef6cf1a02014-08-11 14:13:02 -07002879 final TypedValue value = new TypedValue();
Chris Craikd36a81f2014-07-17 10:16:51 -07002880 final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2881 R.attr.accessibilityFocusedDrawable, value, true);
2882 if (resolved) {
2883 mAttachInfo.mAccessibilityFocusDrawable =
Alan Viverette8eea3ea2014-02-03 18:40:20 -08002884 mView.mContext.getDrawable(value.resourceId);
Svetoslav Ganov42138042012-03-20 11:51:39 -07002885 }
Svetoslav Ganov42138042012-03-20 11:51:39 -07002886 }
Chris Craikd36a81f2014-07-17 10:16:51 -07002887 return mAttachInfo.mAccessibilityFocusDrawable;
Svetoslav Ganov42138042012-03-20 11:51:39 -07002888 }
2889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
Chris Craikd36a81f2014-07-17 10:16:51 -07002891 final Rect ci = mAttachInfo.mContentInsets;
2892 final Rect vi = mAttachInfo.mVisibleInsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 int scrollY = 0;
2894 boolean handled = false;
Romain Guy8506ab42009-06-11 17:35:47 -07002895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 if (vi.left > ci.left || vi.top > ci.top
2897 || vi.right > ci.right || vi.bottom > ci.bottom) {
2898 // We'll assume that we aren't going to change the scroll
2899 // offset, since we want to avoid that unless it is actually
2900 // going to make the focus visible... otherwise we scroll
2901 // all over the place.
2902 scrollY = mScrollY;
2903 // We can be called for two different situations: during a draw,
2904 // to update the scroll position if the focus has changed (in which
2905 // case 'rectangle' is null), or in response to a
2906 // requestChildRectangleOnScreen() call (in which case 'rectangle'
2907 // is non-null and we just want to scroll to whatever that
2908 // rectangle is).
Craig Mautner26a84df2013-04-11 19:09:05 -07002909 final View focus = mView.findFocus();
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002910 if (focus == null) {
Romain Guye8b16522009-07-14 13:06:42 -07002911 return false;
2912 }
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002913 View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
Craig Mautner26a84df2013-04-11 19:09:05 -07002914 if (focus != lastScrolledFocus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 // If the focus has changed, then ignore any requests to scroll
2916 // to a rectangle; first we want to make sure the entire focus
2917 // view is visible.
2918 rectangle = null;
2919 }
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002920 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Eval scroll: focus=" + focus
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 + " rectangle=" + rectangle + " ci=" + ci
2922 + " vi=" + vi);
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002923 if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 // Optimization: if the focus hasn't changed since last
2925 // time, and no layout has happened, then just leave things
2926 // as they are.
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002927 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Keeping scroll y="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 + mScrollY + " vi=" + vi.toShortString());
Craig Mautner26a84df2013-04-11 19:09:05 -07002929 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 // We need to determine if the currently focused view is
2931 // within the visible part of the window and, if not, apply
2932 // a pan so it can be seen.
Svetoslav Ganov149567f2013-01-08 15:23:34 -08002933 mLastScrolledFocus = new WeakReference<View>(focus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 mScrollMayChange = false;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002935 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Need to scroll?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 // Try to find the rectangle from the focus view.
2937 if (focus.getGlobalVisibleRect(mVisRect, null)) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002938 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Root w="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 + mView.getWidth() + " h=" + mView.getHeight()
2940 + " ci=" + ci.toShortString()
2941 + " vi=" + vi.toShortString());
2942 if (rectangle == null) {
2943 focus.getFocusedRect(mTempRect);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002944 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Focus " + focus
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 + ": focusRect=" + mTempRect.toShortString());
Dianne Hackborn1c6a8942010-03-23 16:34:20 -07002946 if (mView instanceof ViewGroup) {
2947 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2948 focus, mTempRect);
2949 }
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002950 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 "Focus in window: focusRect="
2952 + mTempRect.toShortString()
2953 + " visRect=" + mVisRect.toShortString());
2954 } else {
2955 mTempRect.set(rectangle);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002956 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 "Request scroll to rect: "
2958 + mTempRect.toShortString()
2959 + " visRect=" + mVisRect.toShortString());
2960 }
2961 if (mTempRect.intersect(mVisRect)) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002962 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 "Focus window visible rect: "
2964 + mTempRect.toShortString());
2965 if (mTempRect.height() >
2966 (mView.getHeight()-vi.top-vi.bottom)) {
2967 // If the focus simply is not going to fit, then
2968 // best is probably just to leave things as-is.
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002969 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 "Too tall; leaving scrollY=" + scrollY);
2971 } else if ((mTempRect.top-scrollY) < vi.top) {
2972 scrollY -= vi.top - (mTempRect.top-scrollY);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002973 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 "Top covered; scrollY=" + scrollY);
2975 } else if ((mTempRect.bottom-scrollY)
2976 > (mView.getHeight()-vi.bottom)) {
2977 scrollY += (mTempRect.bottom-scrollY)
2978 - (mView.getHeight()-vi.bottom);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002979 if (DEBUG_INPUT_RESIZE) Log.v(mTag,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 "Bottom covered; scrollY=" + scrollY);
2981 }
2982 handled = true;
2983 }
2984 }
2985 }
2986 }
Romain Guy8506ab42009-06-11 17:35:47 -07002987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 if (scrollY != mScrollY) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08002989 if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Pan scroll changed: old="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 + mScrollY + " , new=" + scrollY);
Derek Sollenberger8d948352015-07-16 09:27:59 -04002991 if (!immediate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 if (mScroller == null) {
2993 mScroller = new Scroller(mView.getContext());
2994 }
2995 mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
2996 } else if (mScroller != null) {
2997 mScroller.abortAnimation();
2998 }
2999 mScrollY = scrollY;
3000 }
Romain Guy8506ab42009-06-11 17:35:47 -07003001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 return handled;
3003 }
Romain Guy8506ab42009-06-11 17:35:47 -07003004
Svetoslav Ganove5dfa47d2012-05-08 15:58:32 -07003005 /**
3006 * @hide
3007 */
3008 public View getAccessibilityFocusedHost() {
3009 return mAccessibilityFocusedHost;
3010 }
3011
3012 /**
3013 * @hide
3014 */
3015 public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
3016 return mAccessibilityFocusedVirtualView;
3017 }
3018
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07003019 void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003020 // If we have a virtual view with accessibility focus we need
3021 // to clear the focus and invalidate the virtual view bounds.
3022 if (mAccessibilityFocusedVirtualView != null) {
3023
3024 AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
3025 View focusHost = mAccessibilityFocusedHost;
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003026
3027 // Wipe the state of the current accessibility focus since
3028 // the call into the provider to clear accessibility focus
3029 // will fire an accessibility event which will end up calling
3030 // this method and we want to have clean state when this
3031 // invocation happens.
3032 mAccessibilityFocusedHost = null;
3033 mAccessibilityFocusedVirtualView = null;
3034
Alan Viverette239a0c02013-05-07 17:17:35 -07003035 // Clear accessibility focus on the host after clearing state since
3036 // this method may be reentrant.
3037 focusHost.clearAccessibilityFocusNoCallbacks();
3038
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003039 AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
3040 if (provider != null) {
3041 // Invalidate the area of the cleared accessibility focus.
3042 focusNode.getBoundsInParent(mTempRect);
3043 focusHost.invalidate(mTempRect);
3044 // Clear accessibility focus in the virtual node.
3045 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
3046 focusNode.getSourceNodeId());
3047 provider.performAction(virtualNodeId,
3048 AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
3049 }
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07003050 focusNode.recycle();
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003051 }
3052 if (mAccessibilityFocusedHost != null) {
3053 // Clear accessibility focus in the view.
Svetoslav Ganov42138042012-03-20 11:51:39 -07003054 mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
3055 }
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003056
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07003057 // Set the new focus host and node.
3058 mAccessibilityFocusedHost = view;
3059 mAccessibilityFocusedVirtualView = node;
John Reck0a973302014-07-16 13:29:45 -07003060
3061 if (mAttachInfo.mHardwareRenderer != null) {
3062 mAttachInfo.mHardwareRenderer.invalidateRoot();
3063 }
Svetoslav Ganov42138042012-03-20 11:51:39 -07003064 }
3065
Jun Mukai347e5d42015-12-03 01:13:31 -08003066 void setPointerCapture(View view) {
3067 if (!mAttachInfo.mHasWindowFocus) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003068 Log.w(mTag, "Can't set capture if it's not focused.");
Jun Mukai347e5d42015-12-03 01:13:31 -08003069 return;
3070 }
3071 if (mCapturingView == view) {
3072 return;
3073 }
3074 mCapturingView = view;
3075 InputManager.getInstance().setPointerIconDetached(true);
3076 }
3077
3078 void releasePointerCapture(View view) {
3079 if (mCapturingView != view || mCapturingView == null) {
3080 return;
3081 }
3082
3083 mCapturingView = null;
3084 InputManager.getInstance().setPointerIconDetached(false);
3085 }
3086
3087 boolean hasPointerCapture(View view) {
3088 return view != null && mCapturingView == view;
3089 }
3090
Igor Murashkina86ab6402013-08-30 12:58:36 -07003091 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 public void requestChildFocus(View child, View focused) {
Svetoslav Ganovb36a0ac2012-02-14 17:46:47 -08003093 if (DEBUG_INPUT_RESIZE) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003094 Log.v(mTag, "Request child focus: focus now " + focused);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
Svetoslav Ganov149567f2013-01-08 15:23:34 -08003096 checkThread();
Svetoslav Ganovb36a0ac2012-02-14 17:46:47 -08003097 scheduleTraversals();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
3099
Igor Murashkina86ab6402013-08-30 12:58:36 -07003100 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 public void clearChildFocus(View child) {
Svetoslav Ganovb36a0ac2012-02-14 17:46:47 -08003102 if (DEBUG_INPUT_RESIZE) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003103 Log.v(mTag, "Clearing child focus");
Amith Yamasani73eb97f2012-02-14 15:45:15 -08003104 }
Svetoslav Ganov149567f2013-01-08 15:23:34 -08003105 checkThread();
3106 scheduleTraversals();
Svetoslav Ganovb36a0ac2012-02-14 17:46:47 -08003107 }
Amith Yamasani73eb97f2012-02-14 15:45:15 -08003108
Svetoslav Ganov42138042012-03-20 11:51:39 -07003109 @Override
3110 public ViewParent getParentForAccessibility() {
3111 return null;
3112 }
3113
Igor Murashkina86ab6402013-08-30 12:58:36 -07003114 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 public void focusableViewAvailable(View v) {
3116 checkThread();
Romain Guy1c90f032011-05-24 14:59:50 -07003117 if (mView != null) {
3118 if (!mView.hasFocus()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 v.requestFocus();
Romain Guy1c90f032011-05-24 14:59:50 -07003120 } else {
3121 // the one case where will transfer focus away from the current one
3122 // is if the current view is a view group that prefers to give focus
3123 // to its children first AND the view is a descendant of it.
Svetoslav Ganov149567f2013-01-08 15:23:34 -08003124 View focused = mView.findFocus();
3125 if (focused instanceof ViewGroup) {
3126 ViewGroup group = (ViewGroup) focused;
3127 if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3128 && isViewDescendantOf(v, focused)) {
3129 v.requestFocus();
3130 }
Romain Guy1c90f032011-05-24 14:59:50 -07003131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
3133 }
3134 }
3135
Igor Murashkina86ab6402013-08-30 12:58:36 -07003136 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 public void recomputeViewAttributes(View child) {
3138 checkThread();
3139 if (mView == child) {
3140 mAttachInfo.mRecomputeGlobalAttributes = true;
3141 if (!mWillDrawSoon) {
3142 scheduleTraversals();
3143 }
3144 }
3145 }
3146
3147 void dispatchDetachedFromWindow() {
Romain Guy90fc03b2011-01-16 13:07:15 -08003148 if (mView != null && mView.mAttachInfo != null) {
Dianne Hackborn961cae92013-03-20 14:59:43 -07003149 mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 mView.dispatchDetachedFromWindow();
3151 }
3152
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07003153 mAccessibilityInteractionConnectionManager.ensureNoConnection();
3154 mAccessibilityManager.removeAccessibilityStateChangeListener(
3155 mAccessibilityInteractionConnectionManager);
Chris Craikcce47eb2014-07-16 15:12:15 -07003156 mAccessibilityManager.removeHighTextContrastStateChangeListener(
3157 mHighContrastTextManager);
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07003158 removeSendWindowContentChangedCallback();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07003159
Romain Guya998dff2012-03-23 18:58:36 -07003160 destroyHardwareRenderer();
3161
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07003162 setAccessibilityFocus(null, null);
Svetoslav Ganov791fd312012-05-14 15:12:30 -07003163
Craig Mautner8f303ad2013-06-14 11:32:22 -07003164 mView.assignParent(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 mView = null;
3166 mAttachInfo.mRootView = null;
3167
Jun Mukai347e5d42015-12-03 01:13:31 -08003168 if (mCapturingView != null) {
3169 releasePointerCapture(mCapturingView);
3170 }
3171
Dianne Hackborn0586a1b2009-09-06 21:08:27 -07003172 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173
Jeff Browncc4f7db2011-08-30 20:34:48 -07003174 if (mInputQueueCallback != null && mInputQueue != null) {
3175 mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
Michael Wrighta44dd262013-04-10 21:12:00 -07003176 mInputQueue.dispose();
Jeff Browncc4f7db2011-08-30 20:34:48 -07003177 mInputQueueCallback = null;
3178 mInputQueue = null;
Michael Wrighta44dd262013-04-10 21:12:00 -07003179 }
3180 if (mInputEventReceiver != null) {
Jeff Brown32cbc38552011-12-01 14:01:49 -08003181 mInputEventReceiver.dispose();
3182 mInputEventReceiver = null;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 try {
Jeff Brown98365d72012-08-19 20:30:52 -07003185 mWindowSession.remove(mWindow);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 } catch (RemoteException e) {
3187 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07003188
Jeff Brown00fa7bd2010-07-02 15:37:36 -07003189 // Dispose the input channel after removing the window so the Window Manager
3190 // doesn't interpret the input channel being closed as an abnormal termination.
3191 if (mInputChannel != null) {
3192 mInputChannel.dispose();
3193 mInputChannel = null;
Jeff Brown349703e2010-06-22 01:27:15 -07003194 }
Jeff Brown96e942d2011-11-30 19:55:01 -08003195
Jeff Brownd912e1f2014-04-11 18:46:22 -07003196 mDisplayManager.unregisterDisplayListener(mDisplayListener);
3197
Jeff Brownebb2d8d2012-03-23 17:14:34 -07003198 unscheduleTraversals();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
Romain Guy8506ab42009-06-11 17:35:47 -07003200
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003201 void updateConfiguration(Configuration config, boolean force) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003202 if (DEBUG_CONFIGURATION) Log.v(mTag,
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003203 "Applying new config to window "
3204 + mWindowAttributes.getTitle()
3205 + ": " + config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003206
Craig Mautner48d0d182013-06-11 07:53:06 -07003207 CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3208 if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003209 config = new Configuration(config);
Dianne Hackborn908aecc2012-07-31 16:37:34 -07003210 ci.applyToConfiguration(mNoncompatDensity, config);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07003211 }
3212
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003213 synchronized (sConfigCallbacks) {
3214 for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3215 sConfigCallbacks.get(i).onConfigurationChanged(config);
3216 }
3217 }
3218 if (mView != null) {
3219 // At this point the resources have been updated to
3220 // have the most recent config, whatever that is. Use
Dianne Hackborn908aecc2012-07-31 16:37:34 -07003221 // the one in them which may be newer.
Romain Guy1c90f032011-05-24 14:59:50 -07003222 config = mView.getResources().getConfiguration();
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003223 if (force || mLastConfiguration.diff(config) != 0) {
Fabrice Di Megliocf128972012-10-16 20:51:12 -07003224 final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3225 final int currentLayoutDirection = config.getLayoutDirection();
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003226 mLastConfiguration.setTo(config);
Fabrice Di Megliob003e282012-10-17 17:20:19 -07003227 if (lastLayoutDirection != currentLayoutDirection &&
3228 mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
Fabrice Di Megliocf128972012-10-16 20:51:12 -07003229 mView.setLayoutDirection(currentLayoutDirection);
3230 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07003231 mView.dispatchConfigurationChanged(config);
3232 }
3233 }
3234 }
John Reck05e85842014-04-23 14:48:28 -07003235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 /**
3237 * Return true if child is an ancestor of parent, (or equal to the parent).
3238 */
Svetoslav Ganove5dfa47d2012-05-08 15:58:32 -07003239 public static boolean isViewDescendantOf(View child, View parent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 if (child == parent) {
3241 return true;
3242 }
3243
3244 final ViewParent theParent = child.getParent();
3245 return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3246 }
3247
Yohei Yukawad2e56472015-07-28 17:00:33 -07003248 private static void forceLayout(View view) {
3249 view.forceLayout();
3250 if (view instanceof ViewGroup) {
3251 ViewGroup group = (ViewGroup) view;
3252 final int count = group.getChildCount();
3253 for (int i = 0; i < count; i++) {
3254 forceLayout(group.getChildAt(i));
3255 }
3256 }
3257 }
3258
Jeff Browna175a5b2012-02-15 19:18:31 -08003259 private final static int MSG_INVALIDATE = 1;
3260 private final static int MSG_INVALIDATE_RECT = 2;
3261 private final static int MSG_DIE = 3;
3262 private final static int MSG_RESIZED = 4;
3263 private final static int MSG_RESIZED_REPORT = 5;
3264 private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
keunyoung30f420f2013-08-02 14:23:10 -07003265 private final static int MSG_DISPATCH_INPUT_EVENT = 7;
Jeff Browna175a5b2012-02-15 19:18:31 -08003266 private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3267 private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
Jeff Browna175a5b2012-02-15 19:18:31 -08003268 private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3269 private final static int MSG_FINISH_INPUT_CONNECTION = 12;
3270 private final static int MSG_CHECK_FOCUS = 13;
3271 private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3272 private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3273 private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3274 private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3275 private final static int MSG_UPDATE_CONFIGURATION = 18;
Svetoslav Ganov42138042012-03-20 11:51:39 -07003276 private final static int MSG_PROCESS_INPUT_EVENTS = 19;
Romain Guyfbb93fa2012-12-03 18:50:35 -08003277 private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
Jorim Jaggi827e0fa2015-05-07 11:41:41 -07003278 private final static int MSG_INVALIDATE_WORLD = 22;
3279 private final static int MSG_WINDOW_MOVED = 23;
3280 private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
3281 private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
Clara Bayarri75e09792015-07-29 16:20:40 +01003282 private final static int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08003283 private final static int MSG_UPDATE_POINTER_ICON = 27;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284
Jeff Browna175a5b2012-02-15 19:18:31 -08003285 final class ViewRootHandler extends Handler {
3286 @Override
3287 public String getMessageName(Message message) {
3288 switch (message.what) {
3289 case MSG_INVALIDATE:
3290 return "MSG_INVALIDATE";
3291 case MSG_INVALIDATE_RECT:
3292 return "MSG_INVALIDATE_RECT";
3293 case MSG_DIE:
3294 return "MSG_DIE";
3295 case MSG_RESIZED:
3296 return "MSG_RESIZED";
3297 case MSG_RESIZED_REPORT:
3298 return "MSG_RESIZED_REPORT";
3299 case MSG_WINDOW_FOCUS_CHANGED:
3300 return "MSG_WINDOW_FOCUS_CHANGED";
keunyoung30f420f2013-08-02 14:23:10 -07003301 case MSG_DISPATCH_INPUT_EVENT:
3302 return "MSG_DISPATCH_INPUT_EVENT";
Jeff Browna175a5b2012-02-15 19:18:31 -08003303 case MSG_DISPATCH_APP_VISIBILITY:
3304 return "MSG_DISPATCH_APP_VISIBILITY";
3305 case MSG_DISPATCH_GET_NEW_SURFACE:
3306 return "MSG_DISPATCH_GET_NEW_SURFACE";
Jeff Browna175a5b2012-02-15 19:18:31 -08003307 case MSG_DISPATCH_KEY_FROM_IME:
3308 return "MSG_DISPATCH_KEY_FROM_IME";
3309 case MSG_FINISH_INPUT_CONNECTION:
3310 return "MSG_FINISH_INPUT_CONNECTION";
3311 case MSG_CHECK_FOCUS:
3312 return "MSG_CHECK_FOCUS";
3313 case MSG_CLOSE_SYSTEM_DIALOGS:
3314 return "MSG_CLOSE_SYSTEM_DIALOGS";
3315 case MSG_DISPATCH_DRAG_EVENT:
3316 return "MSG_DISPATCH_DRAG_EVENT";
3317 case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3318 return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3319 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3320 return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3321 case MSG_UPDATE_CONFIGURATION:
3322 return "MSG_UPDATE_CONFIGURATION";
Jeff Browna175a5b2012-02-15 19:18:31 -08003323 case MSG_PROCESS_INPUT_EVENTS:
3324 return "MSG_PROCESS_INPUT_EVENTS";
Svetoslav Ganov005b83b2012-04-16 18:17:17 -07003325 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3326 return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
Craig Mautner5702d4d2012-06-30 14:10:16 -07003327 case MSG_WINDOW_MOVED:
3328 return "MSG_WINDOW_MOVED";
Michael Wright899d7052014-04-23 17:23:39 -07003329 case MSG_SYNTHESIZE_INPUT_EVENT:
3330 return "MSG_SYNTHESIZE_INPUT_EVENT";
Craig Mautner9c795042014-10-28 19:59:59 -07003331 case MSG_DISPATCH_WINDOW_SHOWN:
3332 return "MSG_DISPATCH_WINDOW_SHOWN";
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08003333 case MSG_UPDATE_POINTER_ICON:
3334 return "MSG_UPDATE_POINTER_ICON";
Jeff Browna175a5b2012-02-15 19:18:31 -08003335 }
3336 return super.getMessageName(message);
Romain Guyf9284692011-07-13 18:46:21 -07003337 }
Romain Guyf9284692011-07-13 18:46:21 -07003338
Jeff Browna175a5b2012-02-15 19:18:31 -08003339 @Override
3340 public void handleMessage(Message msg) {
3341 switch (msg.what) {
3342 case MSG_INVALIDATE:
3343 ((View) msg.obj).invalidate();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 break;
Jeff Browna175a5b2012-02-15 19:18:31 -08003345 case MSG_INVALIDATE_RECT:
3346 final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3347 info.target.invalidate(info.left, info.top, info.right, info.bottom);
Svetoslav Ganovabae2a12012-11-27 16:59:37 -08003348 info.recycle();
Jeff Browna175a5b2012-02-15 19:18:31 -08003349 break;
Jeff Browna175a5b2012-02-15 19:18:31 -08003350 case MSG_PROCESS_INPUT_EVENTS:
3351 mProcessInputEventsScheduled = false;
3352 doProcessInputEvents();
3353 break;
3354 case MSG_DISPATCH_APP_VISIBILITY:
3355 handleAppVisibility(msg.arg1 != 0);
3356 break;
3357 case MSG_DISPATCH_GET_NEW_SURFACE:
3358 handleGetNewSurface();
3359 break;
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003360 case MSG_RESIZED: {
3361 // Recycled in the fall through...
3362 SomeArgs args = (SomeArgs) msg.obj;
Romain Guydfab3632012-10-03 14:53:25 -07003363 if (mWinFrame.equals(args.arg1)
Dianne Hackbornc4aad012013-02-22 15:05:25 -08003364 && mPendingOverscanInsets.equals(args.arg5)
Romain Guydfab3632012-10-03 14:53:25 -07003365 && mPendingContentInsets.equals(args.arg2)
Adrian Roosfa104232014-06-20 16:10:14 -07003366 && mPendingStableInsets.equals(args.arg6)
Romain Guydfab3632012-10-03 14:53:25 -07003367 && mPendingVisibleInsets.equals(args.arg3)
Filip Gruszczynski2217f612015-05-26 11:32:08 -07003368 && mPendingOutsets.equals(args.arg7)
Jorim Jaggi0fe356e2016-01-05 14:43:25 +01003369 && mPendingBackDropFrame.equals(args.arg8)
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08003370 && args.arg4 == null
3371 && args.argi1 == 0) {
Jeff Browna175a5b2012-02-15 19:18:31 -08003372 break;
Romain Guycdb86672010-03-18 18:54:50 -07003373 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003374 } // fall through...
Jeff Browna175a5b2012-02-15 19:18:31 -08003375 case MSG_RESIZED_REPORT:
3376 if (mAdded) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003377 SomeArgs args = (SomeArgs) msg.obj;
3378
3379 Configuration config = (Configuration) args.arg4;
Jeff Browna175a5b2012-02-15 19:18:31 -08003380 if (config != null) {
3381 updateConfiguration(config, false);
3382 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003383
3384 mWinFrame.set((Rect) args.arg1);
Dianne Hackbornc4aad012013-02-22 15:05:25 -08003385 mPendingOverscanInsets.set((Rect) args.arg5);
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003386 mPendingContentInsets.set((Rect) args.arg2);
Adrian Roosfa104232014-06-20 16:10:14 -07003387 mPendingStableInsets.set((Rect) args.arg6);
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003388 mPendingVisibleInsets.set((Rect) args.arg3);
Filip Gruszczynski2217f612015-05-26 11:32:08 -07003389 mPendingOutsets.set((Rect) args.arg7);
Jorim Jaggia7262a82015-11-03 15:15:40 +01003390 mPendingBackDropFrame.set((Rect) args.arg8);
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08003391 mForceNextWindowRelayout = args.argi1 != 0;
Svetoslav Ganov758143e2012-08-06 16:40:27 -07003392
3393 args.recycle();
3394
Jeff Browna175a5b2012-02-15 19:18:31 -08003395 if (msg.what == MSG_RESIZED_REPORT) {
3396 mReportNextDraw = true;
3397 }
Romain Guy59a12ca2011-06-09 17:48:21 -07003398
Yohei Yukawad2e56472015-07-28 17:00:33 -07003399 if (mView != null) {
3400 forceLayout(mView);
3401 }
3402
Jeff Browna175a5b2012-02-15 19:18:31 -08003403 requestLayout();
3404 }
3405 break;
Craig Mautner5702d4d2012-06-30 14:10:16 -07003406 case MSG_WINDOW_MOVED:
3407 if (mAdded) {
3408 final int w = mWinFrame.width();
3409 final int h = mWinFrame.height();
3410 final int l = msg.arg1;
3411 final int t = msg.arg2;
3412 mWinFrame.left = l;
3413 mWinFrame.right = l + w;
3414 mWinFrame.top = t;
3415 mWinFrame.bottom = t + h;
3416
Jorim Jaggia7262a82015-11-03 15:15:40 +01003417 mPendingBackDropFrame.set(mWinFrame);
3418
Jorim Jaggi844e1712016-01-13 17:39:25 -08003419 // Suppress layouts during resizing - a correct layout will happen when resizing
3420 // is done, and this just increases system load.
Jorim Jaggi2e95a482016-01-14 17:36:55 -08003421 boolean isDockedDivider = mWindowAttributes.type == TYPE_DOCK_DIVIDER;
3422 boolean suppress = (mDragResizing && mResizeMode == RESIZE_MODE_DOCKED_DIVIDER)
3423 || isDockedDivider;
Jorim Jaggi844e1712016-01-13 17:39:25 -08003424 if (!suppress) {
3425 if (mView != null) {
3426 forceLayout(mView);
3427 }
3428 requestLayout();
Jorim Jaggi2e95a482016-01-14 17:36:55 -08003429 } else {
3430 maybeHandleWindowMove(mWinFrame);
Yohei Yukawad2e56472015-07-28 17:00:33 -07003431 }
Craig Mautner5702d4d2012-06-30 14:10:16 -07003432 }
3433 break;
Jeff Browna175a5b2012-02-15 19:18:31 -08003434 case MSG_WINDOW_FOCUS_CHANGED: {
3435 if (mAdded) {
3436 boolean hasWindowFocus = msg.arg1 != 0;
3437 mAttachInfo.mHasWindowFocus = hasWindowFocus;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438
Jeff Browna175a5b2012-02-15 19:18:31 -08003439 profileRendering(hasWindowFocus);
3440
3441 if (hasWindowFocus) {
3442 boolean inTouchMode = msg.arg2 != 0;
3443 ensureTouchModeLocally(inTouchMode);
3444
Romain Guye55945e2013-04-04 15:26:04 -07003445 if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
Jeff Browna175a5b2012-02-15 19:18:31 -08003446 mFullRedrawNeeded = true;
Dianne Hackborn64825172011-03-02 21:32:58 -08003447 try {
Alan Viveretteccb11e12014-07-08 16:04:02 -07003448 final WindowManager.LayoutParams lp = mWindowAttributes;
Alan Viverette49a22e82014-07-12 20:01:27 -07003449 final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
Romain Guy3696779b2013-01-28 14:04:07 -08003450 mAttachInfo.mHardwareRenderer.initializeIfNeeded(
Alan Viverette50210d92015-05-14 18:05:36 -07003451 mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
Igor Murashkina86ab6402013-08-30 12:58:36 -07003452 } catch (OutOfResourcesException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003453 Log.e(mTag, "OutOfResourcesException locking surface", e);
Jeff Browna175a5b2012-02-15 19:18:31 -08003454 try {
Jeff Brown98365d72012-08-19 20:30:52 -07003455 if (!mWindowSession.outOfMemory(mWindow)) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003456 Slog.w(mTag, "No processes killed for memory; killing self");
Jeff Browna175a5b2012-02-15 19:18:31 -08003457 Process.killProcess(Process.myPid());
3458 }
3459 } catch (RemoteException ex) {
Dianne Hackborn64825172011-03-02 21:32:58 -08003460 }
Jeff Browna175a5b2012-02-15 19:18:31 -08003461 // Retry in a bit.
3462 sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3463 return;
Dianne Hackborn64825172011-03-02 21:32:58 -08003464 }
Dianne Hackborn64825172011-03-02 21:32:58 -08003465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 }
Romain Guy8506ab42009-06-11 17:35:47 -07003467
Jeff Browna175a5b2012-02-15 19:18:31 -08003468 mLastWasImTarget = WindowManager.LayoutParams
3469 .mayUseInputMethod(mWindowAttributes.flags);
Romain Guy8506ab42009-06-11 17:35:47 -07003470
Jeff Browna175a5b2012-02-15 19:18:31 -08003471 InputMethodManager imm = InputMethodManager.peekInstance();
Yohei Yukawa5f059652015-05-14 22:16:41 -07003472 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3473 imm.onPreWindowFocus(mView, hasWindowFocus);
3474 }
Jeff Browna175a5b2012-02-15 19:18:31 -08003475 if (mView != null) {
Jeff Browna175a5b2012-02-15 19:18:31 -08003476 mAttachInfo.mKeyDispatchState.reset();
3477 mView.dispatchWindowFocusChanged(hasWindowFocus);
Dianne Hackborn961cae92013-03-20 14:59:43 -07003478 mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003480
Jeff Browna175a5b2012-02-15 19:18:31 -08003481 // Note: must be done after the focus change callbacks,
3482 // so all of the view state is set up correctly.
3483 if (hasWindowFocus) {
keunyoung30f420f2013-08-02 14:23:10 -07003484 if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
Yohei Yukawa5f059652015-05-14 22:16:41 -07003485 imm.onPostWindowFocus(mView, mView.findFocus(),
Jeff Browna175a5b2012-02-15 19:18:31 -08003486 mWindowAttributes.softInputMode,
3487 !mHasHadWindowFocus, mWindowAttributes.flags);
3488 }
3489 // Clear the forward bit. We can just do this directly, since
3490 // the window manager doesn't care about it.
3491 mWindowAttributes.softInputMode &=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
Jeff Browna175a5b2012-02-15 19:18:31 -08003493 ((WindowManager.LayoutParams)mView.getLayoutParams())
3494 .softInputMode &=
3495 ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3496 mHasHadWindowFocus = true;
Jun Mukai347e5d42015-12-03 01:13:31 -08003497 } else if (mCapturingView != null) {
3498 releasePointerCapture(mCapturingView);
Jeff Browna175a5b2012-02-15 19:18:31 -08003499 }
svetoslavganov75986cf2009-05-14 22:28:01 -07003500 }
Jeff Browna175a5b2012-02-15 19:18:31 -08003501 } break;
3502 case MSG_DIE:
3503 doDie();
3504 break;
keunyoung30f420f2013-08-02 14:23:10 -07003505 case MSG_DISPATCH_INPUT_EVENT: {
Jae Seo6a6059a2014-04-17 21:35:29 -07003506 SomeArgs args = (SomeArgs)msg.obj;
3507 InputEvent event = (InputEvent)args.arg1;
3508 InputEventReceiver receiver = (InputEventReceiver)args.arg2;
3509 enqueueInputEvent(event, receiver, 0, true);
3510 args.recycle();
Jeff Browna175a5b2012-02-15 19:18:31 -08003511 } break;
Michael Wright899d7052014-04-23 17:23:39 -07003512 case MSG_SYNTHESIZE_INPUT_EVENT: {
3513 InputEvent event = (InputEvent)msg.obj;
3514 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
3515 } break;
Jeff Browna175a5b2012-02-15 19:18:31 -08003516 case MSG_DISPATCH_KEY_FROM_IME: {
3517 if (LOCAL_LOGV) Log.v(
3518 TAG, "Dispatching key "
3519 + msg.obj + " from IME to " + mView);
3520 KeyEvent event = (KeyEvent)msg.obj;
3521 if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3522 // The IME is trying to say this event is from the
3523 // system! Bad bad bad!
3524 //noinspection UnusedAssignment
Michael Wright899d7052014-04-23 17:23:39 -07003525 event = KeyEvent.changeFlags(event, event.getFlags() &
3526 ~KeyEvent.FLAG_FROM_SYSTEM);
Jeff Browna175a5b2012-02-15 19:18:31 -08003527 }
3528 enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3529 } break;
3530 case MSG_FINISH_INPUT_CONNECTION: {
3531 InputMethodManager imm = InputMethodManager.peekInstance();
3532 if (imm != null) {
3533 imm.reportFinishInputConnection((InputConnection)msg.obj);
3534 }
3535 } break;
3536 case MSG_CHECK_FOCUS: {
3537 InputMethodManager imm = InputMethodManager.peekInstance();
3538 if (imm != null) {
3539 imm.checkFocus();
3540 }
3541 } break;
3542 case MSG_CLOSE_SYSTEM_DIALOGS: {
3543 if (mView != null) {
3544 mView.onCloseSystemDialogs((String)msg.obj);
3545 }
3546 } break;
3547 case MSG_DISPATCH_DRAG_EVENT:
3548 case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3549 DragEvent event = (DragEvent)msg.obj;
3550 event.mLocalState = mLocalDragState; // only present when this app called startDrag()
3551 handleDragEvent(event);
3552 } break;
3553 case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
Romain Guyfbb93fa2012-12-03 18:50:35 -08003554 handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
Jeff Browna175a5b2012-02-15 19:18:31 -08003555 } break;
3556 case MSG_UPDATE_CONFIGURATION: {
3557 Configuration config = (Configuration)msg.obj;
3558 if (config.isOtherSeqNewer(mLastConfiguration)) {
3559 config = mLastConfiguration;
3560 }
3561 updateConfiguration(config, false);
3562 } break;
Svetoslav Ganov005b83b2012-04-16 18:17:17 -07003563 case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07003564 setAccessibilityFocus(null, null);
Svetoslav Ganov005b83b2012-04-16 18:17:17 -07003565 } break;
Dianne Hackborna53de062012-05-08 18:53:51 -07003566 case MSG_INVALIDATE_WORLD: {
Romain Guyf84208f2012-09-13 22:50:18 -07003567 if (mView != null) {
3568 invalidateWorld(mView);
3569 }
Dianne Hackborna53de062012-05-08 18:53:51 -07003570 } break;
Craig Mautner9c795042014-10-28 19:59:59 -07003571 case MSG_DISPATCH_WINDOW_SHOWN: {
3572 handleDispatchWindowShown();
Clara Bayarri75e09792015-07-29 16:20:40 +01003573 } break;
3574 case MSG_REQUEST_KEYBOARD_SHORTCUTS: {
3575 IResultReceiver receiver = (IResultReceiver) msg.obj;
3576 handleRequestKeyboardShortcuts(receiver);
3577 } break;
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08003578 case MSG_UPDATE_POINTER_ICON: {
3579 MotionEvent event = (MotionEvent) msg.obj;
3580 resetPointerIcon(event);
3581 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
3584 }
Romain Guy51e4d4d2012-03-15 18:30:47 -07003585
Jeff Browna175a5b2012-02-15 19:18:31 -08003586 final ViewRootHandler mHandler = new ViewRootHandler();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07003587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 /**
3589 * Something in the current window tells us we need to change the touch mode. For
3590 * example, we are not in touch mode, and the user touches the screen.
3591 *
3592 * If the touch mode has changed, tell the window manager, and handle it locally.
3593 *
3594 * @param inTouchMode Whether we want to be in touch mode.
3595 * @return True if the touch mode changed and focus changed was changed as a result
3596 */
3597 boolean ensureTouchMode(boolean inTouchMode) {
3598 if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3599 + "touch mode is " + mAttachInfo.mInTouchMode);
3600 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3601
3602 // tell the window manager
3603 try {
Matt Wud6bc96d2016-01-14 12:59:24 -08003604 mWindowSession.setInTouchMode(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 } catch (RemoteException e) {
3606 throw new RuntimeException(e);
3607 }
3608
3609 // handle the change
Romain Guy2d4cff62010-04-09 15:39:00 -07003610 return ensureTouchModeLocally(inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
3612
3613 /**
3614 * Ensure that the touch mode for this window is set, and if it is changing,
3615 * take the appropriate action.
3616 * @param inTouchMode Whether we want to be in touch mode.
3617 * @return True if the touch mode changed and focus changed was changed as a result
3618 */
Romain Guy2d4cff62010-04-09 15:39:00 -07003619 private boolean ensureTouchModeLocally(boolean inTouchMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3621 + "touch mode is " + mAttachInfo.mInTouchMode);
3622
3623 if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3624
3625 mAttachInfo.mInTouchMode = inTouchMode;
3626 mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3627
Romain Guy2d4cff62010-04-09 15:39:00 -07003628 return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 }
3630
3631 private boolean enterTouchMode() {
Alan Viveretteed7821a2013-07-24 15:49:23 -07003632 if (mView != null && mView.hasFocus()) {
3633 // note: not relying on mFocusedView here because this could
3634 // be when the window is first being added, and mFocused isn't
3635 // set yet.
3636 final View focused = mView.findFocus();
3637 if (focused != null && !focused.isFocusableInTouchMode()) {
3638 final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
3639 if (ancestorToTakeFocus != null) {
3640 // there is an ancestor that wants focus after its
3641 // descendants that is focusable in touch mode.. give it
3642 // focus
3643 return ancestorToTakeFocus.requestFocus();
3644 } else {
Alan Viverette973f3b42013-08-13 16:57:28 -07003645 // There's nothing to focus. Clear and propagate through the
3646 // hierarchy, but don't attempt to place new focus.
Alan Viverette223622a2013-12-17 13:29:02 -08003647 focused.clearFocusInternal(null, true, false);
Alan Viveretteed7821a2013-07-24 15:49:23 -07003648 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 }
3651 }
3652 return false;
3653 }
3654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 /**
3656 * Find an ancestor of focused that wants focus after its descendants and is
3657 * focusable in touch mode.
3658 * @param focused The currently focused view.
3659 * @return An appropriate view, or null if no such view exists.
3660 */
Romain Guya998dff2012-03-23 18:58:36 -07003661 private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 ViewParent parent = focused.getParent();
3663 while (parent instanceof ViewGroup) {
3664 final ViewGroup vgParent = (ViewGroup) parent;
3665 if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3666 && vgParent.isFocusableInTouchMode()) {
3667 return vgParent;
3668 }
3669 if (vgParent.isRootNamespace()) {
3670 return null;
3671 } else {
3672 parent = vgParent.getParent();
3673 }
3674 }
3675 return null;
3676 }
3677
3678 private boolean leaveTouchMode() {
3679 if (mView != null) {
3680 if (mView.hasFocus()) {
Svetoslav Ganov149567f2013-01-08 15:23:34 -08003681 View focusedView = mView.findFocus();
3682 if (!(focusedView instanceof ViewGroup)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 // some view has focus, let it keep it
Svetoslav Ganovcf8a3b82012-04-30 16:49:59 -07003684 return false;
Svetoslav Ganov149567f2013-01-08 15:23:34 -08003685 } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3687 // some view group has focus, and doesn't prefer its children
3688 // over itself for focus, so let them keep it.
Svetoslav Ganovcf8a3b82012-04-30 16:49:59 -07003689 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 }
3691 }
Svetoslav Ganovcf8a3b82012-04-30 16:49:59 -07003692
3693 // find the best view to give focus to in this brave new non-touch-mode
3694 // world
3695 final View focused = focusSearch(null, View.FOCUS_DOWN);
3696 if (focused != null) {
3697 return focused.requestFocus(View.FOCUS_DOWN);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 }
3699 }
3700 return false;
3701 }
3702
Jeff Brownf9e989d2013-04-04 23:04:03 -07003703 /**
3704 * Base class for implementing a stage in the chain of responsibility
3705 * for processing input events.
3706 * <p>
3707 * Events are delivered to the stage by the {@link #deliver} method. The stage
3708 * then has the choice of finishing the event or forwarding it to the next stage.
3709 * </p>
3710 */
3711 abstract class InputStage {
3712 private final InputStage mNext;
3713
3714 protected static final int FORWARD = 0;
3715 protected static final int FINISH_HANDLED = 1;
3716 protected static final int FINISH_NOT_HANDLED = 2;
3717
3718 /**
3719 * Creates an input stage.
3720 * @param next The next stage to which events should be forwarded.
3721 */
3722 public InputStage(InputStage next) {
3723 mNext = next;
3724 }
3725
3726 /**
3727 * Delivers an event to be processed.
3728 */
3729 public final void deliver(QueuedInputEvent q) {
3730 if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3731 forward(q);
Michael Wright17d28ca2013-10-31 17:47:45 -07003732 } else if (shouldDropInputEvent(q)) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07003733 finish(q, false);
3734 } else {
3735 apply(q, onProcess(q));
3736 }
3737 }
3738
3739 /**
3740 * Marks the the input event as finished then forwards it to the next stage.
3741 */
3742 protected void finish(QueuedInputEvent q, boolean handled) {
3743 q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3744 if (handled) {
3745 q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3746 }
3747 forward(q);
3748 }
3749
3750 /**
3751 * Forwards the event to the next stage.
3752 */
3753 protected void forward(QueuedInputEvent q) {
3754 onDeliverToNext(q);
3755 }
3756
3757 /**
3758 * Applies a result code from {@link #onProcess} to the specified event.
3759 */
3760 protected void apply(QueuedInputEvent q, int result) {
3761 if (result == FORWARD) {
3762 forward(q);
3763 } else if (result == FINISH_HANDLED) {
3764 finish(q, true);
3765 } else if (result == FINISH_NOT_HANDLED) {
3766 finish(q, false);
3767 } else {
3768 throw new IllegalArgumentException("Invalid result: " + result);
3769 }
3770 }
3771
3772 /**
3773 * Called when an event is ready to be processed.
3774 * @return A result code indicating how the event was handled.
3775 */
3776 protected int onProcess(QueuedInputEvent q) {
3777 return FORWARD;
3778 }
3779
3780 /**
3781 * Called when an event is being delivered to the next stage.
3782 */
3783 protected void onDeliverToNext(QueuedInputEvent q) {
Michael Wright06a79252014-05-05 17:45:29 -07003784 if (DEBUG_INPUT_STAGES) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003785 Log.v(mTag, "Done with " + getClass().getSimpleName() + ". " + q);
Michael Wright06a79252014-05-05 17:45:29 -07003786 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07003787 if (mNext != null) {
3788 mNext.deliver(q);
3789 } else {
3790 finishInputEvent(q);
3791 }
3792 }
Jeff Brown5182c782013-10-15 20:31:52 -07003793
Michael Wright17d28ca2013-10-31 17:47:45 -07003794 protected boolean shouldDropInputEvent(QueuedInputEvent q) {
3795 if (mView == null || !mAdded) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003796 Slog.w(mTag, "Dropping event due to root view being removed: " + q.mEvent);
Michael Wright17d28ca2013-10-31 17:47:45 -07003797 return true;
George Mount41725de2015-04-09 08:23:05 -07003798 } else if ((!mAttachInfo.mHasWindowFocus
3799 && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped
Daniel Koulomzin087ae472015-12-16 17:52:25 -05003800 || mIsAmbientMode || (mPausedForTransition && !isBack(q.mEvent))) {
Wale Ogunwalec3672cd2014-11-05 15:17:35 -08003801 // This is a focus event and the window doesn't currently have input focus or
3802 // has stopped. This could be an event that came back from the previous stage
3803 // but the window has lost focus or stopped in the meantime.
3804 if (isTerminalInputEvent(q.mEvent)) {
3805 // Don't drop terminal input events, however mark them as canceled.
3806 q.mEvent.cancel();
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003807 Slog.w(mTag, "Cancelling event due to no window focus: " + q.mEvent);
Wale Ogunwalec3672cd2014-11-05 15:17:35 -08003808 return false;
3809 }
3810
3811 // Drop non-terminal input events.
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08003812 Slog.w(mTag, "Dropping event due to no window focus: " + q.mEvent);
Michael Wright17d28ca2013-10-31 17:47:45 -07003813 return true;
3814 }
3815 return false;
3816 }
3817
Jeff Brown5182c782013-10-15 20:31:52 -07003818 void dump(String prefix, PrintWriter writer) {
3819 if (mNext != null) {
3820 mNext.dump(prefix, writer);
3821 }
3822 }
George Mount41725de2015-04-09 08:23:05 -07003823
3824 private boolean isBack(InputEvent event) {
3825 if (event instanceof KeyEvent) {
3826 return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;
3827 } else {
3828 return false;
3829 }
3830 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07003831 }
3832
3833 /**
3834 * Base class for implementing an input pipeline stage that supports
3835 * asynchronous and out-of-order processing of input events.
3836 * <p>
3837 * In addition to what a normal input stage can do, an asynchronous
3838 * input stage may also defer an input event that has been delivered to it
3839 * and finish or forward it later.
3840 * </p>
3841 */
3842 abstract class AsyncInputStage extends InputStage {
3843 private final String mTraceCounter;
3844
3845 private QueuedInputEvent mQueueHead;
3846 private QueuedInputEvent mQueueTail;
3847 private int mQueueLength;
3848
3849 protected static final int DEFER = 3;
3850
3851 /**
3852 * Creates an asynchronous input stage.
3853 * @param next The next stage to which events should be forwarded.
3854 * @param traceCounter The name of a counter to record the size of
3855 * the queue of pending events.
3856 */
3857 public AsyncInputStage(InputStage next, String traceCounter) {
3858 super(next);
3859 mTraceCounter = traceCounter;
3860 }
3861
3862 /**
3863 * Marks the event as deferred, which is to say that it will be handled
3864 * asynchronously. The caller is responsible for calling {@link #forward}
3865 * or {@link #finish} later when it is done handling the event.
3866 */
3867 protected void defer(QueuedInputEvent q) {
3868 q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3869 enqueue(q);
3870 }
3871
3872 @Override
3873 protected void forward(QueuedInputEvent q) {
3874 // Clear the deferred flag.
3875 q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3876
3877 // Fast path if the queue is empty.
3878 QueuedInputEvent curr = mQueueHead;
3879 if (curr == null) {
3880 super.forward(q);
3881 return;
3882 }
3883
3884 // Determine whether the event must be serialized behind any others
3885 // before it can be delivered to the next stage. This is done because
3886 // deferred events might be handled out of order by the stage.
3887 final int deviceId = q.mEvent.getDeviceId();
3888 QueuedInputEvent prev = null;
3889 boolean blocked = false;
3890 while (curr != null && curr != q) {
3891 if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
3892 blocked = true;
3893 }
3894 prev = curr;
3895 curr = curr.mNext;
3896 }
3897
3898 // If the event is blocked, then leave it in the queue to be delivered later.
3899 // Note that the event might not yet be in the queue if it was not previously
3900 // deferred so we will enqueue it if needed.
3901 if (blocked) {
3902 if (curr == null) {
3903 enqueue(q);
3904 }
3905 return;
3906 }
3907
3908 // The event is not blocked. Deliver it immediately.
3909 if (curr != null) {
3910 curr = curr.mNext;
3911 dequeue(q, prev);
3912 }
3913 super.forward(q);
3914
3915 // Dequeuing this event may have unblocked successors. Deliver them.
3916 while (curr != null) {
3917 if (deviceId == curr.mEvent.getDeviceId()) {
3918 if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
3919 break;
3920 }
3921 QueuedInputEvent next = curr.mNext;
3922 dequeue(curr, prev);
3923 super.forward(curr);
3924 curr = next;
3925 } else {
3926 prev = curr;
3927 curr = curr.mNext;
3928 }
3929 }
3930 }
3931
3932 @Override
3933 protected void apply(QueuedInputEvent q, int result) {
3934 if (result == DEFER) {
3935 defer(q);
3936 } else {
3937 super.apply(q, result);
3938 }
3939 }
3940
3941 private void enqueue(QueuedInputEvent q) {
3942 if (mQueueTail == null) {
3943 mQueueHead = q;
3944 mQueueTail = q;
3945 } else {
3946 mQueueTail.mNext = q;
3947 mQueueTail = q;
3948 }
3949
3950 mQueueLength += 1;
3951 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3952 }
3953
3954 private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
3955 if (prev == null) {
3956 mQueueHead = q.mNext;
3957 } else {
3958 prev.mNext = q.mNext;
3959 }
3960 if (mQueueTail == q) {
3961 mQueueTail = prev;
3962 }
3963 q.mNext = null;
3964
3965 mQueueLength -= 1;
3966 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3967 }
Jeff Brown5182c782013-10-15 20:31:52 -07003968
3969 @Override
3970 void dump(String prefix, PrintWriter writer) {
3971 writer.print(prefix);
3972 writer.print(getClass().getName());
3973 writer.print(": mQueueLength=");
3974 writer.println(mQueueLength);
3975
3976 super.dump(prefix, writer);
3977 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07003978 }
3979
3980 /**
3981 * Delivers pre-ime input events to a native activity.
3982 * Does not support pointer events.
3983 */
Michael Wrighta44dd262013-04-10 21:12:00 -07003984 final class NativePreImeInputStage extends AsyncInputStage
3985 implements InputQueue.FinishedInputEventCallback {
Jeff Brownf9e989d2013-04-04 23:04:03 -07003986 public NativePreImeInputStage(InputStage next, String traceCounter) {
3987 super(next, traceCounter);
3988 }
3989
3990 @Override
3991 protected int onProcess(QueuedInputEvent q) {
Michael Wrighta44dd262013-04-10 21:12:00 -07003992 if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
3993 mInputQueue.sendInputEvent(q.mEvent, q, true, this);
3994 return DEFER;
3995 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07003996 return FORWARD;
3997 }
Michael Wrighta44dd262013-04-10 21:12:00 -07003998
3999 @Override
4000 public void onFinishedInputEvent(Object token, boolean handled) {
4001 QueuedInputEvent q = (QueuedInputEvent)token;
4002 if (handled) {
4003 finish(q, true);
4004 return;
4005 }
4006 forward(q);
4007 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004008 }
4009
4010 /**
4011 * Delivers pre-ime input events to the view hierarchy.
4012 * Does not support pointer events.
4013 */
4014 final class ViewPreImeInputStage extends InputStage {
4015 public ViewPreImeInputStage(InputStage next) {
4016 super(next);
4017 }
4018
4019 @Override
4020 protected int onProcess(QueuedInputEvent q) {
Jeff Brown481c1572012-03-09 14:41:15 -08004021 if (q.mEvent instanceof KeyEvent) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004022 return processKeyEvent(q);
4023 }
4024 return FORWARD;
4025 }
4026
4027 private int processKeyEvent(QueuedInputEvent q) {
4028 final KeyEvent event = (KeyEvent)q.mEvent;
4029 if (mView.dispatchKeyEventPreIme(event)) {
4030 return FINISH_HANDLED;
4031 }
4032 return FORWARD;
4033 }
4034 }
4035
4036 /**
4037 * Delivers input events to the ime.
4038 * Does not support pointer events.
4039 */
4040 final class ImeInputStage extends AsyncInputStage
4041 implements InputMethodManager.FinishedInputEventCallback {
4042 public ImeInputStage(InputStage next, String traceCounter) {
4043 super(next, traceCounter);
4044 }
4045
4046 @Override
4047 protected int onProcess(QueuedInputEvent q) {
keunyoung30f420f2013-08-02 14:23:10 -07004048 if (mLastWasImTarget && !isInLocalFocusMode()) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004049 InputMethodManager imm = InputMethodManager.peekInstance();
4050 if (imm != null) {
4051 final InputEvent event = q.mEvent;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004052 if (DEBUG_IMF) Log.v(mTag, "Sending input event to IME: " + event);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004053 int result = imm.dispatchInputEvent(event, q, this, mHandler);
4054 if (result == InputMethodManager.DISPATCH_HANDLED) {
4055 return FINISH_HANDLED;
4056 } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) {
Adam Lesinskic0f6eed2013-10-28 16:03:19 -07004057 // The IME could not handle it, so skip along to the next InputStage
4058 return FORWARD;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004059 } else {
4060 return DEFER; // callback will be invoked later
4061 }
4062 }
4063 }
4064 return FORWARD;
4065 }
4066
4067 @Override
4068 public void onFinishedInputEvent(Object token, boolean handled) {
4069 QueuedInputEvent q = (QueuedInputEvent)token;
4070 if (handled) {
4071 finish(q, true);
4072 return;
4073 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004074 forward(q);
4075 }
4076 }
4077
4078 /**
4079 * Performs early processing of post-ime input events.
4080 */
4081 final class EarlyPostImeInputStage extends InputStage {
4082 public EarlyPostImeInputStage(InputStage next) {
4083 super(next);
4084 }
4085
4086 @Override
4087 protected int onProcess(QueuedInputEvent q) {
4088 if (q.mEvent instanceof KeyEvent) {
4089 return processKeyEvent(q);
Jeff Brown4952dfd2011-11-30 19:23:22 -08004090 } else {
Jeff Brown481c1572012-03-09 14:41:15 -08004091 final int source = q.mEvent.getSource();
4092 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004093 return processPointerEvent(q);
Jeff Brown481c1572012-03-09 14:41:15 -08004094 }
Jeff Brown4952dfd2011-11-30 19:23:22 -08004095 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004096 return FORWARD;
4097 }
4098
4099 private int processKeyEvent(QueuedInputEvent q) {
4100 final KeyEvent event = (KeyEvent)q.mEvent;
4101
4102 // If the key's purpose is to exit touch mode then we consume it
4103 // and consider it handled.
4104 if (checkForLeavingTouchModeAndConsume(event)) {
4105 return FINISH_HANDLED;
4106 }
4107
4108 // Make sure the fallback event policy sees all keys that will be
4109 // delivered to the view hierarchy.
4110 mFallbackEventHandler.preDispatchKeyEvent(event);
4111 return FORWARD;
4112 }
4113
4114 private int processPointerEvent(QueuedInputEvent q) {
4115 final MotionEvent event = (MotionEvent)q.mEvent;
4116
4117 // Translate the pointer event for compatibility, if needed.
4118 if (mTranslator != null) {
4119 mTranslator.translateEventInScreenToAppWindow(event);
4120 }
4121
4122 // Enter touch mode on down or scroll.
4123 final int action = event.getAction();
4124 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
4125 ensureTouchMode(true);
4126 }
4127
4128 // Offset the scroll position.
4129 if (mCurScrollY != 0) {
4130 event.offsetLocation(0, mCurScrollY);
4131 }
4132
4133 // Remember the touch position for possible drag-initiation.
4134 if (event.isTouchEvent()) {
4135 mLastTouchPoint.x = event.getRawX();
4136 mLastTouchPoint.y = event.getRawY();
Vladislav Kaznacheevba761122016-01-22 12:09:45 -08004137 mLastTouchSource = event.getSource();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004138 }
4139 return FORWARD;
Jeff Brown4952dfd2011-11-30 19:23:22 -08004140 }
4141 }
4142
Jeff Brownf9e989d2013-04-04 23:04:03 -07004143 /**
4144 * Delivers post-ime input events to a native activity.
4145 */
Michael Wrighta44dd262013-04-10 21:12:00 -07004146 final class NativePostImeInputStage extends AsyncInputStage
4147 implements InputQueue.FinishedInputEventCallback {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004148 public NativePostImeInputStage(InputStage next, String traceCounter) {
4149 super(next, traceCounter);
4150 }
4151
4152 @Override
4153 protected int onProcess(QueuedInputEvent q) {
Michael Wrighta44dd262013-04-10 21:12:00 -07004154 if (mInputQueue != null) {
4155 mInputQueue.sendInputEvent(q.mEvent, q, false, this);
4156 return DEFER;
4157 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004158 return FORWARD;
4159 }
Michael Wrighta44dd262013-04-10 21:12:00 -07004160
4161 @Override
4162 public void onFinishedInputEvent(Object token, boolean handled) {
4163 QueuedInputEvent q = (QueuedInputEvent)token;
4164 if (handled) {
4165 finish(q, true);
4166 return;
4167 }
4168 forward(q);
4169 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004170 }
4171
4172 /**
4173 * Delivers post-ime input events to the view hierarchy.
4174 */
4175 final class ViewPostImeInputStage extends InputStage {
4176 public ViewPostImeInputStage(InputStage next) {
4177 super(next);
4178 }
4179
4180 @Override
4181 protected int onProcess(QueuedInputEvent q) {
Jeff Brown29c0ed22013-01-14 13:50:37 -08004182 if (q.mEvent instanceof KeyEvent) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004183 return processKeyEvent(q);
Jeff Brown29c0ed22013-01-14 13:50:37 -08004184 } else {
4185 final int source = q.mEvent.getSource();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004186 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4187 return processPointerEvent(q);
4188 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4189 return processTrackballEvent(q);
Jeff Brown29c0ed22013-01-14 13:50:37 -08004190 } else {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004191 return processGenericMotionEvent(q);
Jeff Brown29c0ed22013-01-14 13:50:37 -08004192 }
4193 }
Jeff Brown29c0ed22013-01-14 13:50:37 -08004194 }
Jeff Brown29c0ed22013-01-14 13:50:37 -08004195
Michael Wright9d744c72014-02-18 21:27:42 -08004196 @Override
4197 protected void onDeliverToNext(QueuedInputEvent q) {
4198 if (mUnbufferedInputDispatch
4199 && q.mEvent instanceof MotionEvent
4200 && ((MotionEvent)q.mEvent).isTouchEvent()
4201 && isTerminalInputEvent(q.mEvent)) {
4202 mUnbufferedInputDispatch = false;
4203 scheduleConsumeBatchedInput();
4204 }
4205 super.onDeliverToNext(q);
4206 }
4207
Jeff Brownf9e989d2013-04-04 23:04:03 -07004208 private int processKeyEvent(QueuedInputEvent q) {
4209 final KeyEvent event = (KeyEvent)q.mEvent;
4210
4211 // Deliver the key to the view hierarchy.
4212 if (mView.dispatchKeyEvent(event)) {
4213 return FINISH_HANDLED;
Jeff Brown21bc5c92011-02-28 18:27:14 -08004214 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004215
Michael Wright17d28ca2013-10-31 17:47:45 -07004216 if (shouldDropInputEvent(q)) {
4217 return FINISH_NOT_HANDLED;
4218 }
4219
Jeff Brownf9e989d2013-04-04 23:04:03 -07004220 // If the Control modifier is held, try to interpret the key as a shortcut.
4221 if (event.getAction() == KeyEvent.ACTION_DOWN
4222 && event.isCtrlPressed()
4223 && event.getRepeatCount() == 0
4224 && !KeyEvent.isModifierKey(event.getKeyCode())) {
4225 if (mView.dispatchKeyShortcutEvent(event)) {
4226 return FINISH_HANDLED;
4227 }
Michael Wright17d28ca2013-10-31 17:47:45 -07004228 if (shouldDropInputEvent(q)) {
4229 return FINISH_NOT_HANDLED;
4230 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004231 }
4232
4233 // Apply the fallback event policy.
4234 if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4235 return FINISH_HANDLED;
4236 }
Michael Wright17d28ca2013-10-31 17:47:45 -07004237 if (shouldDropInputEvent(q)) {
4238 return FINISH_NOT_HANDLED;
4239 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004240
4241 // Handle automatic focus changes.
4242 if (event.getAction() == KeyEvent.ACTION_DOWN) {
4243 int direction = 0;
4244 switch (event.getKeyCode()) {
4245 case KeyEvent.KEYCODE_DPAD_LEFT:
4246 if (event.hasNoModifiers()) {
4247 direction = View.FOCUS_LEFT;
4248 }
4249 break;
4250 case KeyEvent.KEYCODE_DPAD_RIGHT:
4251 if (event.hasNoModifiers()) {
4252 direction = View.FOCUS_RIGHT;
4253 }
4254 break;
4255 case KeyEvent.KEYCODE_DPAD_UP:
4256 if (event.hasNoModifiers()) {
4257 direction = View.FOCUS_UP;
4258 }
4259 break;
4260 case KeyEvent.KEYCODE_DPAD_DOWN:
4261 if (event.hasNoModifiers()) {
4262 direction = View.FOCUS_DOWN;
4263 }
4264 break;
4265 case KeyEvent.KEYCODE_TAB:
4266 if (event.hasNoModifiers()) {
4267 direction = View.FOCUS_FORWARD;
4268 } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4269 direction = View.FOCUS_BACKWARD;
4270 }
4271 break;
4272 }
4273 if (direction != 0) {
4274 View focused = mView.findFocus();
4275 if (focused != null) {
4276 View v = focused.focusSearch(direction);
4277 if (v != null && v != focused) {
4278 // do the math the get the interesting rect
4279 // of previous focused into the coord system of
4280 // newly focused view
4281 focused.getFocusedRect(mTempRect);
4282 if (mView instanceof ViewGroup) {
4283 ((ViewGroup) mView).offsetDescendantRectToMyCoords(
4284 focused, mTempRect);
4285 ((ViewGroup) mView).offsetRectIntoDescendantCoords(
4286 v, mTempRect);
4287 }
4288 if (v.requestFocus(direction, mTempRect)) {
4289 playSoundEffect(SoundEffectConstants
4290 .getContantForFocusDirection(direction));
4291 return FINISH_HANDLED;
4292 }
4293 }
4294
4295 // Give the focused view a last chance to handle the dpad key.
4296 if (mView.dispatchUnhandledMove(focused, direction)) {
4297 return FINISH_HANDLED;
4298 }
4299 } else {
4300 // find the best view to give focus to in this non-touch-mode with no-focus
4301 View v = focusSearch(null, direction);
4302 if (v != null && v.requestFocus(direction)) {
4303 return FINISH_HANDLED;
4304 }
4305 }
4306 }
4307 }
4308 return FORWARD;
Jeff Brown21bc5c92011-02-28 18:27:14 -08004309 }
4310
Jeff Brownf9e989d2013-04-04 23:04:03 -07004311 private int processPointerEvent(QueuedInputEvent q) {
4312 final MotionEvent event = (MotionEvent)q.mEvent;
4313
Vladislav Kaznacheev527905e2016-02-16 16:20:56 -08004314 mAttachInfo.mUnbufferedDispatchRequested = false;
4315 final View eventTarget =
4316 (event.isFromSource(InputDevice.SOURCE_MOUSE) && mCapturingView != null) ?
4317 mCapturingView : mView;
4318 mAttachInfo.mHandlingPointerEvent = true;
4319 boolean handled = eventTarget.dispatchPointerEvent(event);
4320 maybeUpdatePointerIcon(event);
4321 mAttachInfo.mHandlingPointerEvent = false;
4322 if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4323 mUnbufferedInputDispatch = true;
4324 if (mConsumeBatchedInputScheduled) {
4325 scheduleConsumeBatchedInputImmediately();
4326 }
4327 }
4328 return handled ? FINISH_HANDLED : FORWARD;
4329 }
4330
4331 private void maybeUpdatePointerIcon(MotionEvent event) {
Jun Mukai1db53972015-09-11 18:08:31 -07004332 if (event.getPointerCount() == 1
4333 && event.isFromSource(InputDevice.SOURCE_MOUSE)) {
4334 if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
4335 || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
4336 // Other apps or the window manager may change the icon shape outside of
4337 // this app, therefore the icon shape has to be reset on enter/exit event.
4338 mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4339 }
4340
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08004341 if (event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
4342 if (!updatePointerIcon(event) &&
4343 event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE) {
4344 mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
Jun Mukai1db53972015-09-11 18:08:31 -07004345 }
4346 }
4347 }
Jeff Brown3915bb82010-11-05 15:02:16 -07004348 }
4349
Jeff Brownf9e989d2013-04-04 23:04:03 -07004350 private int processTrackballEvent(QueuedInputEvent q) {
4351 final MotionEvent event = (MotionEvent)q.mEvent;
4352
4353 if (mView.dispatchTrackballEvent(event)) {
4354 return FINISH_HANDLED;
4355 }
4356 return FORWARD;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 }
4358
Jeff Brownf9e989d2013-04-04 23:04:03 -07004359 private int processGenericMotionEvent(QueuedInputEvent q) {
4360 final MotionEvent event = (MotionEvent)q.mEvent;
Jeff Brown00fa7bd2010-07-02 15:37:36 -07004361
Jeff Brownf9e989d2013-04-04 23:04:03 -07004362 // Deliver the event to the view.
4363 if (mView.dispatchGenericMotionEvent(event)) {
4364 return FINISH_HANDLED;
4365 }
4366 return FORWARD;
Jeff Brown3915bb82010-11-05 15:02:16 -07004367 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07004368 }
4369
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08004370 private void resetPointerIcon(MotionEvent event) {
4371 mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4372 updatePointerIcon(event);
4373 }
4374
4375 private boolean updatePointerIcon(MotionEvent event) {
4376 final float x = event.getX();
4377 final float y = event.getY();
4378 if (x < 0 || x >= mView.getWidth() || y < 0 || y >= mView.getHeight()) {
4379 Slog.e(mTag, "updatePointerIcon called with position out of bounds");
4380 return false;
4381 }
4382 final PointerIcon pointerIcon = mView.getPointerIcon(event, x, y);
4383 final int pointerShape = (pointerIcon != null) ?
4384 pointerIcon.getStyle() : PointerIcon.STYLE_DEFAULT;
4385
4386 if (mPointerIconShape != pointerShape) {
4387 mPointerIconShape = pointerShape;
4388 if (mPointerIconShape != PointerIcon.STYLE_CUSTOM) {
4389 mCustomPointerIcon = null;
4390 InputManager.getInstance().setPointerIconShape(pointerShape);
4391 return true;
4392 }
4393 }
4394 if (mPointerIconShape == PointerIcon.STYLE_CUSTOM &&
4395 !pointerIcon.equals(mCustomPointerIcon)) {
4396 mCustomPointerIcon = pointerIcon;
4397 InputManager.getInstance().setCustomPointerIcon(mCustomPointerIcon);
4398 }
4399 return true;
4400 }
4401
Jeff Brownf9e989d2013-04-04 23:04:03 -07004402 /**
Jeff Brown678a1252013-04-09 17:46:25 -07004403 * Performs synthesis of new input events from unhandled input events.
Jeff Brownf9e989d2013-04-04 23:04:03 -07004404 */
4405 final class SyntheticInputStage extends InputStage {
Jeff Brown678a1252013-04-09 17:46:25 -07004406 private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4407 private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4408 private final SyntheticTouchNavigationHandler mTouchNavigation =
4409 new SyntheticTouchNavigationHandler();
Michael Wright899d7052014-04-23 17:23:39 -07004410 private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004411
4412 public SyntheticInputStage() {
4413 super(null);
Jeff Brown21bc5c92011-02-28 18:27:14 -08004414 }
4415
Jeff Brownf9e989d2013-04-04 23:04:03 -07004416 @Override
4417 protected int onProcess(QueuedInputEvent q) {
4418 q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4419 if (q.mEvent instanceof MotionEvent) {
Jeff Brown678a1252013-04-09 17:46:25 -07004420 final MotionEvent event = (MotionEvent)q.mEvent;
4421 final int source = event.getSource();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004422 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown678a1252013-04-09 17:46:25 -07004423 mTrackball.process(event);
4424 return FINISH_HANDLED;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004425 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
Jeff Brown678a1252013-04-09 17:46:25 -07004426 mJoystick.process(event);
4427 return FINISH_HANDLED;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004428 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4429 == InputDevice.SOURCE_TOUCH_NAVIGATION) {
Jeff Brown678a1252013-04-09 17:46:25 -07004430 mTouchNavigation.process(event);
4431 return FINISH_HANDLED;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004432 }
Michael Wright899d7052014-04-23 17:23:39 -07004433 } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4434 mKeyboard.process((KeyEvent)q.mEvent);
4435 return FINISH_HANDLED;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004436 }
Michael Wright899d7052014-04-23 17:23:39 -07004437
Jeff Brownf9e989d2013-04-04 23:04:03 -07004438 return FORWARD;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
4440
Jeff Brownf9e989d2013-04-04 23:04:03 -07004441 @Override
4442 protected void onDeliverToNext(QueuedInputEvent q) {
4443 if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4444 // Cancel related synthetic events if any prior stage has handled the event.
4445 if (q.mEvent instanceof MotionEvent) {
Jeff Brown678a1252013-04-09 17:46:25 -07004446 final MotionEvent event = (MotionEvent)q.mEvent;
4447 final int source = event.getSource();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004448 if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
Jeff Brown678a1252013-04-09 17:46:25 -07004449 mTrackball.cancel(event);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004450 } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
Jeff Brown678a1252013-04-09 17:46:25 -07004451 mJoystick.cancel(event);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004452 } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4453 == InputDevice.SOURCE_TOUCH_NAVIGATION) {
Jeff Brown678a1252013-04-09 17:46:25 -07004454 mTouchNavigation.cancel(event);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004455 }
4456 }
4457 }
4458 super.onDeliverToNext(q);
4459 }
Jeff Brown678a1252013-04-09 17:46:25 -07004460 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004461
Jeff Brown678a1252013-04-09 17:46:25 -07004462 /**
4463 * Creates dpad events from unhandled trackball movements.
4464 */
4465 final class SyntheticTrackballHandler {
4466 private final TrackballAxis mX = new TrackballAxis();
4467 private final TrackballAxis mY = new TrackballAxis();
4468 private long mLastTime;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004469
Jeff Brown678a1252013-04-09 17:46:25 -07004470 public void process(MotionEvent event) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004471 // Translate the trackball event into DPAD keys and try to deliver those.
Jeff Brownf9e989d2013-04-04 23:04:03 -07004472 long curTime = SystemClock.uptimeMillis();
Jeff Brown678a1252013-04-09 17:46:25 -07004473 if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004474 // It has been too long since the last movement,
4475 // so restart at the beginning.
Jeff Brown678a1252013-04-09 17:46:25 -07004476 mX.reset(0);
4477 mY.reset(0);
4478 mLastTime = curTime;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004479 }
4480
4481 final int action = event.getAction();
4482 final int metaState = event.getMetaState();
4483 switch (action) {
4484 case MotionEvent.ACTION_DOWN:
Jeff Brown678a1252013-04-09 17:46:25 -07004485 mX.reset(2);
4486 mY.reset(2);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004487 enqueueInputEvent(new KeyEvent(curTime, curTime,
4488 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4489 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4490 InputDevice.SOURCE_KEYBOARD));
4491 break;
4492 case MotionEvent.ACTION_UP:
Jeff Brown678a1252013-04-09 17:46:25 -07004493 mX.reset(2);
4494 mY.reset(2);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004495 enqueueInputEvent(new KeyEvent(curTime, curTime,
4496 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4497 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4498 InputDevice.SOURCE_KEYBOARD));
4499 break;
4500 }
4501
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004502 if (DEBUG_TRACKBALL) Log.v(mTag, "TB X=" + mX.position + " step="
Jeff Brown678a1252013-04-09 17:46:25 -07004503 + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
Jeff Brownf9e989d2013-04-04 23:04:03 -07004504 + " move=" + event.getX()
Jeff Brown678a1252013-04-09 17:46:25 -07004505 + " / Y=" + mY.position + " step="
4506 + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
Jeff Brownf9e989d2013-04-04 23:04:03 -07004507 + " move=" + event.getY());
Jeff Brown678a1252013-04-09 17:46:25 -07004508 final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4509 final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
Jeff Brownf9e989d2013-04-04 23:04:03 -07004510
4511 // Generate DPAD events based on the trackball movement.
4512 // We pick the axis that has moved the most as the direction of
4513 // the DPAD. When we generate DPAD events for one axis, then the
4514 // other axis is reset -- we don't want to perform DPAD jumps due
4515 // to slight movements in the trackball when making major movements
4516 // along the other axis.
4517 int keycode = 0;
4518 int movement = 0;
4519 float accel = 1;
4520 if (xOff > yOff) {
Jeff Brown678a1252013-04-09 17:46:25 -07004521 movement = mX.generate();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004522 if (movement != 0) {
4523 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4524 : KeyEvent.KEYCODE_DPAD_LEFT;
Jeff Brown678a1252013-04-09 17:46:25 -07004525 accel = mX.acceleration;
4526 mY.reset(2);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004527 }
4528 } else if (yOff > 0) {
Jeff Brown678a1252013-04-09 17:46:25 -07004529 movement = mY.generate();
Jeff Brownf9e989d2013-04-04 23:04:03 -07004530 if (movement != 0) {
4531 keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4532 : KeyEvent.KEYCODE_DPAD_UP;
Jeff Brown678a1252013-04-09 17:46:25 -07004533 accel = mY.acceleration;
4534 mX.reset(2);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004535 }
4536 }
4537
4538 if (keycode != 0) {
4539 if (movement < 0) movement = -movement;
4540 int accelMovement = (int)(movement * accel);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004541 if (DEBUG_TRACKBALL) Log.v(mTag, "Move: movement=" + movement
Jeff Brownf9e989d2013-04-04 23:04:03 -07004542 + " accelMovement=" + accelMovement
4543 + " accel=" + accel);
4544 if (accelMovement > movement) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004545 if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
Jeff Brownf9e989d2013-04-04 23:04:03 -07004546 + keycode);
4547 movement--;
4548 int repeatCount = accelMovement - movement;
4549 enqueueInputEvent(new KeyEvent(curTime, curTime,
4550 KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4551 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4552 InputDevice.SOURCE_KEYBOARD));
4553 }
4554 while (movement > 0) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004555 if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
Jeff Brownf9e989d2013-04-04 23:04:03 -07004556 + keycode);
4557 movement--;
4558 curTime = SystemClock.uptimeMillis();
4559 enqueueInputEvent(new KeyEvent(curTime, curTime,
4560 KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4561 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4562 InputDevice.SOURCE_KEYBOARD));
4563 enqueueInputEvent(new KeyEvent(curTime, curTime,
4564 KeyEvent.ACTION_UP, keycode, 0, metaState,
4565 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4566 InputDevice.SOURCE_KEYBOARD));
4567 }
Jeff Brown678a1252013-04-09 17:46:25 -07004568 mLastTime = curTime;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004569 }
Jeff Brownf9e989d2013-04-04 23:04:03 -07004570 }
4571
Jeff Brown678a1252013-04-09 17:46:25 -07004572 public void cancel(MotionEvent event) {
4573 mLastTime = Integer.MIN_VALUE;
Jeff Brown3915bb82010-11-05 15:02:16 -07004574
Jeff Brownf9e989d2013-04-04 23:04:03 -07004575 // If we reach this, we consumed a trackball event.
4576 // Because we will not translate the trackball event into a key event,
4577 // touch mode will not exit, so we exit touch mode here.
4578 if (mView != null && mAdded) {
4579 ensureTouchMode(false);
Jeff Brown00fa7bd2010-07-02 15:37:36 -07004580 }
4581 }
Jeff Brown678a1252013-04-09 17:46:25 -07004582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583
Jeff Brown678a1252013-04-09 17:46:25 -07004584 /**
4585 * Maintains state information for a single trackball axis, generating
4586 * discrete (DPAD) movements based on raw trackball motion.
4587 */
4588 static final class TrackballAxis {
4589 /**
4590 * The maximum amount of acceleration we will apply.
4591 */
4592 static final float MAX_ACCELERATION = 20;
4593
4594 /**
4595 * The maximum amount of time (in milliseconds) between events in order
4596 * for us to consider the user to be doing fast trackball movements,
4597 * and thus apply an acceleration.
4598 */
4599 static final long FAST_MOVE_TIME = 150;
4600
4601 /**
4602 * Scaling factor to the time (in milliseconds) between events to how
4603 * much to multiple/divide the current acceleration. When movement
4604 * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4605 * FAST_MOVE_TIME it divides it.
4606 */
4607 static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4608
4609 static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4610 static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4611 static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4612
4613 float position;
4614 float acceleration = 1;
4615 long lastMoveTime = 0;
4616 int step;
4617 int dir;
4618 int nonAccelMovement;
4619
4620 void reset(int _step) {
4621 position = 0;
4622 acceleration = 1;
4623 lastMoveTime = 0;
4624 step = _step;
4625 dir = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08004626 }
4627
Jeff Brown678a1252013-04-09 17:46:25 -07004628 /**
4629 * Add trackball movement into the state. If the direction of movement
4630 * has been reversed, the state is reset before adding the
4631 * movement (so that you don't have to compensate for any previously
4632 * collected movement before see the result of the movement in the
4633 * new direction).
4634 *
4635 * @return Returns the absolute value of the amount of movement
4636 * collected so far.
4637 */
4638 float collect(float off, long time, String axis) {
4639 long normTime;
4640 if (off > 0) {
4641 normTime = (long)(off * FAST_MOVE_TIME);
4642 if (dir < 0) {
4643 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4644 position = 0;
4645 step = 0;
4646 acceleration = 1;
4647 lastMoveTime = 0;
4648 }
4649 dir = 1;
4650 } else if (off < 0) {
4651 normTime = (long)((-off) * FAST_MOVE_TIME);
4652 if (dir > 0) {
4653 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4654 position = 0;
4655 step = 0;
4656 acceleration = 1;
4657 lastMoveTime = 0;
4658 }
4659 dir = -1;
4660 } else {
4661 normTime = 0;
4662 }
4663
4664 // The number of milliseconds between each movement that is
4665 // considered "normal" and will not result in any acceleration
4666 // or deceleration, scaled by the offset we have here.
4667 if (normTime > 0) {
4668 long delta = time - lastMoveTime;
4669 lastMoveTime = time;
4670 float acc = acceleration;
4671 if (delta < normTime) {
4672 // The user is scrolling rapidly, so increase acceleration.
4673 float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4674 if (scale > 1) acc *= scale;
4675 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4676 + off + " normTime=" + normTime + " delta=" + delta
4677 + " scale=" + scale + " acc=" + acc);
4678 acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4679 } else {
4680 // The user is scrolling slowly, so decrease acceleration.
4681 float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4682 if (scale > 1) acc /= scale;
4683 if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4684 + off + " normTime=" + normTime + " delta=" + delta
4685 + " scale=" + scale + " acc=" + acc);
4686 acceleration = acc > 1 ? acc : 1;
4687 }
4688 }
4689 position += off;
4690 return Math.abs(position);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004691 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004692
Jeff Brown678a1252013-04-09 17:46:25 -07004693 /**
4694 * Generate the number of discrete movement events appropriate for
4695 * the currently collected trackball movement.
4696 *
4697 * @return Returns the number of discrete movements, either positive
4698 * or negative, or 0 if there is not enough trackball movement yet
4699 * for a discrete movement.
4700 */
4701 int generate() {
4702 int movement = 0;
4703 nonAccelMovement = 0;
4704 do {
4705 final int dir = position >= 0 ? 1 : -1;
4706 switch (step) {
4707 // If we are going to execute the first step, then we want
4708 // to do this as soon as possible instead of waiting for
4709 // a full movement, in order to make things look responsive.
4710 case 0:
4711 if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4712 return movement;
4713 }
4714 movement += dir;
4715 nonAccelMovement += dir;
4716 step = 1;
4717 break;
4718 // If we have generated the first movement, then we need
4719 // to wait for the second complete trackball motion before
4720 // generating the second discrete movement.
4721 case 1:
4722 if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4723 return movement;
4724 }
4725 movement += dir;
4726 nonAccelMovement += dir;
4727 position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4728 step = 2;
4729 break;
4730 // After the first two, we generate discrete movements
4731 // consistently with the trackball, applying an acceleration
4732 // if the trackball is moving quickly. This is a simple
4733 // acceleration on top of what we already compute based
4734 // on how quickly the wheel is being turned, to apply
4735 // a longer increasing acceleration to continuous movement
4736 // in one direction.
4737 default:
4738 if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4739 return movement;
4740 }
4741 movement += dir;
4742 position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4743 float acc = acceleration;
4744 acc *= 1.1f;
4745 acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4746 break;
4747 }
4748 } while (true);
4749 }
4750 }
4751
4752 /**
4753 * Creates dpad events from unhandled joystick movements.
4754 */
4755 final class SyntheticJoystickHandler extends Handler {
Michael Wright9adca062014-03-19 11:51:26 -07004756 private final static String TAG = "SyntheticJoystickHandler";
Jeff Brown678a1252013-04-09 17:46:25 -07004757 private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4758 private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4759
4760 private int mLastXDirection;
4761 private int mLastYDirection;
4762 private int mLastXKeyCode;
4763 private int mLastYKeyCode;
4764
4765 public SyntheticJoystickHandler() {
4766 super(true);
4767 }
4768
4769 @Override
4770 public void handleMessage(Message msg) {
4771 switch (msg.what) {
4772 case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4773 case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4774 KeyEvent oldEvent = (KeyEvent)msg.obj;
4775 KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4776 SystemClock.uptimeMillis(),
4777 oldEvent.getRepeatCount() + 1);
4778 if (mAttachInfo.mHasWindowFocus) {
4779 enqueueInputEvent(e);
4780 Message m = obtainMessage(msg.what, e);
4781 m.setAsynchronous(true);
4782 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4783 }
4784 } break;
4785 }
4786 }
4787
4788 public void process(MotionEvent event) {
Michael Wright9adca062014-03-19 11:51:26 -07004789 switch(event.getActionMasked()) {
4790 case MotionEvent.ACTION_CANCEL:
4791 cancel(event);
4792 break;
4793 case MotionEvent.ACTION_MOVE:
4794 update(event, true);
4795 break;
4796 default:
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08004797 Log.w(mTag, "Unexpected action: " + event.getActionMasked());
Michael Wright9adca062014-03-19 11:51:26 -07004798 }
Jeff Brown678a1252013-04-09 17:46:25 -07004799 }
4800
Michael Wright9adca062014-03-19 11:51:26 -07004801 private void cancel(MotionEvent event) {
4802 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4803 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
Jeff Brown678a1252013-04-09 17:46:25 -07004804 update(event, false);
4805 }
4806
4807 private void update(MotionEvent event, boolean synthesizeNewKeys) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07004808 final long time = event.getEventTime();
4809 final int metaState = event.getMetaState();
4810 final int deviceId = event.getDeviceId();
4811 final int source = event.getSource();
4812
4813 int xDirection = joystickAxisValueToDirection(
4814 event.getAxisValue(MotionEvent.AXIS_HAT_X));
4815 if (xDirection == 0) {
4816 xDirection = joystickAxisValueToDirection(event.getX());
Jeff Browncb1404e2011-01-15 18:14:15 -08004817 }
4818
Jeff Brownf9e989d2013-04-04 23:04:03 -07004819 int yDirection = joystickAxisValueToDirection(
4820 event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4821 if (yDirection == 0) {
4822 yDirection = joystickAxisValueToDirection(event.getY());
4823 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004824
Jeff Brown678a1252013-04-09 17:46:25 -07004825 if (xDirection != mLastXDirection) {
4826 if (mLastXKeyCode != 0) {
4827 removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004828 enqueueInputEvent(new KeyEvent(time, time,
Jeff Brown678a1252013-04-09 17:46:25 -07004829 KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
Jeff Brownf9e989d2013-04-04 23:04:03 -07004830 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
Jeff Brown678a1252013-04-09 17:46:25 -07004831 mLastXKeyCode = 0;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004832 }
4833
Jeff Brown678a1252013-04-09 17:46:25 -07004834 mLastXDirection = xDirection;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004835
4836 if (xDirection != 0 && synthesizeNewKeys) {
Jeff Brown678a1252013-04-09 17:46:25 -07004837 mLastXKeyCode = xDirection > 0
Jeff Brownf9e989d2013-04-04 23:04:03 -07004838 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4839 final KeyEvent e = new KeyEvent(time, time,
Jeff Brown678a1252013-04-09 17:46:25 -07004840 KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
Jeff Brownf9e989d2013-04-04 23:04:03 -07004841 deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4842 enqueueInputEvent(e);
Jeff Brown678a1252013-04-09 17:46:25 -07004843 Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004844 m.setAsynchronous(true);
Michael Wrightb9618522013-04-10 15:20:56 -07004845 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
Jeff Brownf9e989d2013-04-04 23:04:03 -07004846 }
4847 }
4848
Jeff Brown678a1252013-04-09 17:46:25 -07004849 if (yDirection != mLastYDirection) {
4850 if (mLastYKeyCode != 0) {
4851 removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004852 enqueueInputEvent(new KeyEvent(time, time,
Jeff Brown678a1252013-04-09 17:46:25 -07004853 KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
Jeff Brownf9e989d2013-04-04 23:04:03 -07004854 deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
Jeff Brown678a1252013-04-09 17:46:25 -07004855 mLastYKeyCode = 0;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004856 }
4857
Jeff Brown678a1252013-04-09 17:46:25 -07004858 mLastYDirection = yDirection;
Jeff Brownf9e989d2013-04-04 23:04:03 -07004859
4860 if (yDirection != 0 && synthesizeNewKeys) {
Jeff Brown678a1252013-04-09 17:46:25 -07004861 mLastYKeyCode = yDirection > 0
Jeff Brownf9e989d2013-04-04 23:04:03 -07004862 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4863 final KeyEvent e = new KeyEvent(time, time,
Jeff Brown678a1252013-04-09 17:46:25 -07004864 KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
Jeff Brownf9e989d2013-04-04 23:04:03 -07004865 deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4866 enqueueInputEvent(e);
Jeff Brown678a1252013-04-09 17:46:25 -07004867 Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
Jeff Brownf9e989d2013-04-04 23:04:03 -07004868 m.setAsynchronous(true);
Jeff Brown678a1252013-04-09 17:46:25 -07004869 sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
Jeff Brownf9e989d2013-04-04 23:04:03 -07004870 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004871 }
4872 }
4873
Jeff Brownf9e989d2013-04-04 23:04:03 -07004874 private int joystickAxisValueToDirection(float value) {
4875 if (value >= 0.5f) {
4876 return 1;
4877 } else if (value <= -0.5f) {
4878 return -1;
4879 } else {
4880 return 0;
Jeff Browncb1404e2011-01-15 18:14:15 -08004881 }
4882 }
Jeff Brown678a1252013-04-09 17:46:25 -07004883 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004884
Jeff Brown678a1252013-04-09 17:46:25 -07004885 /**
4886 * Creates dpad events from unhandled touch navigation movements.
4887 */
4888 final class SyntheticTouchNavigationHandler extends Handler {
Jeff Brown4dac9012013-04-10 01:03:19 -07004889 private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4890 private static final boolean LOCAL_DEBUG = false;
Jeff Brown678a1252013-04-09 17:46:25 -07004891
Jeff Brown4dac9012013-04-10 01:03:19 -07004892 // Assumed nominal width and height in millimeters of a touch navigation pad,
4893 // if no resolution information is available from the input system.
4894 private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4895 private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
Jeff Brown678a1252013-04-09 17:46:25 -07004896
Jeff Brown4dac9012013-04-10 01:03:19 -07004897 /* TODO: These constants should eventually be moved to ViewConfiguration. */
Jeff Brown678a1252013-04-09 17:46:25 -07004898
Jeff Brown4dac9012013-04-10 01:03:19 -07004899 // The nominal distance traveled to move by one unit.
4900 private static final int TICK_DISTANCE_MILLIMETERS = 12;
4901
4902 // Minimum and maximum fling velocity in ticks per second.
4903 // The minimum velocity should be set such that we perform enough ticks per
4904 // second that the fling appears to be fluid. For example, if we set the minimum
4905 // to 2 ticks per second, then there may be up to half a second delay between the next
4906 // to last and last ticks which is noticeably discrete and jerky. This value should
4907 // probably not be set to anything less than about 4.
4908 // If fling accuracy is a problem then consider tuning the tick distance instead.
4909 private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4910 private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4911
4912 // Fling velocity decay factor applied after each new key is emitted.
4913 // This parameter controls the deceleration and overall duration of the fling.
4914 // The fling stops automatically when its velocity drops below the minimum
4915 // fling velocity defined above.
4916 private static final float FLING_TICK_DECAY = 0.8f;
4917
4918 /* The input device that we are tracking. */
4919
4920 private int mCurrentDeviceId = -1;
4921 private int mCurrentSource;
4922 private boolean mCurrentDeviceSupported;
4923
4924 /* Configuration for the current input device. */
4925
Jeff Brown4dac9012013-04-10 01:03:19 -07004926 // The scaled tick distance. A movement of this amount should generally translate
4927 // into a single dpad event in a given direction.
4928 private float mConfigTickDistance;
4929
4930 // The minimum and maximum scaled fling velocity.
4931 private float mConfigMinFlingVelocity;
4932 private float mConfigMaxFlingVelocity;
4933
4934 /* Tracking state. */
4935
4936 // The velocity tracker for detecting flings.
4937 private VelocityTracker mVelocityTracker;
4938
4939 // The active pointer id, or -1 if none.
4940 private int mActivePointerId = -1;
4941
John Reck79d81e62013-11-05 13:26:57 -08004942 // Location where tracking started.
Jeff Brown4dac9012013-04-10 01:03:19 -07004943 private float mStartX;
4944 private float mStartY;
4945
4946 // Most recently observed position.
4947 private float mLastX;
4948 private float mLastY;
4949
4950 // Accumulated movement delta since the last direction key was sent.
Jeff Brown678a1252013-04-09 17:46:25 -07004951 private float mAccumulatedX;
4952 private float mAccumulatedY;
4953
Jeff Brown4dac9012013-04-10 01:03:19 -07004954 // Set to true if any movement was delivered to the app.
4955 // Implies that tap slop was exceeded.
4956 private boolean mConsumedMovement;
Jeff Brown678a1252013-04-09 17:46:25 -07004957
Jeff Brown4dac9012013-04-10 01:03:19 -07004958 // The most recently sent key down event.
4959 // The keycode remains set until the direction changes or a fling ends
4960 // so that repeated key events may be generated as required.
4961 private long mPendingKeyDownTime;
4962 private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
4963 private int mPendingKeyRepeatCount;
4964 private int mPendingKeyMetaState;
Jeff Brown678a1252013-04-09 17:46:25 -07004965
Jeff Brown4dac9012013-04-10 01:03:19 -07004966 // The current fling velocity while a fling is in progress.
4967 private boolean mFlinging;
4968 private float mFlingVelocity;
Jeff Brown678a1252013-04-09 17:46:25 -07004969
4970 public SyntheticTouchNavigationHandler() {
4971 super(true);
Jeff Brown678a1252013-04-09 17:46:25 -07004972 }
4973
4974 public void process(MotionEvent event) {
Jeff Brown4dac9012013-04-10 01:03:19 -07004975 // Update the current device information.
4976 final long time = event.getEventTime();
4977 final int deviceId = event.getDeviceId();
4978 final int source = event.getSource();
4979 if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
4980 finishKeys(time);
4981 finishTracking(time);
4982 mCurrentDeviceId = deviceId;
4983 mCurrentSource = source;
4984 mCurrentDeviceSupported = false;
4985 InputDevice device = event.getDevice();
4986 if (device != null) {
4987 // In order to support an input device, we must know certain
4988 // characteristics about it, such as its size and resolution.
4989 InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
4990 InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
4991 if (xRange != null && yRange != null) {
4992 mCurrentDeviceSupported = true;
Jeff Brown678a1252013-04-09 17:46:25 -07004993
Jeff Brown4dac9012013-04-10 01:03:19 -07004994 // Infer the resolution if it not actually known.
4995 float xRes = xRange.getResolution();
4996 if (xRes <= 0) {
4997 xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
4998 }
4999 float yRes = yRange.getResolution();
5000 if (yRes <= 0) {
5001 yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
5002 }
5003 float nominalRes = (xRes + yRes) * 0.5f;
Jeff Brown678a1252013-04-09 17:46:25 -07005004
Jeff Brown4dac9012013-04-10 01:03:19 -07005005 // Precompute all of the configuration thresholds we will need.
Jeff Brown4dac9012013-04-10 01:03:19 -07005006 mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
5007 mConfigMinFlingVelocity =
5008 MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5009 mConfigMaxFlingVelocity =
5010 MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5011
5012 if (LOCAL_DEBUG) {
5013 Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
5014 + " (" + Integer.toHexString(mCurrentSource) + "): "
Jeff Brown4dac9012013-04-10 01:03:19 -07005015 + ", mConfigTickDistance=" + mConfigTickDistance
5016 + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
5017 + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
5018 }
5019 }
5020 }
Jeff Brown678a1252013-04-09 17:46:25 -07005021 }
Jeff Brown4dac9012013-04-10 01:03:19 -07005022 if (!mCurrentDeviceSupported) {
Jeff Brown678a1252013-04-09 17:46:25 -07005023 return;
5024 }
5025
Jeff Brown4dac9012013-04-10 01:03:19 -07005026 // Handle the event.
5027 final int action = event.getActionMasked();
5028 switch (action) {
Jeff Brown678a1252013-04-09 17:46:25 -07005029 case MotionEvent.ACTION_DOWN: {
Jeff Brown4dac9012013-04-10 01:03:19 -07005030 boolean caughtFling = mFlinging;
5031 finishKeys(time);
5032 finishTracking(time);
5033 mActivePointerId = event.getPointerId(0);
5034 mVelocityTracker = VelocityTracker.obtain();
5035 mVelocityTracker.addMovement(event);
Jeff Brown4dac9012013-04-10 01:03:19 -07005036 mStartX = event.getX();
5037 mStartY = event.getY();
5038 mLastX = mStartX;
5039 mLastY = mStartY;
Jeff Brown678a1252013-04-09 17:46:25 -07005040 mAccumulatedX = 0;
5041 mAccumulatedY = 0;
Jeff Brown4dac9012013-04-10 01:03:19 -07005042
5043 // If we caught a fling, then pretend that the tap slop has already
5044 // been exceeded to suppress taps whose only purpose is to stop the fling.
5045 mConsumedMovement = caughtFling;
Jeff Brown678a1252013-04-09 17:46:25 -07005046 break;
5047 }
5048
Jeff Brown4dac9012013-04-10 01:03:19 -07005049 case MotionEvent.ACTION_MOVE:
Jeff Brown678a1252013-04-09 17:46:25 -07005050 case MotionEvent.ACTION_UP: {
Jeff Brown4dac9012013-04-10 01:03:19 -07005051 if (mActivePointerId < 0) {
5052 break;
5053 }
5054 final int index = event.findPointerIndex(mActivePointerId);
5055 if (index < 0) {
5056 finishKeys(time);
5057 finishTracking(time);
5058 break;
5059 }
Jeff Brown678a1252013-04-09 17:46:25 -07005060
Jeff Brown4dac9012013-04-10 01:03:19 -07005061 mVelocityTracker.addMovement(event);
5062 final float x = event.getX(index);
5063 final float y = event.getY(index);
5064 mAccumulatedX += x - mLastX;
5065 mAccumulatedY += y - mLastY;
5066 mLastX = x;
5067 mLastY = y;
5068
5069 // Consume any accumulated movement so far.
5070 final int metaState = event.getMetaState();
5071 consumeAccumulatedMovement(time, metaState);
5072
5073 // Detect taps and flings.
5074 if (action == MotionEvent.ACTION_UP) {
Michael Wright88d7f792013-08-27 15:45:42 -07005075 if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
Jeff Brown4dac9012013-04-10 01:03:19 -07005076 // It might be a fling.
5077 mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
5078 final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
5079 final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
5080 if (!startFling(time, vx, vy)) {
5081 finishKeys(time);
Jeff Brown678a1252013-04-09 17:46:25 -07005082 }
5083 }
Jeff Brown4dac9012013-04-10 01:03:19 -07005084 finishTracking(time);
Jeff Brown678a1252013-04-09 17:46:25 -07005085 }
Jeff Brown4dac9012013-04-10 01:03:19 -07005086 break;
5087 }
5088
5089 case MotionEvent.ACTION_CANCEL: {
5090 finishKeys(time);
5091 finishTracking(time);
Jeff Brown678a1252013-04-09 17:46:25 -07005092 break;
5093 }
5094 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005095 }
Jeff Brown4dac9012013-04-10 01:03:19 -07005096
5097 public void cancel(MotionEvent event) {
5098 if (mCurrentDeviceId == event.getDeviceId()
5099 && mCurrentSource == event.getSource()) {
5100 final long time = event.getEventTime();
5101 finishKeys(time);
5102 finishTracking(time);
5103 }
5104 }
5105
5106 private void finishKeys(long time) {
5107 cancelFling();
5108 sendKeyUp(time);
5109 }
5110
5111 private void finishTracking(long time) {
5112 if (mActivePointerId >= 0) {
5113 mActivePointerId = -1;
5114 mVelocityTracker.recycle();
5115 mVelocityTracker = null;
5116 }
5117 }
5118
5119 private void consumeAccumulatedMovement(long time, int metaState) {
5120 final float absX = Math.abs(mAccumulatedX);
5121 final float absY = Math.abs(mAccumulatedY);
5122 if (absX >= absY) {
5123 if (absX >= mConfigTickDistance) {
5124 mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
5125 KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
5126 mAccumulatedY = 0;
5127 mConsumedMovement = true;
5128 }
5129 } else {
5130 if (absY >= mConfigTickDistance) {
5131 mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
5132 KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
5133 mAccumulatedX = 0;
5134 mConsumedMovement = true;
5135 }
5136 }
5137 }
5138
5139 private float consumeAccumulatedMovement(long time, int metaState,
5140 float accumulator, int negativeKeyCode, int positiveKeyCode) {
5141 while (accumulator <= -mConfigTickDistance) {
5142 sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
5143 accumulator += mConfigTickDistance;
5144 }
5145 while (accumulator >= mConfigTickDistance) {
5146 sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
5147 accumulator -= mConfigTickDistance;
5148 }
5149 return accumulator;
5150 }
5151
5152 private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
5153 if (mPendingKeyCode != keyCode) {
5154 sendKeyUp(time);
5155 mPendingKeyDownTime = time;
5156 mPendingKeyCode = keyCode;
5157 mPendingKeyRepeatCount = 0;
5158 } else {
5159 mPendingKeyRepeatCount += 1;
5160 }
5161 mPendingKeyMetaState = metaState;
5162
5163 // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
5164 // but it doesn't quite make sense when simulating the events in this way.
5165 if (LOCAL_DEBUG) {
5166 Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
5167 + ", repeatCount=" + mPendingKeyRepeatCount
5168 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5169 }
5170 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5171 KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
5172 mPendingKeyMetaState, mCurrentDeviceId,
5173 KeyEvent.FLAG_FALLBACK, mCurrentSource));
5174 }
5175
5176 private void sendKeyUp(long time) {
5177 if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
5178 if (LOCAL_DEBUG) {
5179 Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
5180 + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5181 }
5182 enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5183 KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
5184 mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
5185 mCurrentSource));
5186 mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
5187 }
5188 }
5189
5190 private boolean startFling(long time, float vx, float vy) {
5191 if (LOCAL_DEBUG) {
5192 Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
5193 + ", min=" + mConfigMinFlingVelocity);
5194 }
5195
5196 // Flings must be oriented in the same direction as the preceding movements.
5197 switch (mPendingKeyCode) {
5198 case KeyEvent.KEYCODE_DPAD_LEFT:
5199 if (-vx >= mConfigMinFlingVelocity
5200 && Math.abs(vy) < mConfigMinFlingVelocity) {
5201 mFlingVelocity = -vx;
5202 break;
5203 }
5204 return false;
5205
5206 case KeyEvent.KEYCODE_DPAD_RIGHT:
5207 if (vx >= mConfigMinFlingVelocity
5208 && Math.abs(vy) < mConfigMinFlingVelocity) {
5209 mFlingVelocity = vx;
5210 break;
5211 }
5212 return false;
5213
5214 case KeyEvent.KEYCODE_DPAD_UP:
5215 if (-vy >= mConfigMinFlingVelocity
5216 && Math.abs(vx) < mConfigMinFlingVelocity) {
5217 mFlingVelocity = -vy;
5218 break;
5219 }
5220 return false;
5221
5222 case KeyEvent.KEYCODE_DPAD_DOWN:
5223 if (vy >= mConfigMinFlingVelocity
5224 && Math.abs(vx) < mConfigMinFlingVelocity) {
5225 mFlingVelocity = vy;
5226 break;
5227 }
5228 return false;
5229 }
5230
5231 // Post the first fling event.
5232 mFlinging = postFling(time);
5233 return mFlinging;
5234 }
5235
5236 private boolean postFling(long time) {
5237 // The idea here is to estimate the time when the pointer would have
5238 // traveled one tick distance unit given the current fling velocity.
5239 // This effect creates continuity of motion.
5240 if (mFlingVelocity >= mConfigMinFlingVelocity) {
5241 long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5242 postAtTime(mFlingRunnable, time + delay);
5243 if (LOCAL_DEBUG) {
5244 Log.d(LOCAL_TAG, "Posted fling: velocity="
5245 + mFlingVelocity + ", delay=" + delay
5246 + ", keyCode=" + mPendingKeyCode);
5247 }
5248 return true;
5249 }
5250 return false;
5251 }
5252
5253 private void cancelFling() {
5254 if (mFlinging) {
5255 removeCallbacks(mFlingRunnable);
5256 mFlinging = false;
5257 }
5258 }
5259
5260 private final Runnable mFlingRunnable = new Runnable() {
5261 @Override
5262 public void run() {
5263 final long time = SystemClock.uptimeMillis();
5264 sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5265 mFlingVelocity *= FLING_TICK_DECAY;
5266 if (!postFling(time)) {
5267 mFlinging = false;
5268 finishKeys(time);
5269 }
5270 }
5271 };
Jeff Browncb1404e2011-01-15 18:14:15 -08005272 }
5273
Michael Wright899d7052014-04-23 17:23:39 -07005274 final class SyntheticKeyboardHandler {
5275 public void process(KeyEvent event) {
5276 if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5277 return;
5278 }
5279
5280 final KeyCharacterMap kcm = event.getKeyCharacterMap();
5281 final int keyCode = event.getKeyCode();
5282 final int metaState = event.getMetaState();
5283
5284 // Check for fallback actions specified by the key character map.
5285 KeyCharacterMap.FallbackAction fallbackAction =
5286 kcm.getFallbackAction(keyCode, metaState);
5287 if (fallbackAction != null) {
5288 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5289 KeyEvent fallbackEvent = KeyEvent.obtain(
5290 event.getDownTime(), event.getEventTime(),
5291 event.getAction(), fallbackAction.keyCode,
5292 event.getRepeatCount(), fallbackAction.metaState,
5293 event.getDeviceId(), event.getScanCode(),
5294 flags, event.getSource(), null);
5295 fallbackAction.recycle();
5296 enqueueInputEvent(fallbackEvent);
5297 }
5298 }
5299 }
5300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08005302 * Returns true if the key is used for keyboard navigation.
5303 * @param keyEvent The key event.
5304 * @return True if the key is used for keyboard navigation.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08005306 private static boolean isNavigationKey(KeyEvent keyEvent) {
5307 switch (keyEvent.getKeyCode()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 case KeyEvent.KEYCODE_DPAD_LEFT:
5309 case KeyEvent.KEYCODE_DPAD_RIGHT:
5310 case KeyEvent.KEYCODE_DPAD_UP:
5311 case KeyEvent.KEYCODE_DPAD_DOWN:
Jeff Brown4e6319b2010-12-13 10:36:51 -08005312 case KeyEvent.KEYCODE_DPAD_CENTER:
5313 case KeyEvent.KEYCODE_PAGE_UP:
5314 case KeyEvent.KEYCODE_PAGE_DOWN:
5315 case KeyEvent.KEYCODE_MOVE_HOME:
5316 case KeyEvent.KEYCODE_MOVE_END:
5317 case KeyEvent.KEYCODE_TAB:
5318 case KeyEvent.KEYCODE_SPACE:
5319 case KeyEvent.KEYCODE_ENTER:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 return true;
5321 }
5322 return false;
5323 }
5324
5325 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08005326 * Returns true if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005327 * @param keyEvent The key event.
Jeff Brown4e6319b2010-12-13 10:36:51 -08005328 * @return True if the key is used for typing.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 */
Jeff Brown4e6319b2010-12-13 10:36:51 -08005330 private static boolean isTypingKey(KeyEvent keyEvent) {
5331 return keyEvent.getUnicodeChar() > 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 /**
Jeff Brown4e6319b2010-12-13 10:36:51 -08005335 * See if the key event means we should leave touch mode (and leave touch mode if so).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 * @param event The key event.
5337 * @return Whether this key event should be consumed (meaning the act of
5338 * leaving touch mode alone is considered the event).
5339 */
5340 private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
Jeff Brown4e6319b2010-12-13 10:36:51 -08005341 // Only relevant in touch mode.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 if (!mAttachInfo.mInTouchMode) {
5343 return false;
5344 }
5345
Jeff Brown4e6319b2010-12-13 10:36:51 -08005346 // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5347 final int action = event.getAction();
5348 if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 return false;
5350 }
5351
Jeff Brown4e6319b2010-12-13 10:36:51 -08005352 // Don't leave touch mode if the IME told us not to.
5353 if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5354 return false;
5355 }
5356
5357 // If the key can be used for keyboard navigation then leave touch mode
5358 // and select a focused view if needed (in ensureTouchMode).
5359 // When a new focused view is selected, we consume the navigation key because
5360 // navigation doesn't make much sense unless a view already has focus so
5361 // the key's purpose is to set focus.
5362 if (isNavigationKey(event)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 return ensureTouchMode(false);
5364 }
Jeff Brown4e6319b2010-12-13 10:36:51 -08005365
5366 // If the key can be used for typing then leave touch mode
5367 // and select a focused view if needed (in ensureTouchMode).
5368 // Always allow the view to process the typing key.
5369 if (isTypingKey(event)) {
5370 ensureTouchMode(false);
5371 return false;
5372 }
5373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 return false;
5375 }
5376
Christopher Tatea53146c2010-09-07 11:57:52 -07005377 /* drag/drop */
Christopher Tate407b4e92010-11-30 17:14:08 -08005378 void setLocalDragState(Object obj) {
5379 mLocalDragState = obj;
5380 }
5381
Christopher Tatea53146c2010-09-07 11:57:52 -07005382 private void handleDragEvent(DragEvent event) {
5383 // From the root, only drag start/end/location are dispatched. entered/exited
5384 // are determined and dispatched by the viewgroup hierarchy, who then report
5385 // that back here for ultimate reporting back to the framework.
5386 if (mView != null && mAdded) {
5387 final int what = event.mAction;
5388
5389 if (what == DragEvent.ACTION_DRAG_EXITED) {
5390 // A direct EXITED event means that the window manager knows we've just crossed
5391 // a window boundary, so the current drag target within this one must have
5392 // just been exited. Send it the usual notifications and then we're done
5393 // for now.
Chris Tate9d1ab882010-11-02 15:55:39 -07005394 mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07005395 } else {
5396 // Cache the drag description when the operation starts, then fill it in
5397 // on subsequent calls as a convenience
5398 if (what == DragEvent.ACTION_DRAG_STARTED) {
Chris Tate9d1ab882010-11-02 15:55:39 -07005399 mCurrentDragView = null; // Start the current-recipient tracking
Christopher Tatea53146c2010-09-07 11:57:52 -07005400 mDragDescription = event.mClipDescription;
5401 } else {
5402 event.mClipDescription = mDragDescription;
5403 }
5404
5405 // For events with a [screen] location, translate into window coordinates
5406 if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5407 mDragPoint.set(event.mX, event.mY);
5408 if (mTranslator != null) {
5409 mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5410 }
5411
5412 if (mCurScrollY != 0) {
5413 mDragPoint.offset(0, mCurScrollY);
5414 }
5415
5416 event.mX = mDragPoint.x;
5417 event.mY = mDragPoint.y;
5418 }
5419
5420 // Remember who the current drag target is pre-dispatch
5421 final View prevDragView = mCurrentDragView;
5422
5423 // Now dispatch the drag/drop event
Chris Tated4533f12010-10-19 15:15:08 -07005424 boolean result = mView.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07005425
5426 // If we changed apparent drag target, tell the OS about it
5427 if (prevDragView != mCurrentDragView) {
5428 try {
5429 if (prevDragView != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005430 mWindowSession.dragRecipientExited(mWindow);
Christopher Tatea53146c2010-09-07 11:57:52 -07005431 }
5432 if (mCurrentDragView != null) {
Jeff Brown98365d72012-08-19 20:30:52 -07005433 mWindowSession.dragRecipientEntered(mWindow);
Christopher Tatea53146c2010-09-07 11:57:52 -07005434 }
5435 } catch (RemoteException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005436 Slog.e(mTag, "Unable to note drag target change");
Christopher Tatea53146c2010-09-07 11:57:52 -07005437 }
Christopher Tatea53146c2010-09-07 11:57:52 -07005438 }
Chris Tated4533f12010-10-19 15:15:08 -07005439
Christopher Tate407b4e92010-11-30 17:14:08 -08005440 // Report the drop result when we're done
Chris Tated4533f12010-10-19 15:15:08 -07005441 if (what == DragEvent.ACTION_DROP) {
Christopher Tate1fc014f2011-01-19 12:56:26 -08005442 mDragDescription = null;
Chris Tated4533f12010-10-19 15:15:08 -07005443 try {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005444 Log.i(mTag, "Reporting drop result: " + result);
Jeff Brown98365d72012-08-19 20:30:52 -07005445 mWindowSession.reportDropResult(mWindow, result);
Chris Tated4533f12010-10-19 15:15:08 -07005446 } catch (RemoteException e) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005447 Log.e(mTag, "Unable to report drop result");
Chris Tated4533f12010-10-19 15:15:08 -07005448 }
5449 }
Christopher Tate407b4e92010-11-30 17:14:08 -08005450
Vladislav Kaznacheev82063912015-11-20 14:20:13 -08005451 // When the drag operation ends, reset drag-related state
Christopher Tate407b4e92010-11-30 17:14:08 -08005452 if (what == DragEvent.ACTION_DRAG_ENDED) {
5453 setLocalDragState(null);
Vladislav Kaznacheev82063912015-11-20 14:20:13 -08005454 mAttachInfo.mDragToken = null;
Vladislav Kaznacheev4f639742015-11-18 13:21:35 -08005455 if (mAttachInfo.mDragSurface != null) {
5456 mAttachInfo.mDragSurface.release();
5457 mAttachInfo.mDragSurface = null;
5458 }
Christopher Tate407b4e92010-11-30 17:14:08 -08005459 }
Christopher Tatea53146c2010-09-07 11:57:52 -07005460 }
5461 }
5462 event.recycle();
5463 }
5464
Dianne Hackborn9a230e02011-10-06 11:51:27 -07005465 public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5466 if (mSeq != args.seq) {
5467 // The sequence has changed, so we need to update our value and make
5468 // sure to do a traversal afterward so the window manager is given our
5469 // most recent data.
5470 mSeq = args.seq;
5471 mAttachInfo.mForceReportNewAttributes = true;
Igor Murashkina86ab6402013-08-30 12:58:36 -07005472 scheduleTraversals();
Joe Onorato14782f72011-01-25 19:53:17 -08005473 }
Dianne Hackborn9a230e02011-10-06 11:51:27 -07005474 if (mView == null) return;
5475 if (args.localChanges != 0) {
Dianne Hackborn9a230e02011-10-06 11:51:27 -07005476 mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
Dianne Hackborn9a230e02011-10-06 11:51:27 -07005477 }
Chris Craikd36a81f2014-07-17 10:16:51 -07005478
5479 int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5480 if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5481 mAttachInfo.mGlobalSystemUiVisibility = visibility;
5482 mView.dispatchSystemUiVisibilityChanged(visibility);
Dianne Hackborncf675782012-05-10 15:07:24 -07005483 }
Joe Onorato664644d2011-01-23 17:53:23 -08005484 }
5485
Craig Mautner9c795042014-10-28 19:59:59 -07005486 public void handleDispatchWindowShown() {
5487 mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5488 }
5489
Clara Bayarri75e09792015-07-29 16:20:40 +01005490 public void handleRequestKeyboardShortcuts(IResultReceiver receiver) {
5491 Bundle data = new Bundle();
5492 ArrayList<KeyboardShortcutGroup> list = new ArrayList<>();
5493 if (mView != null) {
5494 mView.requestKeyboardShortcuts(list);
5495 }
5496 data.putParcelableArrayList(WindowManager.PARCEL_KEY_SHORTCUTS_ARRAY, list);
5497 try {
5498 receiver.send(0, data);
5499 } catch (RemoteException e) {
5500 }
5501 }
5502
Christopher Tate2c095f32010-10-04 14:13:40 -07005503 public void getLastTouchPoint(Point outLocation) {
5504 outLocation.x = (int) mLastTouchPoint.x;
5505 outLocation.y = (int) mLastTouchPoint.y;
5506 }
5507
Vladislav Kaznacheevba761122016-01-22 12:09:45 -08005508 public int getLastTouchSource() {
5509 return mLastTouchSource;
5510 }
5511
Chris Tate9d1ab882010-11-02 15:55:39 -07005512 public void setDragFocus(View newDragTarget) {
Christopher Tatea53146c2010-09-07 11:57:52 -07005513 if (mCurrentDragView != newDragTarget) {
Chris Tate048691c2010-10-12 17:39:18 -07005514 mCurrentDragView = newDragTarget;
Christopher Tatea53146c2010-09-07 11:57:52 -07005515 }
Christopher Tatea53146c2010-09-07 11:57:52 -07005516 }
5517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 private AudioManager getAudioManager() {
5519 if (mView == null) {
5520 throw new IllegalStateException("getAudioManager called when there is no mView");
5521 }
5522 if (mAudioManager == null) {
5523 mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5524 }
5525 return mAudioManager;
5526 }
5527
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07005528 public AccessibilityInteractionController getAccessibilityInteractionController() {
5529 if (mView == null) {
5530 throw new IllegalStateException("getAccessibilityInteractionController"
5531 + " called when there is no mView");
5532 }
Gilles Debunne5ac84422011-10-19 09:35:58 -07005533 if (mAccessibilityInteractionController == null) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07005534 mAccessibilityInteractionController = new AccessibilityInteractionController(this);
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07005535 }
Gilles Debunne5ac84422011-10-19 09:35:58 -07005536 return mAccessibilityInteractionController;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07005537 }
5538
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07005539 private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5540 boolean insetsPending) throws RemoteException {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005541
5542 float appScale = mAttachInfo.mApplicationScale;
Mitsuru Oshima3d914922009-05-13 22:29:15 -07005543 boolean restore = false;
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005544 if (params != null && mTranslator != null) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005545 restore = true;
5546 params.backup();
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005547 mTranslator.translateWindowLayout(params);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07005548 }
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005549 if (params != null) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005550 if (DBG) Log.d(mTag, "WindowLayout in layoutWindow:" + params);
Mitsuru Oshima3d914922009-05-13 22:29:15 -07005551 }
Dianne Hackborn694f79b2010-03-17 19:44:59 -07005552 mPendingConfiguration.seq = 0;
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005553 //Log.d(mTag, ">>>>>> CALLING relayout");
Dianne Hackborn180c4842011-09-13 12:39:25 -07005554 if (params != null && mOrigWindowType != params.type) {
5555 // For compatibility with old apps, don't crash here.
Michael Wright5bd69e62015-05-14 14:48:08 +01005556 if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005557 Slog.w(mTag, "Window type can not be changed after "
Dianne Hackborn180c4842011-09-13 12:39:25 -07005558 + "the window is added; ignoring change of " + mView);
5559 params.type = mOrigWindowType;
5560 }
5561 }
Jeff Brown98365d72012-08-19 20:30:52 -07005562 int relayoutResult = mWindowSession.relayout(
Dianne Hackborn9a230e02011-10-06 11:51:27 -07005563 mWindow, mSeq, params,
Dianne Hackborn189ee182010-12-02 21:48:53 -08005564 (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5565 (int) (mView.getMeasuredHeight() * appScale + 0.5f),
Jeff Brown98365d72012-08-19 20:30:52 -07005566 viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
Dianne Hackbornc4aad012013-02-22 15:05:25 -08005567 mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
Jorim Jaggi2e95a482016-01-14 17:36:55 -08005568 mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingConfiguration,
5569 mSurface);
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005570 //Log.d(mTag, "<<<<<< BACK FROM relayout");
Mitsuru Oshima3d914922009-05-13 22:29:15 -07005571 if (restore) {
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005572 params.restore();
Mitsuru Oshima3d914922009-05-13 22:29:15 -07005573 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07005574
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005575 if (mTranslator != null) {
5576 mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
Dianne Hackbornc4aad012013-02-22 15:05:25 -08005577 mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005578 mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5579 mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
Adrian Roosfa104232014-06-20 16:10:14 -07005580 mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07005581 }
Mitsuru Oshima8169dae2009-04-28 18:12:09 -07005582 return relayoutResult;
5583 }
Romain Guy8506ab42009-06-11 17:35:47 -07005584
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07005585 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 * {@inheritDoc}
5587 */
Igor Murashkina86ab6402013-08-30 12:58:36 -07005588 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 public void playSoundEffect(int effectId) {
5590 checkThread();
5591
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07005592 try {
5593 final AudioManager audioManager = getAudioManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07005595 switch (effectId) {
5596 case SoundEffectConstants.CLICK:
5597 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5598 return;
5599 case SoundEffectConstants.NAVIGATION_DOWN:
5600 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5601 return;
5602 case SoundEffectConstants.NAVIGATION_LEFT:
5603 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5604 return;
5605 case SoundEffectConstants.NAVIGATION_RIGHT:
5606 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5607 return;
5608 case SoundEffectConstants.NAVIGATION_UP:
5609 audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5610 return;
5611 default:
5612 throw new IllegalArgumentException("unknown effect id " + effectId +
5613 " not defined in " + SoundEffectConstants.class.getCanonicalName());
5614 }
5615 } catch (IllegalStateException e) {
5616 // Exception thrown by getAudioManager() when mView is null
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005617 Log.e(mTag, "FATAL EXCEPTION when attempting to play sound effect: " + e);
Jean-Michel Trivi13b18fd2010-05-05 09:18:15 -07005618 e.printStackTrace();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 }
5620 }
5621
5622 /**
5623 * {@inheritDoc}
5624 */
Igor Murashkina86ab6402013-08-30 12:58:36 -07005625 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 public boolean performHapticFeedback(int effectId, boolean always) {
5627 try {
Jeff Brown98365d72012-08-19 20:30:52 -07005628 return mWindowSession.performHapticFeedback(mWindow, effectId, always);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 } catch (RemoteException e) {
5630 return false;
5631 }
5632 }
5633
5634 /**
5635 * {@inheritDoc}
5636 */
Igor Murashkina86ab6402013-08-30 12:58:36 -07005637 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 public View focusSearch(View focused, int direction) {
5639 checkThread();
5640 if (!(mView instanceof ViewGroup)) {
5641 return null;
5642 }
5643 return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5644 }
5645
5646 public void debug() {
5647 mView.debug();
5648 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07005649
Jeff Brown5182c782013-10-15 20:31:52 -07005650 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5651 String innerPrefix = prefix + " ";
5652 writer.print(prefix); writer.println("ViewRoot:");
5653 writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5654 writer.print(" mRemoved="); writer.println(mRemoved);
5655 writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5656 writer.println(mConsumeBatchedInputScheduled);
Michael Wright9d744c72014-02-18 21:27:42 -08005657 writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5658 writer.println(mConsumeBatchedInputImmediatelyScheduled);
Jeff Brown5182c782013-10-15 20:31:52 -07005659 writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5660 writer.println(mPendingInputEventCount);
5661 writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5662 writer.println(mProcessInputEventsScheduled);
5663 writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5664 writer.print(mTraversalScheduled);
Daniel Koulomzin087ae472015-12-16 17:52:25 -05005665 writer.print(innerPrefix); writer.print("mIsAmbientMode=");
5666 writer.print(mIsAmbientMode);
Jeff Brown5182c782013-10-15 20:31:52 -07005667 if (mTraversalScheduled) {
5668 writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5669 } else {
5670 writer.println();
5671 }
5672 mFirstInputStage.dump(innerPrefix, writer);
5673
5674 mChoreographer.dump(prefix, writer);
5675
5676 writer.print(prefix); writer.println("View Hierarchy:");
5677 dumpViewHierarchy(innerPrefix, writer, mView);
5678 }
5679
5680 private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5681 writer.print(prefix);
5682 if (view == null) {
5683 writer.println("null");
5684 return;
5685 }
5686 writer.println(view.toString());
5687 if (!(view instanceof ViewGroup)) {
5688 return;
5689 }
5690 ViewGroup grp = (ViewGroup)view;
5691 final int N = grp.getChildCount();
5692 if (N <= 0) {
5693 return;
5694 }
5695 prefix = prefix + " ";
5696 for (int i=0; i<N; i++) {
5697 dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5698 }
5699 }
5700
Romain Guy211370f2012-02-01 16:10:55 -08005701 public void dumpGfxInfo(int[] info) {
Romain Guy54ab3472012-06-14 12:52:53 -07005702 info[0] = info[1] = 0;
Romain Guy65b345f2011-07-27 18:51:50 -07005703 if (mView != null) {
5704 getGfxInfo(mView, info);
Romain Guy65b345f2011-07-27 18:51:50 -07005705 }
5706 }
5707
Romain Guya998dff2012-03-23 18:58:36 -07005708 private static void getGfxInfo(View view, int[] info) {
Chris Craik64a12e12014-03-28 18:12:12 -07005709 RenderNode renderNode = view.mRenderNode;
Romain Guy65b345f2011-07-27 18:51:50 -07005710 info[0]++;
Chris Craik64a12e12014-03-28 18:12:12 -07005711 if (renderNode != null) {
John Reckfe5e7b72014-05-23 17:42:28 -07005712 info[1] += renderNode.getDebugSize();
Romain Guy65b345f2011-07-27 18:51:50 -07005713 }
5714
5715 if (view instanceof ViewGroup) {
5716 ViewGroup group = (ViewGroup) view;
5717
5718 int count = group.getChildCount();
5719 for (int i = 0; i < count; i++) {
5720 getGfxInfo(group.getChildAt(i), info);
5721 }
5722 }
5723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724
Craig Mautner8f303ad2013-06-14 11:32:22 -07005725 /**
5726 * @param immediate True, do now if not in traversal. False, put on queue and do later.
5727 * @return True, request has been queued. False, request has been completed.
5728 */
5729 boolean die(boolean immediate) {
Craig Mautnerdf2390a2012-08-29 20:59:22 -07005730 // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5731 // done by dispatchDetachedFromWindow will cause havoc on return.
5732 if (immediate && !mIsInTraversal) {
Dianne Hackborn94d69142009-09-28 22:14:42 -07005733 doDie();
Craig Mautner8f303ad2013-06-14 11:32:22 -07005734 return false;
Dianne Hackborn94d69142009-09-28 22:14:42 -07005735 }
Craig Mautner8f303ad2013-06-14 11:32:22 -07005736
5737 if (!mIsDrawing) {
5738 destroyHardwareRenderer();
5739 } else {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005740 Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
Craig Mautner8f303ad2013-06-14 11:32:22 -07005741 " window=" + this + ", title=" + mWindowAttributes.getTitle());
5742 }
5743 mHandler.sendEmptyMessage(MSG_DIE);
5744 return true;
Dianne Hackborn94d69142009-09-28 22:14:42 -07005745 }
5746
5747 void doDie() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 checkThread();
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005749 if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 synchronized (this) {
Craig Mautner8f303ad2013-06-14 11:32:22 -07005751 if (mRemoved) {
5752 return;
5753 }
5754 mRemoved = true;
Romain Guy16260e72011-09-01 14:26:11 -07005755 if (mAdded) {
Romain Guy16260e72011-09-01 14:26:11 -07005756 dispatchDetachedFromWindow();
5757 }
5758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 if (mAdded && !mFirst) {
Romain Guy29d89972010-09-22 16:10:57 -07005760 destroyHardwareRenderer();
5761
Romain Guyedbca122012-04-04 18:25:53 -07005762 if (mView != null) {
5763 int viewVisibility = mView.getVisibility();
5764 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5765 if (mWindowAttributesChanged || viewVisibilityChanged) {
5766 // If layout params have been changed, first give them
5767 // to the window manager to make sure it has the correct
5768 // animation info.
5769 try {
5770 if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
Jeff Brown98365d72012-08-19 20:30:52 -07005771 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5772 mWindowSession.finishDrawing(mWindow);
Romain Guyedbca122012-04-04 18:25:53 -07005773 }
5774 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 }
Craig Mautner8f303ad2013-06-14 11:32:22 -07005777
Romain Guyedbca122012-04-04 18:25:53 -07005778 mSurface.release();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 }
Romain Guyedbca122012-04-04 18:25:53 -07005781
5782 mAdded = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 }
Craig Mautner05eb7302013-06-03 17:24:21 -07005784 WindowManagerGlobal.getInstance().doRemoveView(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 }
5786
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005787 public void requestUpdateConfiguration(Configuration config) {
Jeff Browna175a5b2012-02-15 19:18:31 -08005788 Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5789 mHandler.sendMessage(msg);
Dianne Hackborn5fd21692011-06-07 14:09:47 -07005790 }
5791
Dianne Hackborna53de062012-05-08 18:53:51 -07005792 public void loadSystemProperties() {
Romain Guy5bb3c732012-11-29 17:52:58 -08005793 mHandler.post(new Runnable() {
5794 @Override
5795 public void run() {
5796 // Profiling
5797 mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5798 profileRendering(mAttachInfo.mHasWindowFocus);
5799
5800 // Hardware rendering
5801 if (mAttachInfo.mHardwareRenderer != null) {
John Reckcec24ae2013-11-05 13:27:50 -08005802 if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
Romain Guy5bb3c732012-11-29 17:52:58 -08005803 invalidate();
5804 }
5805 }
5806
5807 // Layout debugging
5808 boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5809 if (layout != mAttachInfo.mDebugLayout) {
5810 mAttachInfo.mDebugLayout = layout;
5811 if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5812 mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5813 }
5814 }
Dianne Hackborna53de062012-05-08 18:53:51 -07005815 }
Romain Guy5bb3c732012-11-29 17:52:58 -08005816 });
Dianne Hackborna53de062012-05-08 18:53:51 -07005817 }
5818
Romain Guy29d89972010-09-22 16:10:57 -07005819 private void destroyHardwareRenderer() {
John Reck51aaf902015-12-02 15:08:07 -08005820 ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
Romain Guya998dff2012-03-23 18:58:36 -07005821
5822 if (hardwareRenderer != null) {
5823 if (mView != null) {
5824 hardwareRenderer.destroyHardwareResources(mView);
5825 }
John Reckf47a5942014-06-30 16:20:04 -07005826 hardwareRenderer.destroy();
Romain Guya998dff2012-03-23 18:58:36 -07005827 hardwareRenderer.setRequested(false);
5828
Chris Craikd36a81f2014-07-17 10:16:51 -07005829 mAttachInfo.mHardwareRenderer = null;
5830 mAttachInfo.mHardwareAccelerated = false;
Romain Guy29d89972010-09-22 16:10:57 -07005831 }
5832 }
5833
Jeff Browna175a5b2012-02-15 19:18:31 -08005834 public void dispatchFinishInputConnection(InputConnection connection) {
5835 Message msg = mHandler.obtainMessage(MSG_FINISH_INPUT_CONNECTION, connection);
5836 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
Mitsuru Oshima3d914922009-05-13 22:29:15 -07005838
Dianne Hackbornc4aad012013-02-22 15:05:25 -08005839 public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
Filip Gruszczynski2217f612015-05-26 11:32:08 -07005840 Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08005841 Configuration newConfig, Rect backDropFrame, boolean forceLayout) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005842 if (DEBUG_LAYOUT) Log.v(mTag, "Resizing " + this + ": frame=" + frame.toShortString()
Svetoslav Ganov758143e2012-08-06 16:40:27 -07005843 + " contentInsets=" + contentInsets.toShortString()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 + " visibleInsets=" + visibleInsets.toShortString()
Chong Zhangd153c4f2015-11-06 20:26:40 -08005845 + " reportDraw=" + reportDraw
5846 + " backDropFrame=" + backDropFrame);
Chong Zhangdcee1de2015-10-06 10:26:00 -07005847
5848 // Tell all listeners that we are resizing the window so that the chrome can get
5849 // updated as fast as possible on a separate thread,
5850 if (mDragResizing) {
Jorim Jaggi9511b0f2016-01-29 19:12:44 -08005851 boolean fullscreen = frame.equals(backDropFrame);
Chong Zhangdcee1de2015-10-06 10:26:00 -07005852 synchronized (mWindowCallbacks) {
5853 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
Jorim Jaggi9511b0f2016-01-29 19:12:44 -08005854 mWindowCallbacks.get(i).onWindowSizeIsChanging(backDropFrame, fullscreen,
5855 visibleInsets, stableInsets);
Chong Zhangdcee1de2015-10-06 10:26:00 -07005856 }
5857 }
5858 }
5859
Svetoslav Ganov758143e2012-08-06 16:40:27 -07005860 Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005861 if (mTranslator != null) {
Svetoslav Ganov758143e2012-08-06 16:40:27 -07005862 mTranslator.translateRectInScreenToAppWindow(frame);
Dianne Hackbornc4aad012013-02-22 15:05:25 -08005863 mTranslator.translateRectInScreenToAppWindow(overscanInsets);
Dianne Hackborn3556c9a2012-05-04 16:31:25 -07005864 mTranslator.translateRectInScreenToAppWindow(contentInsets);
Mitsuru Oshima64f59342009-06-21 00:03:11 -07005865 mTranslator.translateRectInScreenToAppWindow(visibleInsets);
Mitsuru Oshima9189cab2009-06-03 11:19:12 -07005866 }
Svetoslav Ganov758143e2012-08-06 16:40:27 -07005867 SomeArgs args = SomeArgs.obtain();
5868 final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5869 args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5870 args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5871 args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5872 args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
Dianne Hackbornc4aad012013-02-22 15:05:25 -08005873 args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
Adrian Roosfa104232014-06-20 16:10:14 -07005874 args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
Filip Gruszczynski2217f612015-05-26 11:32:08 -07005875 args.arg7 = sameProcessCall ? new Rect(outsets) : outsets;
Jorim Jaggia7262a82015-11-03 15:15:40 +01005876 args.arg8 = sameProcessCall ? new Rect(backDropFrame) : backDropFrame;
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08005877 args.argi1 = forceLayout ? 1 : 0;
Svetoslav Ganov758143e2012-08-06 16:40:27 -07005878 msg.obj = args;
Jeff Browna175a5b2012-02-15 19:18:31 -08005879 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 }
Chet Haase1f4786b2011-11-02 10:51:52 -07005881
Craig Mautner5702d4d2012-06-30 14:10:16 -07005882 public void dispatchMoved(int newX, int newY) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08005883 if (DEBUG_LAYOUT) Log.v(mTag, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
Craig Mautner5702d4d2012-06-30 14:10:16 -07005884 if (mTranslator != null) {
5885 PointF point = new PointF(newX, newY);
5886 mTranslator.translatePointInScreenToAppWindow(point);
5887 newX = (int) (point.x + 0.5);
5888 newY = (int) (point.y + 0.5);
5889 }
5890 Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5891 mHandler.sendMessage(msg);
5892 }
5893
Jeff Brown4952dfd2011-11-30 19:23:22 -08005894 /**
5895 * Represents a pending input event that is waiting in a queue.
5896 *
5897 * Input events are processed in serial order by the timestamp specified by
Romain Guy211370f2012-02-01 16:10:55 -08005898 * {@link InputEvent#getEventTimeNano()}. In general, the input dispatcher delivers
Jeff Brown4952dfd2011-11-30 19:23:22 -08005899 * one input event to the application at a time and waits for the application
5900 * to finish handling it before delivering the next one.
5901 *
5902 * However, because the application or IME can synthesize and inject multiple
5903 * key events at a time without going through the input dispatcher, we end up
5904 * needing a queue on the application's side.
5905 */
5906 private static final class QueuedInputEvent {
Jeff Brownf9e989d2013-04-04 23:04:03 -07005907 public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5908 public static final int FLAG_DEFERRED = 1 << 1;
5909 public static final int FLAG_FINISHED = 1 << 2;
5910 public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5911 public static final int FLAG_RESYNTHESIZED = 1 << 4;
Michael Wright899d7052014-04-23 17:23:39 -07005912 public static final int FLAG_UNHANDLED = 1 << 5;
Jeff Brown4952dfd2011-11-30 19:23:22 -08005913
5914 public QueuedInputEvent mNext;
5915
5916 public InputEvent mEvent;
Jeff Brown32cbc38552011-12-01 14:01:49 -08005917 public InputEventReceiver mReceiver;
Jeff Brown4952dfd2011-11-30 19:23:22 -08005918 public int mFlags;
Jeff Brownf9e989d2013-04-04 23:04:03 -07005919
5920 public boolean shouldSkipIme() {
5921 if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5922 return true;
5923 }
5924 return mEvent instanceof MotionEvent
5925 && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5926 }
Michael Wright899d7052014-04-23 17:23:39 -07005927
5928 public boolean shouldSendToSynthesizer() {
5929 if ((mFlags & FLAG_UNHANDLED) != 0) {
5930 return true;
5931 }
5932
5933 return false;
5934 }
Michael Wright06a79252014-05-05 17:45:29 -07005935
5936 @Override
5937 public String toString() {
5938 StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5939 boolean hasPrevious = false;
5940 hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5941 hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5942 hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5943 hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5944 hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5945 hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5946 if (!hasPrevious) {
5947 sb.append("0");
5948 }
5949 sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5950 sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5951 sb.append(", mEvent=" + mEvent + "}");
5952 return sb.toString();
5953 }
5954
5955 private boolean flagToString(String name, int flag,
5956 boolean hasPrevious, StringBuilder sb) {
5957 if ((mFlags & flag) != 0) {
5958 if (hasPrevious) {
5959 sb.append("|");
5960 }
5961 sb.append(name);
5962 return true;
5963 }
5964 return hasPrevious;
5965 }
Jeff Brown4952dfd2011-11-30 19:23:22 -08005966 }
5967
5968 private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
Jeff Brown32cbc38552011-12-01 14:01:49 -08005969 InputEventReceiver receiver, int flags) {
Jeff Brown4952dfd2011-11-30 19:23:22 -08005970 QueuedInputEvent q = mQueuedInputEventPool;
5971 if (q != null) {
5972 mQueuedInputEventPoolSize -= 1;
5973 mQueuedInputEventPool = q.mNext;
5974 q.mNext = null;
5975 } else {
5976 q = new QueuedInputEvent();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005977 }
5978
Jeff Brown4952dfd2011-11-30 19:23:22 -08005979 q.mEvent = event;
Jeff Brown32cbc38552011-12-01 14:01:49 -08005980 q.mReceiver = receiver;
Jeff Brown4952dfd2011-11-30 19:23:22 -08005981 q.mFlags = flags;
Jeff Brown4952dfd2011-11-30 19:23:22 -08005982 return q;
5983 }
5984
5985 private void recycleQueuedInputEvent(QueuedInputEvent q) {
5986 q.mEvent = null;
Jeff Brown32cbc38552011-12-01 14:01:49 -08005987 q.mReceiver = null;
Jeff Brown4952dfd2011-11-30 19:23:22 -08005988
5989 if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
5990 mQueuedInputEventPoolSize += 1;
5991 q.mNext = mQueuedInputEventPool;
5992 mQueuedInputEventPool = q;
5993 }
5994 }
5995
Jeff Brownf9261d22012-02-03 13:49:15 -08005996 void enqueueInputEvent(InputEvent event) {
5997 enqueueInputEvent(event, null, 0, false);
5998 }
5999
Jeff Brown4952dfd2011-11-30 19:23:22 -08006000 void enqueueInputEvent(InputEvent event,
Jeff Brownf9261d22012-02-03 13:49:15 -08006001 InputEventReceiver receiver, int flags, boolean processImmediately) {
Michael Wright5bd69e62015-05-14 14:48:08 +01006002 adjustInputEventForCompatibility(event);
Jeff Brown32cbc38552011-12-01 14:01:49 -08006003 QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
Jeff Brown4952dfd2011-11-30 19:23:22 -08006004
Jeff Brown4952dfd2011-11-30 19:23:22 -08006005 // Always enqueue the input event in order, regardless of its time stamp.
6006 // We do this because the application or the IME may inject key events
6007 // in response to touch events and we want to ensure that the injected keys
6008 // are processed in the order they were received and we cannot trust that
6009 // the time stamp of injected events are monotonic.
Michael Wrightc8a7e542013-03-20 17:58:33 -07006010 QueuedInputEvent last = mPendingInputEventTail;
Jeff Brown4952dfd2011-11-30 19:23:22 -08006011 if (last == null) {
Michael Wrightc8a7e542013-03-20 17:58:33 -07006012 mPendingInputEventHead = q;
6013 mPendingInputEventTail = q;
Jeff Brown4952dfd2011-11-30 19:23:22 -08006014 } else {
Jeff Brown4952dfd2011-11-30 19:23:22 -08006015 last.mNext = q;
Michael Wrightc8a7e542013-03-20 17:58:33 -07006016 mPendingInputEventTail = q;
Jeff Brown4952dfd2011-11-30 19:23:22 -08006017 }
Michael Wright95ae9422013-03-14 10:58:50 -07006018 mPendingInputEventCount += 1;
6019 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6020 mPendingInputEventCount);
Jeff Brown4952dfd2011-11-30 19:23:22 -08006021
Jeff Brownf9261d22012-02-03 13:49:15 -08006022 if (processImmediately) {
6023 doProcessInputEvents();
6024 } else {
6025 scheduleProcessInputEvents();
6026 }
Jeff Brown4952dfd2011-11-30 19:23:22 -08006027 }
6028
6029 private void scheduleProcessInputEvents() {
Jeff Brown96e942d2011-11-30 19:55:01 -08006030 if (!mProcessInputEventsScheduled) {
6031 mProcessInputEventsScheduled = true;
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006032 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
6033 msg.setAsynchronous(true);
6034 mHandler.sendMessage(msg);
Jeff Brown4952dfd2011-11-30 19:23:22 -08006035 }
6036 }
6037
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006038 void doProcessInputEvents() {
Jeff Brownf9e989d2013-04-04 23:04:03 -07006039 // Deliver all pending input events in the queue.
Michael Wrightc8a7e542013-03-20 17:58:33 -07006040 while (mPendingInputEventHead != null) {
6041 QueuedInputEvent q = mPendingInputEventHead;
6042 mPendingInputEventHead = q.mNext;
6043 if (mPendingInputEventHead == null) {
6044 mPendingInputEventTail = null;
6045 }
Jeff Brown4952dfd2011-11-30 19:23:22 -08006046 q.mNext = null;
Jeff Brown29c0ed22013-01-14 13:50:37 -08006047
Michael Wright95ae9422013-03-14 10:58:50 -07006048 mPendingInputEventCount -= 1;
6049 Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6050 mPendingInputEventCount);
6051
John Reckba6adf62015-02-19 14:36:50 -08006052 long eventTime = q.mEvent.getEventTimeNano();
6053 long oldestEventTime = eventTime;
6054 if (q.mEvent instanceof MotionEvent) {
6055 MotionEvent me = (MotionEvent)q.mEvent;
6056 if (me.getHistorySize() > 0) {
6057 oldestEventTime = me.getHistoricalEventTimeNano(0);
6058 }
6059 }
6060 mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
6061
Jeff Brownf9e989d2013-04-04 23:04:03 -07006062 deliverInputEvent(q);
Jeff Brown4952dfd2011-11-30 19:23:22 -08006063 }
6064
6065 // We are done processing all input events that we can process right now
6066 // so we can clear the pending flag immediately.
Jeff Brown96e942d2011-11-30 19:55:01 -08006067 if (mProcessInputEventsScheduled) {
6068 mProcessInputEventsScheduled = false;
Jeff Browna175a5b2012-02-15 19:18:31 -08006069 mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
Jeff Brown4952dfd2011-11-30 19:23:22 -08006070 }
6071 }
6072
Jeff Brownf9e989d2013-04-04 23:04:03 -07006073 private void deliverInputEvent(QueuedInputEvent q) {
Michael Wrightd2c3adc2014-02-18 22:50:50 -08006074 Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6075 q.mEvent.getSequenceNumber());
6076 if (mInputEventConsistencyVerifier != null) {
6077 mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
6078 }
Michael Wrightc8a7e542013-03-20 17:58:33 -07006079
Michael Wright899d7052014-04-23 17:23:39 -07006080 InputStage stage;
6081 if (q.shouldSendToSynthesizer()) {
6082 stage = mSyntheticInputStage;
6083 } else {
6084 stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
6085 }
6086
Michael Wrightd2c3adc2014-02-18 22:50:50 -08006087 if (stage != null) {
6088 stage.deliver(q);
6089 } else {
6090 finishInputEvent(q);
Michael Wrightbf020962013-03-28 17:27:50 -07006091 }
Michael Wrightbf020962013-03-28 17:27:50 -07006092 }
6093
Jeff Brownf9e989d2013-04-04 23:04:03 -07006094 private void finishInputEvent(QueuedInputEvent q) {
Michael Wrightd2c3adc2014-02-18 22:50:50 -08006095 Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6096 q.mEvent.getSequenceNumber());
Michael Wright9d744c72014-02-18 21:27:42 -08006097
Jeff Brown32cbc38552011-12-01 14:01:49 -08006098 if (q.mReceiver != null) {
Jeff Brownf9e989d2013-04-04 23:04:03 -07006099 boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
Jeff Brown32cbc38552011-12-01 14:01:49 -08006100 q.mReceiver.finishInputEvent(q.mEvent, handled);
Jeff Brown92cc2d82011-12-02 01:19:47 -08006101 } else {
6102 q.mEvent.recycleIfNeededAfterDispatch();
Jeff Brown4952dfd2011-11-30 19:23:22 -08006103 }
6104
6105 recycleQueuedInputEvent(q);
Jeff Brown29c0ed22013-01-14 13:50:37 -08006106 }
Jeff Brown4952dfd2011-11-30 19:23:22 -08006107
Michael Wright5bd69e62015-05-14 14:48:08 +01006108 private void adjustInputEventForCompatibility(InputEvent e) {
Dianne Hackborn0e3de6c2015-07-29 15:20:21 -07006109 if (mTargetSdkVersion < Build.VERSION_CODES.M && e instanceof MotionEvent) {
Michael Wright5bd69e62015-05-14 14:48:08 +01006110 MotionEvent motion = (MotionEvent) e;
6111 final int mask =
6112 MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY;
6113 final int buttonState = motion.getButtonState();
6114 final int compatButtonState = (buttonState & mask) >> 4;
6115 if (compatButtonState != 0) {
6116 motion.setButtonState(buttonState | compatButtonState);
6117 }
6118 }
6119 }
6120
Jeff Brownf9e989d2013-04-04 23:04:03 -07006121 static boolean isTerminalInputEvent(InputEvent event) {
Jeff Brown29c0ed22013-01-14 13:50:37 -08006122 if (event instanceof KeyEvent) {
6123 final KeyEvent keyEvent = (KeyEvent)event;
6124 return keyEvent.getAction() == KeyEvent.ACTION_UP;
6125 } else {
6126 final MotionEvent motionEvent = (MotionEvent)event;
6127 final int action = motionEvent.getAction();
6128 return action == MotionEvent.ACTION_UP
6129 || action == MotionEvent.ACTION_CANCEL
6130 || action == MotionEvent.ACTION_HOVER_EXIT;
Jeff Brown4952dfd2011-11-30 19:23:22 -08006131 }
6132 }
6133
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006134 void scheduleConsumeBatchedInput() {
6135 if (!mConsumeBatchedInputScheduled) {
6136 mConsumeBatchedInputScheduled = true;
6137 mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
6138 mConsumedBatchedInputRunnable, null);
Jeff Brown4a06c802012-02-15 15:06:01 -08006139 }
6140 }
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006141
6142 void unscheduleConsumeBatchedInput() {
6143 if (mConsumeBatchedInputScheduled) {
6144 mConsumeBatchedInputScheduled = false;
6145 mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
6146 mConsumedBatchedInputRunnable, null);
6147 }
6148 }
6149
Michael Wright9d744c72014-02-18 21:27:42 -08006150 void scheduleConsumeBatchedInputImmediately() {
6151 if (!mConsumeBatchedInputImmediatelyScheduled) {
6152 unscheduleConsumeBatchedInput();
6153 mConsumeBatchedInputImmediatelyScheduled = true;
6154 mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
6155 }
6156 }
6157
Jeff Brown771526c2012-04-27 15:13:25 -07006158 void doConsumeBatchedInput(long frameTimeNanos) {
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006159 if (mConsumeBatchedInputScheduled) {
6160 mConsumeBatchedInputScheduled = false;
Jeff Brown330314c2012-04-27 02:20:22 -07006161 if (mInputEventReceiver != null) {
Michael Wright9d744c72014-02-18 21:27:42 -08006162 if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
6163 && frameTimeNanos != -1) {
Michael Wright62ce65d2013-10-25 14:50:36 -07006164 // If we consumed a batch here, we want to go ahead and schedule the
6165 // consumption of batched input events on the next frame. Otherwise, we would
6166 // wait until we have more input events pending and might get starved by other
Michael Wright9d744c72014-02-18 21:27:42 -08006167 // things occurring in the process. If the frame time is -1, however, then
6168 // we're in a non-batching mode, so there's no need to schedule this.
Michael Wright62ce65d2013-10-25 14:50:36 -07006169 scheduleConsumeBatchedInput();
6170 }
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006171 }
Jeff Brown330314c2012-04-27 02:20:22 -07006172 doProcessInputEvents();
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006173 }
6174 }
6175
6176 final class TraversalRunnable implements Runnable {
6177 @Override
6178 public void run() {
6179 doTraversal();
6180 }
6181 }
6182 final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
Jeff Brown4a06c802012-02-15 15:06:01 -08006183
Jeff Brown32cbc38552011-12-01 14:01:49 -08006184 final class WindowInputEventReceiver extends InputEventReceiver {
6185 public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
6186 super(inputChannel, looper);
Jeff Brown46b9ac02010-04-22 18:58:52 -07006187 }
Jeff Brown32cbc38552011-12-01 14:01:49 -08006188
6189 @Override
6190 public void onInputEvent(InputEvent event) {
Jeff Brownf9261d22012-02-03 13:49:15 -08006191 enqueueInputEvent(event, this, 0, true);
Jeff Brown32cbc38552011-12-01 14:01:49 -08006192 }
Jeff Brown072ec962012-02-07 14:46:57 -08006193
6194 @Override
6195 public void onBatchedInputEventPending() {
Michael Wright9d744c72014-02-18 21:27:42 -08006196 if (mUnbufferedInputDispatch) {
6197 super.onBatchedInputEventPending();
6198 } else {
6199 scheduleConsumeBatchedInput();
6200 }
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006201 }
6202
6203 @Override
6204 public void dispose() {
6205 unscheduleConsumeBatchedInput();
6206 super.dispose();
Jeff Brown072ec962012-02-07 14:46:57 -08006207 }
Jeff Brown32cbc38552011-12-01 14:01:49 -08006208 }
6209 WindowInputEventReceiver mInputEventReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006211 final class ConsumeBatchedInputRunnable implements Runnable {
6212 @Override
6213 public void run() {
Jeff Brown771526c2012-04-27 15:13:25 -07006214 doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006215 }
6216 }
6217 final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
6218 new ConsumeBatchedInputRunnable();
6219 boolean mConsumeBatchedInputScheduled;
6220
Michael Wright9d744c72014-02-18 21:27:42 -08006221 final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
6222 @Override
6223 public void run() {
6224 doConsumeBatchedInput(-1);
6225 }
6226 }
6227 final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
6228 new ConsumeBatchedInputImmediatelyRunnable();
6229 boolean mConsumeBatchedInputImmediatelyScheduled;
6230
Jeff Brown6cb7b462012-03-05 13:21:17 -08006231 final class InvalidateOnAnimationRunnable implements Runnable {
6232 private boolean mPosted;
Igor Murashkina86ab6402013-08-30 12:58:36 -07006233 private final ArrayList<View> mViews = new ArrayList<View>();
6234 private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
Jeff Brown6cb7b462012-03-05 13:21:17 -08006235 new ArrayList<AttachInfo.InvalidateInfo>();
6236 private View[] mTempViews;
6237 private AttachInfo.InvalidateInfo[] mTempViewRects;
6238
6239 public void addView(View view) {
6240 synchronized (this) {
6241 mViews.add(view);
6242 postIfNeededLocked();
6243 }
6244 }
6245
6246 public void addViewRect(AttachInfo.InvalidateInfo info) {
6247 synchronized (this) {
6248 mViewRects.add(info);
6249 postIfNeededLocked();
6250 }
6251 }
6252
6253 public void removeView(View view) {
6254 synchronized (this) {
6255 mViews.remove(view);
6256
6257 for (int i = mViewRects.size(); i-- > 0; ) {
6258 AttachInfo.InvalidateInfo info = mViewRects.get(i);
6259 if (info.target == view) {
6260 mViewRects.remove(i);
Svetoslav Ganovabae2a12012-11-27 16:59:37 -08006261 info.recycle();
Jeff Brown6cb7b462012-03-05 13:21:17 -08006262 }
6263 }
6264
6265 if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006266 mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
Jeff Brown6cb7b462012-03-05 13:21:17 -08006267 mPosted = false;
6268 }
6269 }
6270 }
6271
6272 @Override
6273 public void run() {
6274 final int viewCount;
6275 final int viewRectCount;
6276 synchronized (this) {
6277 mPosted = false;
6278
6279 viewCount = mViews.size();
6280 if (viewCount != 0) {
6281 mTempViews = mViews.toArray(mTempViews != null
6282 ? mTempViews : new View[viewCount]);
6283 mViews.clear();
6284 }
6285
6286 viewRectCount = mViewRects.size();
6287 if (viewRectCount != 0) {
6288 mTempViewRects = mViewRects.toArray(mTempViewRects != null
6289 ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6290 mViewRects.clear();
6291 }
6292 }
6293
6294 for (int i = 0; i < viewCount; i++) {
6295 mTempViews[i].invalidate();
Adam Powell3e3c4ee2012-05-16 17:34:21 -07006296 mTempViews[i] = null;
Jeff Brown6cb7b462012-03-05 13:21:17 -08006297 }
6298
6299 for (int i = 0; i < viewRectCount; i++) {
6300 final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6301 info.target.invalidate(info.left, info.top, info.right, info.bottom);
Svetoslav Ganovabae2a12012-11-27 16:59:37 -08006302 info.recycle();
Jeff Brown6cb7b462012-03-05 13:21:17 -08006303 }
6304 }
6305
6306 private void postIfNeededLocked() {
6307 if (!mPosted) {
Jeff Brownebb2d8d2012-03-23 17:14:34 -07006308 mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
Jeff Brown6cb7b462012-03-05 13:21:17 -08006309 mPosted = true;
6310 }
6311 }
6312 }
6313 final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6314 new InvalidateOnAnimationRunnable();
6315
Jeff Browna175a5b2012-02-15 19:18:31 -08006316 public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6317 Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6318 mHandler.sendMessageDelayed(msg, delayMilliseconds);
6319 }
6320
Jeff Browna175a5b2012-02-15 19:18:31 -08006321 public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6322 long delayMilliseconds) {
6323 final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6324 mHandler.sendMessageDelayed(msg, delayMilliseconds);
6325 }
6326
Jeff Brown6cb7b462012-03-05 13:21:17 -08006327 public void dispatchInvalidateOnAnimation(View view) {
6328 mInvalidateOnAnimationRunnable.addView(view);
6329 }
6330
6331 public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6332 mInvalidateOnAnimationRunnable.addViewRect(info);
6333 }
6334
6335 public void cancelInvalidate(View view) {
6336 mHandler.removeMessages(MSG_INVALIDATE, view);
6337 // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6338 // them to the pool
6339 mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6340 mInvalidateOnAnimationRunnable.removeView(view);
6341 }
6342
keunyoung30f420f2013-08-02 14:23:10 -07006343 public void dispatchInputEvent(InputEvent event) {
Jae Seo6a6059a2014-04-17 21:35:29 -07006344 dispatchInputEvent(event, null);
6345 }
6346
6347 public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6348 SomeArgs args = SomeArgs.obtain();
6349 args.arg1 = event;
6350 args.arg2 = receiver;
6351 Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
Jeff Browne0dbd002012-02-15 19:34:58 -08006352 msg.setAsynchronous(true);
Jeff Browna175a5b2012-02-15 19:18:31 -08006353 mHandler.sendMessage(msg);
6354 }
6355
Michael Wright899d7052014-04-23 17:23:39 -07006356 public void synthesizeInputEvent(InputEvent event) {
6357 Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6358 msg.setAsynchronous(true);
6359 mHandler.sendMessage(msg);
6360 }
6361
Jeff Browna175a5b2012-02-15 19:18:31 -08006362 public void dispatchKeyFromIme(KeyEvent event) {
6363 Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
Jeff Browne0dbd002012-02-15 19:34:58 -08006364 msg.setAsynchronous(true);
Jeff Browna175a5b2012-02-15 19:18:31 -08006365 mHandler.sendMessage(msg);
Jeff Browncb1404e2011-01-15 18:14:15 -08006366 }
6367
Michael Wright899d7052014-04-23 17:23:39 -07006368 /**
6369 * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6370 *
6371 * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6372 * passes in.
6373 */
Michael Wright3da28342014-04-22 17:00:11 -07006374 public void dispatchUnhandledInputEvent(InputEvent event) {
Michael Wright899d7052014-04-23 17:23:39 -07006375 if (event instanceof MotionEvent) {
6376 event = MotionEvent.obtain((MotionEvent) event);
Michael Wright3da28342014-04-22 17:00:11 -07006377 }
Michael Wright899d7052014-04-23 17:23:39 -07006378 synthesizeInputEvent(event);
Michael Wright3da28342014-04-22 17:00:11 -07006379 }
6380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 public void dispatchAppVisibility(boolean visible) {
Jeff Browna175a5b2012-02-15 19:18:31 -08006382 Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 msg.arg1 = visible ? 1 : 0;
Jeff Browna175a5b2012-02-15 19:18:31 -08006384 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 }
6386
6387 public void dispatchGetNewSurface() {
Jeff Browna175a5b2012-02-15 19:18:31 -08006388 Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6389 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 }
6391
6392 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6393 Message msg = Message.obtain();
Jeff Browna175a5b2012-02-15 19:18:31 -08006394 msg.what = MSG_WINDOW_FOCUS_CHANGED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 msg.arg1 = hasFocus ? 1 : 0;
6396 msg.arg2 = inTouchMode ? 1 : 0;
Jeff Browna175a5b2012-02-15 19:18:31 -08006397 mHandler.sendMessage(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 }
6399
Craig Mautner9c795042014-10-28 19:59:59 -07006400 public void dispatchWindowShown() {
6401 mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6402 }
6403
Dianne Hackbornffa42482009-09-23 22:20:11 -07006404 public void dispatchCloseSystemDialogs(String reason) {
6405 Message msg = Message.obtain();
Jeff Browna175a5b2012-02-15 19:18:31 -08006406 msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
Dianne Hackbornffa42482009-09-23 22:20:11 -07006407 msg.obj = reason;
Jeff Browna175a5b2012-02-15 19:18:31 -08006408 mHandler.sendMessage(msg);
Dianne Hackbornffa42482009-09-23 22:20:11 -07006409 }
Christopher Tatea53146c2010-09-07 11:57:52 -07006410
6411 public void dispatchDragEvent(DragEvent event) {
Chris Tate91e9bb32010-10-12 12:58:43 -07006412 final int what;
6413 if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
Jeff Browna175a5b2012-02-15 19:18:31 -08006414 what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6415 mHandler.removeMessages(what);
Chris Tate91e9bb32010-10-12 12:58:43 -07006416 } else {
Jeff Browna175a5b2012-02-15 19:18:31 -08006417 what = MSG_DISPATCH_DRAG_EVENT;
Chris Tate91e9bb32010-10-12 12:58:43 -07006418 }
Jeff Browna175a5b2012-02-15 19:18:31 -08006419 Message msg = mHandler.obtainMessage(what, event);
6420 mHandler.sendMessage(msg);
Christopher Tatea53146c2010-09-07 11:57:52 -07006421 }
6422
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08006423 public void updatePointerIcon(float x, float y) {
6424 final int what = MSG_UPDATE_POINTER_ICON;
6425 mHandler.removeMessages(what);
6426 final long now = SystemClock.uptimeMillis();
6427 final MotionEvent event = MotionEvent.obtain(
6428 0, now, MotionEvent.ACTION_HOVER_MOVE, x, y, 0);
6429 Message msg = mHandler.obtainMessage(what, event);
6430 mHandler.sendMessage(msg);
6431 }
6432
Dianne Hackborn9a230e02011-10-06 11:51:27 -07006433 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6434 int localValue, int localChanges) {
6435 SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6436 args.seq = seq;
6437 args.globalVisibility = globalVisibility;
6438 args.localValue = localValue;
6439 args.localChanges = localChanges;
Jeff Browna175a5b2012-02-15 19:18:31 -08006440 mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6441 }
6442
6443 public void dispatchCheckFocus() {
6444 if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6445 // This will result in a call to checkFocus() below.
6446 mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6447 }
Joe Onorato664644d2011-01-23 17:53:23 -08006448 }
6449
Clara Bayarri75e09792015-07-29 16:20:40 +01006450 public void dispatchRequestKeyboardShortcuts(IResultReceiver receiver) {
6451 mHandler.obtainMessage(MSG_REQUEST_KEYBOARD_SHORTCUTS, receiver).sendToTarget();
6452 }
6453
svetoslavganov75986cf2009-05-14 22:28:01 -07006454 /**
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07006455 * Post a callback to send a
6456 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
Svetoslav Ganova0156172011-06-26 17:55:44 -07006457 * This event is send at most once every
6458 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07006459 */
Alan Viverette77e9a282013-09-12 17:16:09 -07006460 private void postSendWindowContentChangedCallback(View source, int changeType) {
Svetoslav Ganova0156172011-06-26 17:55:44 -07006461 if (mSendWindowContentChangedAccessibilityEvent == null) {
6462 mSendWindowContentChangedAccessibilityEvent =
6463 new SendWindowContentChangedAccessibilityEvent();
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07006464 }
Alan Viverette77e9a282013-09-12 17:16:09 -07006465 mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07006466 }
6467
6468 /**
6469 * Remove a posted callback to send a
6470 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6471 */
6472 private void removeSendWindowContentChangedCallback() {
Svetoslav Ganova0156172011-06-26 17:55:44 -07006473 if (mSendWindowContentChangedAccessibilityEvent != null) {
Jeff Browna175a5b2012-02-15 19:18:31 -08006474 mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07006475 }
6476 }
6477
Igor Murashkina86ab6402013-08-30 12:58:36 -07006478 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 public boolean showContextMenuForChild(View originalView) {
6480 return false;
6481 }
6482
Igor Murashkina86ab6402013-08-30 12:58:36 -07006483 @Override
Oren Blasberged391262015-09-01 12:12:51 -07006484 public boolean showContextMenuForChild(View originalView, float x, float y) {
6485 return false;
6486 }
6487
6488 @Override
Adam Powell6e346362010-07-23 10:18:23 -07006489 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6490 return null;
6491 }
6492
Igor Murashkina86ab6402013-08-30 12:58:36 -07006493 @Override
Clara Bayarri4423d912015-03-02 19:42:48 +00006494 public ActionMode startActionModeForChild(
6495 View originalView, ActionMode.Callback callback, int type) {
6496 return null;
6497 }
6498
6499 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 public void createContextMenu(ContextMenu menu) {
6501 }
6502
Igor Murashkina86ab6402013-08-30 12:58:36 -07006503 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 public void childDrawableStateChanged(View child) {
6505 }
6506
Igor Murashkina86ab6402013-08-30 12:58:36 -07006507 @Override
Svetoslav Ganov736c2752011-04-22 18:30:36 -07006508 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
George Mount41725de2015-04-09 08:23:05 -07006509 if (mView == null || mStopped || mPausedForTransition) {
Svetoslav Ganov736c2752011-04-22 18:30:36 -07006510 return false;
6511 }
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07006512 // Intercept accessibility focus events fired by virtual nodes to keep
6513 // track of accessibility focus position in such nodes.
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006514 final int eventType = event.getEventType();
6515 switch (eventType) {
6516 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07006517 final long sourceNodeId = event.getSourceNodeId();
6518 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6519 sourceNodeId);
6520 View source = mView.findViewByAccessibilityId(accessibilityViewId);
6521 if (source != null) {
6522 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6523 if (provider != null) {
Svetoslavb3ba1d42014-09-26 15:20:40 -07006524 final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6525 sourceNodeId);
6526 final AccessibilityNodeInfo node;
6527 if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6528 node = provider.createAccessibilityNodeInfo(
6529 AccessibilityNodeProvider.HOST_VIEW_ID);
6530 } else {
6531 node = provider.createAccessibilityNodeInfo(virtualNodeId);
6532 }
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07006533 setAccessibilityFocus(source, node);
6534 }
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006535 }
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006536 } break;
6537 case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
Svetoslav Ganov45a02e02012-06-17 15:07:29 -07006538 final long sourceNodeId = event.getSourceNodeId();
6539 final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6540 sourceNodeId);
6541 View source = mView.findViewByAccessibilityId(accessibilityViewId);
6542 if (source != null) {
6543 AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6544 if (provider != null) {
6545 setAccessibilityFocus(null, null);
6546 }
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006547 }
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006548 } break;
Svetoslavf0c758b2014-09-03 17:47:37 -07006549
6550
6551 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
Alan Viverette34457f52015-03-25 13:09:20 -07006552 handleWindowContentChangedEvent(event);
Svetoslavf0c758b2014-09-03 17:47:37 -07006553 } break;
Svetoslav Ganov791fd312012-05-14 15:12:30 -07006554 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006555 mAccessibilityManager.sendAccessibilityEvent(event);
Svetoslav Ganov736c2752011-04-22 18:30:36 -07006556 return true;
6557 }
6558
Alan Viverette34457f52015-03-25 13:09:20 -07006559 /**
6560 * Updates the focused virtual view, when necessary, in response to a
6561 * content changed event.
6562 * <p>
6563 * This is necessary to get updated bounds after a position change.
6564 *
6565 * @param event an accessibility event of type
6566 * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6567 */
6568 private void handleWindowContentChangedEvent(AccessibilityEvent event) {
Alan Viverette25acc7e2015-05-19 11:32:08 -07006569 final View focusedHost = mAccessibilityFocusedHost;
6570 if (focusedHost == null || mAccessibilityFocusedVirtualView == null) {
6571 // No virtual view focused, nothing to do here.
Alan Viverette34457f52015-03-25 13:09:20 -07006572 return;
6573 }
6574
Alan Viverette25acc7e2015-05-19 11:32:08 -07006575 final AccessibilityNodeProvider provider = focusedHost.getAccessibilityNodeProvider();
Alan Viverette34457f52015-03-25 13:09:20 -07006576 if (provider == null) {
Alan Viverette25acc7e2015-05-19 11:32:08 -07006577 // Error state: virtual view with no provider. Clear focus.
6578 mAccessibilityFocusedHost = null;
6579 mAccessibilityFocusedVirtualView = null;
6580 focusedHost.clearAccessibilityFocusNoCallbacks();
Alan Viverette34457f52015-03-25 13:09:20 -07006581 return;
6582 }
6583
6584 // We only care about change types that may affect the bounds of the
6585 // focused virtual view.
6586 final int changes = event.getContentChangeTypes();
6587 if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
6588 && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6589 return;
6590 }
6591
6592 final long eventSourceNodeId = event.getSourceNodeId();
6593 final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
6594
6595 // Search up the tree for subtree containment.
6596 boolean hostInSubtree = false;
6597 View root = mAccessibilityFocusedHost;
6598 while (root != null && !hostInSubtree) {
6599 if (changedViewId == root.getAccessibilityViewId()) {
6600 hostInSubtree = true;
6601 } else {
6602 final ViewParent parent = root.getParent();
6603 if (parent instanceof View) {
6604 root = (View) parent;
6605 } else {
6606 root = null;
6607 }
6608 }
6609 }
6610
6611 // We care only about changes in subtrees containing the host view.
6612 if (!hostInSubtree) {
6613 return;
6614 }
6615
6616 final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
6617 int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
6618 if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6619 // TODO: Should we clear the focused virtual view?
6620 focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID;
6621 }
6622
6623 // Refresh the node for the focused virtual view.
Alan Viverettea7ea65e2015-05-15 11:30:21 -07006624 final Rect oldBounds = mTempRect;
6625 mAccessibilityFocusedVirtualView.getBoundsInScreen(oldBounds);
Alan Viverette34457f52015-03-25 13:09:20 -07006626 mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
Alan Viverette25acc7e2015-05-19 11:32:08 -07006627 if (mAccessibilityFocusedVirtualView == null) {
6628 // Error state: The node no longer exists. Clear focus.
6629 mAccessibilityFocusedHost = null;
6630 focusedHost.clearAccessibilityFocusNoCallbacks();
6631
6632 // This will probably fail, but try to keep the provider's internal
6633 // state consistent by clearing focus.
6634 provider.performAction(focusedChildId,
6635 AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS.getId(), null);
Alan Viverettea7ea65e2015-05-15 11:30:21 -07006636 invalidateRectOnScreen(oldBounds);
Alan Viverette25acc7e2015-05-19 11:32:08 -07006637 } else {
6638 // The node was refreshed, invalidate bounds if necessary.
6639 final Rect newBounds = mAccessibilityFocusedVirtualView.getBoundsInScreen();
6640 if (!oldBounds.equals(newBounds)) {
6641 oldBounds.union(newBounds);
6642 invalidateRectOnScreen(oldBounds);
6643 }
Alan Viverettea7ea65e2015-05-15 11:30:21 -07006644 }
Alan Viverette34457f52015-03-25 13:09:20 -07006645 }
6646
Svetoslav Ganov42138042012-03-20 11:51:39 -07006647 @Override
Alan Viverette77e9a282013-09-12 17:16:09 -07006648 public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6649 postSendWindowContentChangedCallback(source, changeType);
Svetoslav Ganov42138042012-03-20 11:51:39 -07006650 }
6651
Fabrice Di Meglio9dd4c5c2013-02-08 18:15:07 -08006652 @Override
6653 public boolean canResolveLayoutDirection() {
6654 return true;
6655 }
6656
6657 @Override
6658 public boolean isLayoutDirectionResolved() {
6659 return true;
6660 }
6661
6662 @Override
6663 public int getLayoutDirection() {
6664 return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6665 }
6666
6667 @Override
6668 public boolean canResolveTextDirection() {
6669 return true;
6670 }
6671
6672 @Override
6673 public boolean isTextDirectionResolved() {
6674 return true;
6675 }
6676
6677 @Override
6678 public int getTextDirection() {
6679 return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6680 }
6681
6682 @Override
6683 public boolean canResolveTextAlignment() {
6684 return true;
6685 }
6686
6687 @Override
6688 public boolean isTextAlignmentResolved() {
6689 return true;
6690 }
6691
6692 @Override
6693 public int getTextAlignment() {
6694 return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6695 }
6696
Svetoslav Ganov42138042012-03-20 11:51:39 -07006697 private View getCommonPredecessor(View first, View second) {
Chris Craikd36a81f2014-07-17 10:16:51 -07006698 if (mTempHashSet == null) {
6699 mTempHashSet = new HashSet<View>();
Svetoslav Ganov42138042012-03-20 11:51:39 -07006700 }
Chris Craikd36a81f2014-07-17 10:16:51 -07006701 HashSet<View> seen = mTempHashSet;
6702 seen.clear();
6703 View firstCurrent = first;
6704 while (firstCurrent != null) {
6705 seen.add(firstCurrent);
6706 ViewParent firstCurrentParent = firstCurrent.mParent;
6707 if (firstCurrentParent instanceof View) {
6708 firstCurrent = (View) firstCurrentParent;
6709 } else {
6710 firstCurrent = null;
6711 }
6712 }
6713 View secondCurrent = second;
6714 while (secondCurrent != null) {
6715 if (seen.contains(secondCurrent)) {
6716 seen.clear();
6717 return secondCurrent;
6718 }
6719 ViewParent secondCurrentParent = secondCurrent.mParent;
6720 if (secondCurrentParent instanceof View) {
6721 secondCurrent = (View) secondCurrentParent;
6722 } else {
6723 secondCurrent = null;
6724 }
6725 }
6726 seen.clear();
Svetoslav Ganov42138042012-03-20 11:51:39 -07006727 return null;
6728 }
6729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 void checkThread() {
6731 if (mThread != Thread.currentThread()) {
6732 throw new CalledFromWrongThreadException(
6733 "Only the original thread that created a view hierarchy can touch its views.");
6734 }
6735 }
6736
Igor Murashkina86ab6402013-08-30 12:58:36 -07006737 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
Joe Onoratoc6cc0f82011-04-12 11:53:13 -07006739 // ViewAncestor never intercepts touch event, so this can be a no-op
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 }
6741
Igor Murashkina86ab6402013-08-30 12:58:36 -07006742 @Override
Svetoslav Ganov1cf70bb2012-08-06 10:53:34 -07006743 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Yigit Boyard62d5e92016-01-19 18:56:20 -08006744 if (rectangle == null) {
6745 return scrollToRectOrFocus(null, immediate);
6746 }
6747 rectangle.offset(child.getLeft() - child.getScrollX(),
6748 child.getTop() - child.getScrollY());
Svetoslav Ganov1cf70bb2012-08-06 10:53:34 -07006749 final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
Yigit Boyard62d5e92016-01-19 18:56:20 -08006750 mTempRect.set(rectangle);
6751 mTempRect.offset(0, -mCurScrollY);
6752 mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6753 try {
6754 mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6755 } catch (RemoteException re) {
6756 /* ignore */
Svetoslav Ganov1cf70bb2012-08-06 10:53:34 -07006757 }
6758 return scrolled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 }
Romain Guy8506ab42009-06-11 17:35:47 -07006760
Igor Murashkina86ab6402013-08-30 12:58:36 -07006761 @Override
Adam Powell539ee872012-02-03 19:00:49 -08006762 public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6763 // Do nothing.
6764 }
6765
Adam Powell10ba2772014-04-15 09:46:51 -07006766 @Override
6767 public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6768 return false;
6769 }
6770
6771 @Override
6772 public void onStopNestedScroll(View target) {
6773 }
6774
6775 @Override
6776 public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6777 }
6778
6779 @Override
6780 public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6781 int dxUnconsumed, int dyUnconsumed) {
6782 }
6783
6784 @Override
6785 public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6786 }
6787
6788 @Override
Adam Powellb36e4f92014-05-01 10:23:33 -07006789 public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
Adam Powell10ba2772014-04-15 09:46:51 -07006790 return false;
6791 }
6792
Adam Powellb72be592014-07-16 21:41:31 -07006793 @Override
6794 public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6795 return false;
6796 }
6797
Adam Powellb6ab0982015-01-07 17:00:12 -08006798 @Override
6799 public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6800 return false;
6801 }
6802
Jorim Jaggib774e552015-08-24 14:52:45 -07006803 /**
6804 * Force the window to report its next draw.
6805 * <p>
6806 * This method is only supposed to be used to speed up the interaction from SystemUI and window
6807 * manager when waiting for the first frame to be drawn when turning on the screen. DO NOT USE
6808 * unless you fully understand this interaction.
6809 * @hide
6810 */
6811 public void setReportNextDraw() {
6812 mReportNextDraw = true;
6813 invalidate();
6814 }
6815
Craig Mautnerbc57cd12013-08-19 15:47:42 -07006816 void changeCanvasOpacity(boolean opaque) {
Filip Gruszczynski34dab0b2015-12-22 08:29:07 -08006817 Log.d(mTag, "changeCanvasOpacity: opaque=" + opaque);
John Reck63a06672014-05-07 13:45:54 -07006818 if (mAttachInfo.mHardwareRenderer != null) {
6819 mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6820 }
Craig Mautnerbc57cd12013-08-19 15:47:42 -07006821 }
6822
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006823 class TakenSurfaceHolder extends BaseSurfaceHolder {
6824 @Override
6825 public boolean onAllowLockCanvas() {
6826 return mDrawingAllowed;
6827 }
6828
6829 @Override
6830 public void onRelayoutContainer() {
6831 // Not currently interesting -- from changing between fixed and layout size.
6832 }
6833
Igor Murashkina86ab6402013-08-30 12:58:36 -07006834 @Override
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006835 public void setFormat(int format) {
6836 ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6837 }
6838
Igor Murashkina86ab6402013-08-30 12:58:36 -07006839 @Override
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006840 public void setType(int type) {
6841 ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6842 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07006843
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006844 @Override
6845 public void onUpdateSurface() {
6846 // We take care of format and type changes on our own.
6847 throw new IllegalStateException("Shouldn't be here");
6848 }
6849
Igor Murashkina86ab6402013-08-30 12:58:36 -07006850 @Override
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006851 public boolean isCreating() {
6852 return mIsCreating;
6853 }
6854
6855 @Override
6856 public void setFixedSize(int width, int height) {
6857 throw new UnsupportedOperationException(
6858 "Currently only support sizing from layout");
6859 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07006860
6861 @Override
Dianne Hackborndc8a7f62010-05-10 11:29:34 -07006862 public void setKeepScreenOn(boolean screenOn) {
6863 ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6864 }
6865 }
Romain Guy8506ab42009-06-11 17:35:47 -07006866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 static class W extends IWindow.Stub {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006868 private final WeakReference<ViewRootImpl> mViewAncestor;
Jeff Brown98365d72012-08-19 20:30:52 -07006869 private final IWindowSession mWindowSession;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006871 W(ViewRootImpl viewAncestor) {
6872 mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
Jeff Brown98365d72012-08-19 20:30:52 -07006873 mWindowSession = viewAncestor.mWindowSession;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 }
6875
Igor Murashkina86ab6402013-08-30 12:58:36 -07006876 @Override
Dianne Hackbornc4aad012013-02-22 15:05:25 -08006877 public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
Filip Gruszczynski2217f612015-05-26 11:32:08 -07006878 Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08006879 Configuration newConfig, Rect backDropFrame, boolean forceLayout) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006880 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006881 if (viewAncestor != null) {
Dianne Hackbornc4aad012013-02-22 15:05:25 -08006882 viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
Jorim Jaggia4a58ef2016-01-27 02:10:08 -08006883 visibleInsets, stableInsets, outsets, reportDraw, newConfig, backDropFrame,
6884 forceLayout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 }
6886 }
6887
Craig Mautner5702d4d2012-06-30 14:10:16 -07006888 @Override
6889 public void moved(int newX, int newY) {
6890 final ViewRootImpl viewAncestor = mViewAncestor.get();
6891 if (viewAncestor != null) {
6892 viewAncestor.dispatchMoved(newX, newY);
6893 }
6894 }
6895
Igor Murashkina86ab6402013-08-30 12:58:36 -07006896 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 public void dispatchAppVisibility(boolean visible) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006898 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006899 if (viewAncestor != null) {
6900 viewAncestor.dispatchAppVisibility(visible);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 }
6902 }
6903
Igor Murashkina86ab6402013-08-30 12:58:36 -07006904 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 public void dispatchGetNewSurface() {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006906 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006907 if (viewAncestor != null) {
6908 viewAncestor.dispatchGetNewSurface();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
6910 }
6911
Igor Murashkina86ab6402013-08-30 12:58:36 -07006912 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006914 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006915 if (viewAncestor != null) {
6916 viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 }
6918 }
6919
6920 private static int checkCallingPermission(String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 try {
6922 return ActivityManagerNative.getDefault().checkPermission(
6923 permission, Binder.getCallingPid(), Binder.getCallingUid());
6924 } catch (RemoteException e) {
6925 return PackageManager.PERMISSION_DENIED;
6926 }
6927 }
6928
Igor Murashkina86ab6402013-08-30 12:58:36 -07006929 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006931 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006932 if (viewAncestor != null) {
6933 final View view = viewAncestor.mView;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 if (view != null) {
6935 if (checkCallingPermission(Manifest.permission.DUMP) !=
6936 PackageManager.PERMISSION_GRANTED) {
6937 throw new SecurityException("Insufficient permissions to invoke"
6938 + " executeCommand() from pid=" + Binder.getCallingPid()
6939 + ", uid=" + Binder.getCallingUid());
6940 }
6941
6942 OutputStream clientStream = null;
6943 try {
6944 clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6945 ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6946 } catch (IOException e) {
6947 e.printStackTrace();
6948 } finally {
6949 if (clientStream != null) {
6950 try {
6951 clientStream.close();
6952 } catch (IOException e) {
6953 e.printStackTrace();
6954 }
6955 }
6956 }
6957 }
6958 }
6959 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07006960
6961 @Override
Dianne Hackbornffa42482009-09-23 22:20:11 -07006962 public void closeSystemDialogs(String reason) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006963 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006964 if (viewAncestor != null) {
6965 viewAncestor.dispatchCloseSystemDialogs(reason);
Dianne Hackbornffa42482009-09-23 22:20:11 -07006966 }
6967 }
Igor Murashkina86ab6402013-08-30 12:58:36 -07006968
6969 @Override
Marco Nelissenbf6956b2009-11-09 15:21:13 -08006970 public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
6971 boolean sync) {
Dianne Hackborn19382ac2009-09-11 21:13:37 -07006972 if (sync) {
6973 try {
Jeff Brown98365d72012-08-19 20:30:52 -07006974 mWindowSession.wallpaperOffsetsComplete(asBinder());
Dianne Hackborn19382ac2009-09-11 21:13:37 -07006975 } catch (RemoteException e) {
6976 }
6977 }
Dianne Hackborn72c82ab2009-08-11 21:13:54 -07006978 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006979
Igor Murashkina86ab6402013-08-30 12:58:36 -07006980 @Override
Dianne Hackborn75804932009-10-20 20:15:20 -07006981 public void dispatchWallpaperCommand(String action, int x, int y,
6982 int z, Bundle extras, boolean sync) {
6983 if (sync) {
6984 try {
Jeff Brown98365d72012-08-19 20:30:52 -07006985 mWindowSession.wallpaperCommandComplete(asBinder(), null);
Dianne Hackborn75804932009-10-20 20:15:20 -07006986 } catch (RemoteException e) {
6987 }
6988 }
6989 }
Christopher Tatea53146c2010-09-07 11:57:52 -07006990
6991 /* Drag/drop */
Igor Murashkina86ab6402013-08-30 12:58:36 -07006992 @Override
Christopher Tatea53146c2010-09-07 11:57:52 -07006993 public void dispatchDragEvent(DragEvent event) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07006994 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07006995 if (viewAncestor != null) {
6996 viewAncestor.dispatchDragEvent(event);
Christopher Tatea53146c2010-09-07 11:57:52 -07006997 }
6998 }
Joe Onorato664644d2011-01-23 17:53:23 -08006999
Igor Murashkina86ab6402013-08-30 12:58:36 -07007000 @Override
Vladislav Kaznacheevec6a4472016-01-22 12:21:52 -08007001 public void updatePointerIcon(float x, float y) {
7002 final ViewRootImpl viewAncestor = mViewAncestor.get();
7003 if (viewAncestor != null) {
7004 viewAncestor.updatePointerIcon(x, y);
7005 }
7006 }
7007
7008 @Override
Dianne Hackborn9a230e02011-10-06 11:51:27 -07007009 public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
7010 int localValue, int localChanges) {
Dianne Hackborn6dd005b2011-07-18 13:22:50 -07007011 final ViewRootImpl viewAncestor = mViewAncestor.get();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007012 if (viewAncestor != null) {
Dianne Hackborn9a230e02011-10-06 11:51:27 -07007013 viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
7014 localValue, localChanges);
Joe Onorato664644d2011-01-23 17:53:23 -08007015 }
7016 }
Dianne Hackborn12d3a942012-04-27 14:16:30 -07007017
Igor Murashkina86ab6402013-08-30 12:58:36 -07007018 @Override
Craig Mautner9c795042014-10-28 19:59:59 -07007019 public void dispatchWindowShown() {
7020 final ViewRootImpl viewAncestor = mViewAncestor.get();
7021 if (viewAncestor != null) {
7022 viewAncestor.dispatchWindowShown();
7023 }
7024 }
Clara Bayarri75e09792015-07-29 16:20:40 +01007025
7026 @Override
7027 public void requestAppKeyboardShortcuts(IResultReceiver receiver) {
7028 ViewRootImpl viewAncestor = mViewAncestor.get();
7029 if (viewAncestor != null) {
7030 viewAncestor.dispatchRequestKeyboardShortcuts(receiver);
7031 }
7032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 }
7034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
7036 public CalledFromWrongThreadException(String msg) {
7037 super(msg);
7038 }
7039 }
7040
Alan Viverettebea0c7da2015-09-01 16:00:20 -04007041 static HandlerActionQueue getRunQueue() {
7042 HandlerActionQueue rq = sRunQueues.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 if (rq != null) {
7044 return rq;
7045 }
Alan Viverettebea0c7da2015-09-01 16:00:20 -04007046 rq = new HandlerActionQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 sRunQueues.set(rq);
7048 return rq;
7049 }
Romain Guy8506ab42009-06-11 17:35:47 -07007050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 /**
Skuhneb8160872015-09-22 09:51:39 -07007052 * Start a drag resizing which will inform all listeners that a window resize is taking place.
7053 */
Jorim Jaggi9511b0f2016-01-29 19:12:44 -08007054 private void startDragResizing(Rect initialBounds, boolean fullscreen, Rect systemInsets,
7055 Rect stableInsets) {
Skuhneb8160872015-09-22 09:51:39 -07007056 if (!mDragResizing) {
7057 mDragResizing = true;
Chong Zhangdcee1de2015-10-06 10:26:00 -07007058 synchronized (mWindowCallbacks) {
7059 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
Jorim Jaggi9511b0f2016-01-29 19:12:44 -08007060 mWindowCallbacks.get(i).onWindowDragResizeStart(initialBounds, fullscreen,
7061 systemInsets, stableInsets);
Skuhneb8160872015-09-22 09:51:39 -07007062 }
7063 }
7064 mFullRedrawNeeded = true;
7065 }
7066 }
7067
7068 /**
7069 * End a drag resize which will inform all listeners that a window resize has ended.
7070 */
7071 private void endDragResizing() {
7072 if (mDragResizing) {
7073 mDragResizing = false;
Chong Zhangdcee1de2015-10-06 10:26:00 -07007074 synchronized (mWindowCallbacks) {
7075 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7076 mWindowCallbacks.get(i).onWindowDragResizeEnd();
Skuhneb8160872015-09-22 09:51:39 -07007077 }
7078 }
7079 mFullRedrawNeeded = true;
7080 }
7081 }
7082
Chong Zhang8dbd9ad2015-10-09 10:06:11 -07007083 private boolean updateContentDrawBounds() {
7084 boolean updated = false;
7085 synchronized (mWindowCallbacks) {
7086 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7087 updated |= mWindowCallbacks.get(i).onContentDrawn(
7088 mWindowAttributes.surfaceInsets.left,
7089 mWindowAttributes.surfaceInsets.top,
7090 mWidth, mHeight);
7091 }
7092 }
7093 return updated | (mDragResizing && mReportNextDraw);
7094 }
7095
7096 private void requestDrawWindow() {
7097 if (mReportNextDraw) {
7098 mWindowDrawCountDown = new CountDownLatch(mWindowCallbacks.size());
7099 }
7100 synchronized (mWindowCallbacks) {
7101 for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7102 mWindowCallbacks.get(i).onRequestDraw(mReportNextDraw);
7103 }
7104 }
7105 }
7106
Skuhneb8160872015-09-22 09:51:39 -07007107 /**
Jorim Jaggi4846ee32016-01-07 17:39:12 +01007108 * Tells this instance that its corresponding activity has just relaunched. In this case, we
7109 * need to force a relayout of the window to make sure we get the correct bounds from window
7110 * manager.
7111 */
7112 public void reportActivityRelaunched() {
7113 mActivityRelaunched = true;
7114 }
7115
7116 /**
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007117 * Class for managing the accessibility interaction connection
7118 * based on the global accessibility state.
7119 */
7120 final class AccessibilityInteractionConnectionManager
7121 implements AccessibilityStateChangeListener {
Igor Murashkina86ab6402013-08-30 12:58:36 -07007122 @Override
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007123 public void onAccessibilityStateChanged(boolean enabled) {
7124 if (enabled) {
7125 ensureConnection();
Chris Craikcce47eb2014-07-16 15:12:15 -07007126 if (mAttachInfo.mHasWindowFocus) {
Svetoslav Ganov0d04e242012-02-21 13:46:36 -08007127 mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
7128 View focusedView = mView.findFocus();
7129 if (focusedView != null && focusedView != mView) {
7130 focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
7131 }
7132 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007133 } else {
7134 ensureNoConnection();
Svetoslav Ganov005b83b2012-04-16 18:17:17 -07007135 mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007136 }
7137 }
7138
7139 public void ensureConnection() {
Chris Craikcce47eb2014-07-16 15:12:15 -07007140 final boolean registered =
Svetoslav8e3feb12014-02-24 13:46:47 -08007141 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
Chris Craikcce47eb2014-07-16 15:12:15 -07007142 if (!registered) {
7143 mAttachInfo.mAccessibilityWindowId =
Svetoslav Ganov0d04e242012-02-21 13:46:36 -08007144 mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
7145 new AccessibilityInteractionConnection(ViewRootImpl.this));
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007146 }
7147 }
7148
7149 public void ensureNoConnection() {
Svetoslav Ganov0d04e242012-02-21 13:46:36 -08007150 final boolean registered =
Svetoslav8e3feb12014-02-24 13:46:47 -08007151 mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007152 if (registered) {
Svetoslav8e3feb12014-02-24 13:46:47 -08007153 mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007154 mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
7155 }
7156 }
7157 }
7158
Chris Craikcce47eb2014-07-16 15:12:15 -07007159 final class HighContrastTextManager implements HighTextContrastChangeListener {
7160 HighContrastTextManager() {
7161 mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
7162 }
7163 @Override
7164 public void onHighTextContrastStateChanged(boolean enabled) {
7165 mAttachInfo.mHighContrastText = enabled;
7166
7167 // Destroy Displaylists so they can be recreated with high contrast recordings
7168 destroyHardwareResources();
Chris Craikd36a81f2014-07-17 10:16:51 -07007169
7170 // Schedule redraw, which will rerecord + redraw all text
7171 invalidate();
Chris Craikcce47eb2014-07-16 15:12:15 -07007172 }
7173 }
7174
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007175 /**
7176 * This class is an interface this ViewAncestor provides to the
7177 * AccessibilityManagerService to the latter can interact with
7178 * the view hierarchy in this ViewAncestor.
7179 */
Svetoslav Ganovaf5b4f42011-10-28 12:41:38 -07007180 static final class AccessibilityInteractionConnection
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007181 extends IAccessibilityInteractionConnection.Stub {
Svetoslav Ganov02107852011-10-03 17:06:56 -07007182 private final WeakReference<ViewRootImpl> mViewRootImpl;
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007183
Svetoslav Ganovf79f4762011-10-28 15:40:32 -07007184 AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
7185 mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007186 }
7187
Svetoslav Ganov42138042012-03-20 11:51:39 -07007188 @Override
Svetoslav Ganov02107852011-10-03 17:06:56 -07007189 public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007190 Region interactiveRegion, int interactionId,
7191 IAccessibilityInteractionConnectionCallback callback, int flags,
Svetoslav Ganov152e9bb2012-10-12 20:15:29 -07007192 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
Svetoslav Ganov02107852011-10-03 17:06:56 -07007193 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7194 if (viewRootImpl != null && viewRootImpl.mView != null) {
Svetoslav Ganovaf5b4f42011-10-28 12:41:38 -07007195 viewRootImpl.getAccessibilityInteractionController()
Svetoslav Ganov02107852011-10-03 17:06:56 -07007196 .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007197 interactiveRegion, interactionId, callback, flags, interrogatingPid,
7198 interrogatingTid, spec);
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007199 } else {
7200 // We cannot make the call and notify the caller so it does not wait.
7201 try {
7202 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7203 } catch (RemoteException re) {
7204 /* best effort - ignore */
7205 }
Svetoslav Ganov601ad802011-06-09 14:47:38 -07007206 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007207 }
7208
Svetoslav Ganov42138042012-03-20 11:51:39 -07007209 @Override
Svetoslav Ganov02107852011-10-03 17:06:56 -07007210 public void performAccessibilityAction(long accessibilityNodeId, int action,
Svetoslav Ganovaa780c12012-04-19 23:01:39 -07007211 Bundle arguments, int interactionId,
7212 IAccessibilityInteractionConnectionCallback callback, int flags,
Svet Ganov7498efd2014-09-03 21:33:00 -07007213 int interrogatingPid, long interrogatingTid) {
Svetoslav Ganov02107852011-10-03 17:06:56 -07007214 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7215 if (viewRootImpl != null && viewRootImpl.mView != null) {
Svetoslav Ganovaf5b4f42011-10-28 12:41:38 -07007216 viewRootImpl.getAccessibilityInteractionController()
Svetoslav Ganovaa780c12012-04-19 23:01:39 -07007217 .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
Svet Ganov7498efd2014-09-03 21:33:00 -07007218 interactionId, callback, flags, interrogatingPid, interrogatingTid);
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007219 } else {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007220 // We cannot make the call and notify the caller so it does not wait.
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007221 try {
7222 callback.setPerformAccessibilityActionResult(false, interactionId);
7223 } catch (RemoteException re) {
7224 /* best effort - ignore */
7225 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007226 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007227 }
7228
Svetoslav Ganov42138042012-03-20 11:51:39 -07007229 @Override
Svetoslav Ganov80943d82013-01-02 10:25:37 -08007230 public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007231 String viewId, Region interactiveRegion, int interactionId,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08007232 IAccessibilityInteractionConnectionCallback callback, int flags,
Svetoslav Ganov152e9bb2012-10-12 20:15:29 -07007233 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
Svetoslav Ganov02107852011-10-03 17:06:56 -07007234 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7235 if (viewRootImpl != null && viewRootImpl.mView != null) {
Svetoslav Ganovaf5b4f42011-10-28 12:41:38 -07007236 viewRootImpl.getAccessibilityInteractionController()
Svetoslav Ganov80943d82013-01-02 10:25:37 -08007237 .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007238 viewId, interactiveRegion, interactionId, callback, flags,
7239 interrogatingPid, interrogatingTid, spec);
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007240 } else {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007241 // We cannot make the call and notify the caller so it does not wait.
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007242 try {
7243 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7244 } catch (RemoteException re) {
7245 /* best effort - ignore */
7246 }
7247 }
7248 }
7249
Svetoslav Ganov42138042012-03-20 11:51:39 -07007250 @Override
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007251 public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007252 Region interactiveRegion, int interactionId,
7253 IAccessibilityInteractionConnectionCallback callback, int flags,
Svetoslav Ganov152e9bb2012-10-12 20:15:29 -07007254 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007255 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7256 if (viewRootImpl != null && viewRootImpl.mView != null) {
7257 viewRootImpl.getAccessibilityInteractionController()
7258 .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
Svetoslav9ae9ed22014-09-02 16:36:35 -07007259 interactiveRegion, interactionId, callback, flags, interrogatingPid,
7260 interrogatingTid, spec);
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007261 } else {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007262 // We cannot make the call and notify the caller so it does not wait.
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007263 try {
7264 callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7265 } catch (RemoteException re) {
7266 /* best effort - ignore */
7267 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007268 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007269 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007270
Svetoslav Ganov42138042012-03-20 11:51:39 -07007271 @Override
Svetoslav9ae9ed22014-09-02 16:36:35 -07007272 public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
7273 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
Svetoslav Ganov152e9bb2012-10-12 20:15:29 -07007274 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007275 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7276 if (viewRootImpl != null && viewRootImpl.mView != null) {
7277 viewRootImpl.getAccessibilityInteractionController()
Svetoslav9ae9ed22014-09-02 16:36:35 -07007278 .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
7279 interactionId, callback, flags, interrogatingPid, interrogatingTid,
7280 spec);
Svetoslav Ganov8bd69612011-08-23 13:40:30 -07007281 } else {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007282 // We cannot make the call and notify the caller so it does not wait.
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007283 try {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007284 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007285 } catch (RemoteException re) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007286 /* best effort - ignore */
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007287 }
7288 }
7289 }
7290
Svetoslav Ganov42138042012-03-20 11:51:39 -07007291 @Override
Svetoslav9ae9ed22014-09-02 16:36:35 -07007292 public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
7293 int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
Svetoslav Ganov152e9bb2012-10-12 20:15:29 -07007294 int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007295 ViewRootImpl viewRootImpl = mViewRootImpl.get();
7296 if (viewRootImpl != null && viewRootImpl.mView != null) {
7297 viewRootImpl.getAccessibilityInteractionController()
Svetoslav9ae9ed22014-09-02 16:36:35 -07007298 .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
7299 interactionId, callback, flags, interrogatingPid, interrogatingTid,
7300 spec);
Svetoslav Ganov8bd69612011-08-23 13:40:30 -07007301 } else {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007302 // We cannot make the call and notify the caller so it does not wait.
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007303 try {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007304 callback.setFindAccessibilityNodeInfoResult(null, interactionId);
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007305 } catch (RemoteException re) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007306 /* best effort - ignore */
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007307 }
7308 }
7309 }
Svetoslav Ganov8643aa02011-04-20 12:12:33 -07007310 }
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07007311
Svetoslav Ganova0156172011-06-26 17:55:44 -07007312 private class SendWindowContentChangedAccessibilityEvent implements Runnable {
Alan Viverette77e9a282013-09-12 17:16:09 -07007313 private int mChangeTypes = 0;
7314
Svetoslav Ganov42138042012-03-20 11:51:39 -07007315 public View mSource;
Svetoslav6254f482013-06-04 17:22:14 -07007316 public long mLastEventTimeMillis;
Svetoslav Ganova0156172011-06-26 17:55:44 -07007317
Igor Murashkina86ab6402013-08-30 12:58:36 -07007318 @Override
Svetoslav Ganoveeee4d22011-06-10 20:51:30 -07007319 public void run() {
Svetoslav8d820ecf2013-07-15 17:12:41 -07007320 // The accessibility may be turned off while we were waiting so check again.
7321 if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7322 mLastEventTimeMillis = SystemClock.uptimeMillis();
7323 AccessibilityEvent event = AccessibilityEvent.obtain();
7324 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
Alan Viverette77e9a282013-09-12 17:16:09 -07007325 event.setContentChangeTypes(mChangeTypes);
Svetoslav8d820ecf2013-07-15 17:12:41 -07007326 mSource.sendAccessibilityEventUnchecked(event);
7327 } else {
7328 mLastEventTimeMillis = 0;
7329 }
7330 // In any case reset to initial state.
Svetoslav6254f482013-06-04 17:22:14 -07007331 mSource.resetSubtreeAccessibilityStateChanged();
7332 mSource = null;
Alan Viverette77e9a282013-09-12 17:16:09 -07007333 mChangeTypes = 0;
Svetoslav6254f482013-06-04 17:22:14 -07007334 }
7335
Alan Viverette77e9a282013-09-12 17:16:09 -07007336 public void runOrPost(View source, int changeType) {
Svetoslav Ganov42138042012-03-20 11:51:39 -07007337 if (mSource != null) {
Svetoslav9dafebb2013-06-18 16:29:25 -07007338 // If there is no common predecessor, then mSource points to
7339 // a removed view, hence in this case always prefer the source.
7340 View predecessor = getCommonPredecessor(mSource, source);
7341 mSource = (predecessor != null) ? predecessor : source;
Alan Viverette77e9a282013-09-12 17:16:09 -07007342 mChangeTypes |= changeType;
Svetoslav6254f482013-06-04 17:22:14 -07007343 return;
7344 }
7345 mSource = source;
Alan Viverette77e9a282013-09-12 17:16:09 -07007346 mChangeTypes = changeType;
Svetoslav6254f482013-06-04 17:22:14 -07007347 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
7348 final long minEventIntevalMillis =
7349 ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
7350 if (timeSinceLastMillis >= minEventIntevalMillis) {
Svetoslav9dafebb2013-06-18 16:29:25 -07007351 mSource.removeCallbacks(this);
Svetoslav6254f482013-06-04 17:22:14 -07007352 run();
7353 } else {
7354 mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
Svetoslav Ganov79311c42012-01-17 20:24:26 -08007355 }
7356 }
7357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358}