ViewRootImpl.java revision 16b631923ddf7a32d055e06d1dea70964f85e5a6
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import static android.view.WindowCallbacks.RESIZE_MODE_DOCKED_DIVIDER;
20import static android.view.WindowCallbacks.RESIZE_MODE_FREEFORM;
21import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
22import static android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER;
23import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
24import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
25import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
26
27import android.Manifest;
28import android.animation.LayoutTransition;
29import android.app.ActivityManagerNative;
30import android.content.ClipDescription;
31import android.content.ComponentCallbacks;
32import android.content.Context;
33import android.content.pm.PackageManager;
34import android.content.res.CompatibilityInfo;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.graphics.Canvas;
38import android.graphics.Matrix;
39import android.graphics.PixelFormat;
40import android.graphics.Point;
41import android.graphics.PointF;
42import android.graphics.PorterDuff;
43import android.graphics.Rect;
44import android.graphics.Region;
45import android.graphics.drawable.Drawable;
46import android.hardware.display.DisplayManager;
47import android.hardware.display.DisplayManager.DisplayListener;
48import android.hardware.input.InputManager;
49import android.media.AudioManager;
50import android.os.Binder;
51import android.os.Build;
52import android.os.Bundle;
53import android.os.Debug;
54import android.os.Handler;
55import android.os.Looper;
56import android.os.Message;
57import android.os.ParcelFileDescriptor;
58import android.os.Process;
59import android.os.RemoteException;
60import android.os.SystemClock;
61import android.os.SystemProperties;
62import android.os.Trace;
63import android.util.AndroidRuntimeException;
64import android.util.DisplayMetrics;
65import android.util.Log;
66import android.util.Slog;
67import android.util.TimeUtils;
68import android.util.TypedValue;
69import android.view.Surface.OutOfResourcesException;
70import android.view.View.AttachInfo;
71import android.view.View.MeasureSpec;
72import android.view.accessibility.AccessibilityEvent;
73import android.view.accessibility.AccessibilityManager;
74import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
75import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
78import android.view.accessibility.AccessibilityNodeProvider;
79import android.view.accessibility.IAccessibilityInteractionConnection;
80import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
81import android.view.animation.AccelerateDecelerateInterpolator;
82import android.view.animation.Interpolator;
83import android.view.inputmethod.InputConnection;
84import android.view.inputmethod.InputMethodManager;
85import android.widget.Scroller;
86
87import com.android.internal.R;
88import com.android.internal.annotations.GuardedBy;
89import com.android.internal.os.IResultReceiver;
90import com.android.internal.os.SomeArgs;
91import com.android.internal.policy.PhoneFallbackEventHandler;
92import com.android.internal.view.BaseSurfaceHolder;
93import com.android.internal.view.RootViewSurfaceTaker;
94
95import java.io.FileDescriptor;
96import java.io.IOException;
97import java.io.OutputStream;
98import java.io.PrintWriter;
99import java.lang.ref.WeakReference;
100import java.util.ArrayList;
101import java.util.HashSet;
102import java.util.concurrent.CountDownLatch;
103
104/**
105 * The top of a view hierarchy, implementing the needed protocol between View
106 * and the WindowManager.  This is for the most part an internal implementation
107 * detail of {@link WindowManagerGlobal}.
108 *
109 * {@hide}
110 */
111@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
112public final class ViewRootImpl implements ViewParent,
113        View.AttachInfo.Callbacks, ThreadedRenderer.HardwareDrawCallbacks {
114    private static final String TAG = "ViewRootImpl";
115    private static final boolean DBG = false;
116    private static final boolean LOCAL_LOGV = false;
117    /** @noinspection PointlessBooleanExpression*/
118    private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
119    private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
120    private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
121    private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
122    private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
123    private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
124    private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
125    private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
126    private static final boolean DEBUG_FPS = false;
127    private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
128
129    /**
130     * Set to false if we do not want to use the multi threaded renderer. Note that by disabling
131     * this, WindowCallbacks will not fire.
132     */
133    private static final boolean USE_MT_RENDERER = true;
134
135    /**
136     * Set this system property to true to force the view hierarchy to render
137     * at 60 Hz. This can be used to measure the potential framerate.
138     */
139    private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
140
141    // properties used by emulator to determine display shape
142    public static final String PROPERTY_EMULATOR_WIN_OUTSET_BOTTOM_PX =
143            "ro.emu.win_outset_bottom_px";
144
145    /**
146     * Maximum time we allow the user to roll the trackball enough to generate
147     * a key event, before resetting the counters.
148     */
149    static final int MAX_TRACKBALL_DELAY = 250;
150
151    static final ThreadLocal<HandlerActionQueue> sRunQueues = new ThreadLocal<HandlerActionQueue>();
152
153    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList();
154    static boolean sFirstDrawComplete = false;
155
156    static final ArrayList<ComponentCallbacks> sConfigCallbacks = new ArrayList();
157
158    /**
159     * This list must only be modified by the main thread, so a lock is only needed when changing
160     * the list or when accessing the list from a non-main thread.
161     */
162    @GuardedBy("mWindowCallbacks")
163    final ArrayList<WindowCallbacks> mWindowCallbacks = new ArrayList<>();
164    final Context mContext;
165    final IWindowSession mWindowSession;
166    final Display mDisplay;
167    final DisplayManager mDisplayManager;
168    final String mBasePackageName;
169
170    final int[] mTmpLocation = new int[2];
171
172    final TypedValue mTmpValue = new TypedValue();
173
174    final Thread mThread;
175
176    final WindowLeaked mLocation;
177
178    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
179
180    final W mWindow;
181
182    final int mTargetSdkVersion;
183
184    int mSeq;
185
186    View mView;
187
188    View mAccessibilityFocusedHost;
189    AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
190
191    // The view which captures mouse input, or null when no one is capturing.
192    View mCapturingView;
193
194    int mViewVisibility;
195    boolean mAppVisible = true;
196    // For recents to freeform transition we need to keep drawing after the app receives information
197    // that it became invisible. This will ignore that information and depend on the decor view
198    // visibility to control drawing. The decor view visibility will get adjusted when the app get
199    // stopped and that's when the app will stop drawing further frames.
200    private boolean mForceDecorViewVisibility = false;
201    int mOrigWindowType = -1;
202
203    /** Whether the window had focus during the most recent traversal. */
204    boolean mHadWindowFocus;
205
206    /**
207     * Whether the window lost focus during a previous traversal and has not
208     * yet gained it back. Used to determine whether a WINDOW_STATE_CHANGE
209     * accessibility events should be sent during traversal.
210     */
211    boolean mLostWindowFocus;
212
213    // Set to true if the owner of this window is in the stopped state,
214    // so the window should no longer be active.
215    boolean mStopped = false;
216
217    // Set to true if the owner of this window is in ambient mode,
218    // which means it won't receive input events.
219    boolean mIsAmbientMode = false;
220
221    // Set to true to stop input during an Activity Transition.
222    boolean mPausedForTransition = false;
223
224    boolean mLastInCompatMode = false;
225
226    SurfaceHolder.Callback2 mSurfaceHolderCallback;
227    BaseSurfaceHolder mSurfaceHolder;
228    boolean mIsCreating;
229    boolean mDrawingAllowed;
230
231    final Region mTransparentRegion;
232    final Region mPreviousTransparentRegion;
233
234    int mWidth;
235    int mHeight;
236    Rect mDirty;
237    boolean mIsAnimating;
238
239    private boolean mDragResizing;
240    private boolean mInvalidateRootRequested;
241    private int mResizeMode;
242    private int mCanvasOffsetX;
243    private int mCanvasOffsetY;
244    private boolean mActivityRelaunched;
245
246    CompatibilityInfo.Translator mTranslator;
247
248    final View.AttachInfo mAttachInfo;
249    InputChannel mInputChannel;
250    InputQueue.Callback mInputQueueCallback;
251    InputQueue mInputQueue;
252    FallbackEventHandler mFallbackEventHandler;
253    Choreographer mChoreographer;
254
255    final Rect mTempRect; // used in the transaction to not thrash the heap.
256    final Rect mVisRect; // used to retrieve visible rect of focused view.
257
258    boolean mTraversalScheduled;
259    int mTraversalBarrier;
260    boolean mWillDrawSoon;
261    /** Set to true while in performTraversals for detecting when die(true) is called from internal
262     * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
263    boolean mIsInTraversal;
264    boolean mApplyInsetsRequested;
265    boolean mLayoutRequested;
266    boolean mFirst;
267    boolean mReportNextDraw;
268    boolean mFullRedrawNeeded;
269    boolean mNewSurfaceNeeded;
270    boolean mHasHadWindowFocus;
271    boolean mLastWasImTarget;
272    boolean mForceNextWindowRelayout;
273    CountDownLatch mWindowDrawCountDown;
274
275    boolean mIsDrawing;
276    int mLastSystemUiVisibility;
277    int mClientWindowLayoutFlags;
278    boolean mLastOverscanRequested;
279
280    // Pool of queued input events.
281    private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
282    private QueuedInputEvent mQueuedInputEventPool;
283    private int mQueuedInputEventPoolSize;
284
285    /* Input event queue.
286     * Pending input events are input events waiting to be delivered to the input stages
287     * and handled by the application.
288     */
289    QueuedInputEvent mPendingInputEventHead;
290    QueuedInputEvent mPendingInputEventTail;
291    int mPendingInputEventCount;
292    boolean mProcessInputEventsScheduled;
293    boolean mUnbufferedInputDispatch;
294    String mPendingInputEventQueueLengthCounterName = "pq";
295
296    InputStage mFirstInputStage;
297    InputStage mFirstPostImeInputStage;
298    InputStage mSyntheticInputStage;
299
300    boolean mWindowAttributesChanged = false;
301    int mWindowAttributesChangesFlag = 0;
302
303    // These can be accessed by any thread, must be protected with a lock.
304    // Surface can never be reassigned or cleared (use Surface.clear()).
305    final Surface mSurface = new Surface();
306
307    boolean mAdded;
308    boolean mAddedTouchMode;
309
310    final DisplayAdjustments mDisplayAdjustments;
311
312    // These are accessed by multiple threads.
313    final Rect mWinFrame; // frame given by window manager.
314
315    final Rect mPendingOverscanInsets = new Rect();
316    final Rect mPendingVisibleInsets = new Rect();
317    final Rect mPendingStableInsets = new Rect();
318    final Rect mPendingContentInsets = new Rect();
319    final Rect mPendingOutsets = new Rect();
320    final Rect mPendingBackDropFrame = new Rect();
321    boolean mPendingAlwaysConsumeNavBar;
322    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
323            = new ViewTreeObserver.InternalInsetsInfo();
324
325    final Rect mDispatchContentInsets = new Rect();
326    final Rect mDispatchStableInsets = new Rect();
327
328    private WindowInsets mLastWindowInsets;
329
330    final Configuration mLastConfiguration = new Configuration();
331    final Configuration mPendingConfiguration = new Configuration();
332
333    boolean mScrollMayChange;
334    int mSoftInputMode;
335    WeakReference<View> mLastScrolledFocus;
336    int mScrollY;
337    int mCurScrollY;
338    Scroller mScroller;
339    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
340    private ArrayList<LayoutTransition> mPendingTransitions;
341
342    final ViewConfiguration mViewConfiguration;
343
344    /* Drag/drop */
345    ClipDescription mDragDescription;
346    View mCurrentDragView;
347    volatile Object mLocalDragState;
348    final PointF mDragPoint = new PointF();
349    final PointF mLastTouchPoint = new PointF();
350    int mLastTouchSource;
351
352    private boolean mProfileRendering;
353    private Choreographer.FrameCallback mRenderProfiler;
354    private boolean mRenderProfilingEnabled;
355
356    // Variables to track frames per second, enabled via DEBUG_FPS flag
357    private long mFpsStartTime = -1;
358    private long mFpsPrevTime = -1;
359    private int mFpsNumFrames;
360
361    private int mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
362    private PointerIcon mCustomPointerIcon = null;
363
364    /**
365     * see {@link #playSoundEffect(int)}
366     */
367    AudioManager mAudioManager;
368
369    final AccessibilityManager mAccessibilityManager;
370
371    AccessibilityInteractionController mAccessibilityInteractionController;
372
373    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
374    HighContrastTextManager mHighContrastTextManager;
375
376    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
377
378    HashSet<View> mTempHashSet;
379
380    private final int mDensity;
381    private final int mNoncompatDensity;
382
383    private boolean mInLayout = false;
384    ArrayList<View> mLayoutRequesters = new ArrayList<View>();
385    boolean mHandlingLayoutInLayoutRequest = false;
386
387    private int mViewLayoutDirectionInitial;
388
389    /** Set to true once doDie() has been called. */
390    private boolean mRemoved;
391
392    /**
393     * Consistency verifier for debugging purposes.
394     */
395    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
396            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
397                    new InputEventConsistencyVerifier(this, 0) : null;
398
399    static final class SystemUiVisibilityInfo {
400        int seq;
401        int globalVisibility;
402        int localValue;
403        int localChanges;
404    }
405
406    private String mTag = TAG;
407
408    public ViewRootImpl(Context context, Display display) {
409        mContext = context;
410        mWindowSession = WindowManagerGlobal.getWindowSession();
411        mDisplay = display;
412        mBasePackageName = context.getBasePackageName();
413
414        mDisplayAdjustments = display.getDisplayAdjustments();
415
416        mThread = Thread.currentThread();
417        mLocation = new WindowLeaked(null);
418        mLocation.fillInStackTrace();
419        mWidth = -1;
420        mHeight = -1;
421        mDirty = new Rect();
422        mTempRect = new Rect();
423        mVisRect = new Rect();
424        mWinFrame = new Rect();
425        mWindow = new W(this);
426        mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
427        mViewVisibility = View.GONE;
428        mTransparentRegion = new Region();
429        mPreviousTransparentRegion = new Region();
430        mFirst = true; // true for the first time the view is added
431        mAdded = false;
432        mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
433        mAccessibilityManager = AccessibilityManager.getInstance(context);
434        mAccessibilityInteractionConnectionManager =
435            new AccessibilityInteractionConnectionManager();
436        mAccessibilityManager.addAccessibilityStateChangeListener(
437                mAccessibilityInteractionConnectionManager);
438        mHighContrastTextManager = new HighContrastTextManager();
439        mAccessibilityManager.addHighTextContrastStateChangeListener(
440                mHighContrastTextManager);
441        mViewConfiguration = ViewConfiguration.get(context);
442        mDensity = context.getResources().getDisplayMetrics().densityDpi;
443        mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
444        mFallbackEventHandler = new PhoneFallbackEventHandler(context);
445        mChoreographer = Choreographer.getInstance();
446        mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
447        loadSystemProperties();
448    }
449
450    public static void addFirstDrawHandler(Runnable callback) {
451        synchronized (sFirstDrawHandlers) {
452            if (!sFirstDrawComplete) {
453                sFirstDrawHandlers.add(callback);
454            }
455        }
456    }
457
458    public static void addConfigCallback(ComponentCallbacks callback) {
459        synchronized (sConfigCallbacks) {
460            sConfigCallbacks.add(callback);
461        }
462    }
463
464    public void addWindowCallbacks(WindowCallbacks callback) {
465        if (USE_MT_RENDERER) {
466            synchronized (mWindowCallbacks) {
467                mWindowCallbacks.add(callback);
468            }
469        }
470    }
471
472    public void removeWindowCallbacks(WindowCallbacks callback) {
473        if (USE_MT_RENDERER) {
474            synchronized (mWindowCallbacks) {
475                mWindowCallbacks.remove(callback);
476            }
477        }
478    }
479
480    public void reportDrawFinish() {
481        if (mWindowDrawCountDown != null) {
482            mWindowDrawCountDown.countDown();
483        }
484    }
485
486    // FIXME for perf testing only
487    private boolean mProfile = false;
488
489    /**
490     * Call this to profile the next traversal call.
491     * FIXME for perf testing only. Remove eventually
492     */
493    public void profile() {
494        mProfile = true;
495    }
496
497    /**
498     * Indicates whether we are in touch mode. Calling this method triggers an IPC
499     * call and should be avoided whenever possible.
500     *
501     * @return True, if the device is in touch mode, false otherwise.
502     *
503     * @hide
504     */
505    static boolean isInTouchMode() {
506        IWindowSession windowSession = WindowManagerGlobal.peekWindowSession();
507        if (windowSession != null) {
508            try {
509                return windowSession.getInTouchMode();
510            } catch (RemoteException e) {
511            }
512        }
513        return false;
514    }
515
516    /**
517     * We have one child
518     */
519    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
520        synchronized (this) {
521            if (mView == null) {
522                mView = view;
523
524                mAttachInfo.mDisplayState = mDisplay.getState();
525                mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);
526
527                mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
528                mFallbackEventHandler.setView(view);
529                mWindowAttributes.copyFrom(attrs);
530                if (mWindowAttributes.packageName == null) {
531                    mWindowAttributes.packageName = mBasePackageName;
532                }
533                attrs = mWindowAttributes;
534                setTag();
535                // Keep track of the actual window flags supplied by the client.
536                mClientWindowLayoutFlags = attrs.flags;
537
538                setAccessibilityFocus(null, null);
539
540                if (view instanceof RootViewSurfaceTaker) {
541                    mSurfaceHolderCallback =
542                            ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
543                    if (mSurfaceHolderCallback != null) {
544                        mSurfaceHolder = new TakenSurfaceHolder();
545                        mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
546                    }
547                }
548
549                // Compute surface insets required to draw at specified Z value.
550                // TODO: Use real shadow insets for a constant max Z.
551                if (!attrs.hasManualSurfaceInsets) {
552                    final int surfaceInset = (int) Math.ceil(view.getZ() * 2);
553                    attrs.surfaceInsets.set(surfaceInset, surfaceInset, surfaceInset, surfaceInset);
554                }
555
556                CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
557                mTranslator = compatibilityInfo.getTranslator();
558
559                // If the application owns the surface, don't enable hardware acceleration
560                if (mSurfaceHolder == null) {
561                    enableHardwareAcceleration(attrs);
562                }
563
564                boolean restore = false;
565                if (mTranslator != null) {
566                    mSurface.setCompatibilityTranslator(mTranslator);
567                    restore = true;
568                    attrs.backup();
569                    mTranslator.translateWindowLayout(attrs);
570                }
571                if (DEBUG_LAYOUT) Log.d(mTag, "WindowLayout in setView:" + attrs);
572
573                if (!compatibilityInfo.supportsScreen()) {
574                    attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
575                    mLastInCompatMode = true;
576                }
577
578                mSoftInputMode = attrs.softInputMode;
579                mWindowAttributesChanged = true;
580                mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
581                mAttachInfo.mRootView = view;
582                mAttachInfo.mScalingRequired = mTranslator != null;
583                mAttachInfo.mApplicationScale =
584                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
585                if (panelParentView != null) {
586                    mAttachInfo.mPanelParentWindowToken
587                            = panelParentView.getApplicationWindowToken();
588                }
589                mAdded = true;
590                int res; /* = WindowManagerImpl.ADD_OKAY; */
591
592                // Schedule the first layout -before- adding to the window
593                // manager, to make sure we do the relayout before receiving
594                // any other events from the system.
595                requestLayout();
596                if ((mWindowAttributes.inputFeatures
597                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
598                    mInputChannel = new InputChannel();
599                }
600                mForceDecorViewVisibility = (mWindowAttributes.privateFlags
601                        & PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY) != 0;
602                try {
603                    mOrigWindowType = mWindowAttributes.type;
604                    mAttachInfo.mRecomputeGlobalAttributes = true;
605                    collectViewAttributes();
606                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
607                            getHostVisibility(), mDisplay.getDisplayId(),
608                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
609                            mAttachInfo.mOutsets, mInputChannel);
610                } catch (RemoteException e) {
611                    mAdded = false;
612                    mView = null;
613                    mAttachInfo.mRootView = null;
614                    mInputChannel = null;
615                    mFallbackEventHandler.setView(null);
616                    unscheduleTraversals();
617                    setAccessibilityFocus(null, null);
618                    throw new RuntimeException("Adding window failed", e);
619                } finally {
620                    if (restore) {
621                        attrs.restore();
622                    }
623                }
624
625                if (mTranslator != null) {
626                    mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
627                }
628                mPendingOverscanInsets.set(0, 0, 0, 0);
629                mPendingContentInsets.set(mAttachInfo.mContentInsets);
630                mPendingStableInsets.set(mAttachInfo.mStableInsets);
631                mPendingVisibleInsets.set(0, 0, 0, 0);
632                mAttachInfo.mAlwaysConsumeNavBar =
633                        (res & WindowManagerGlobal.ADD_FLAG_ALWAYS_CONSUME_NAV_BAR) != 0;
634                mPendingAlwaysConsumeNavBar = mAttachInfo.mAlwaysConsumeNavBar;
635                if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);
636                if (res < WindowManagerGlobal.ADD_OKAY) {
637                    mAttachInfo.mRootView = null;
638                    mAdded = false;
639                    mFallbackEventHandler.setView(null);
640                    unscheduleTraversals();
641                    setAccessibilityFocus(null, null);
642                    switch (res) {
643                        case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
644                        case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
645                            throw new WindowManager.BadTokenException(
646                                    "Unable to add window -- token " + attrs.token
647                                    + " is not valid; is your activity running?");
648                        case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
649                            throw new WindowManager.BadTokenException(
650                                    "Unable to add window -- token " + attrs.token
651                                    + " is not for an application");
652                        case WindowManagerGlobal.ADD_APP_EXITING:
653                            throw new WindowManager.BadTokenException(
654                                    "Unable to add window -- app for token " + attrs.token
655                                    + " is exiting");
656                        case WindowManagerGlobal.ADD_DUPLICATE_ADD:
657                            throw new WindowManager.BadTokenException(
658                                    "Unable to add window -- window " + mWindow
659                                    + " has already been added");
660                        case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
661                            // Silently ignore -- we would have just removed it
662                            // right away, anyway.
663                            return;
664                        case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
665                            throw new WindowManager.BadTokenException("Unable to add window "
666                                    + mWindow + " -- another window of type "
667                                    + mWindowAttributes.type + " already exists");
668                        case WindowManagerGlobal.ADD_PERMISSION_DENIED:
669                            throw new WindowManager.BadTokenException("Unable to add window "
670                                    + mWindow + " -- permission denied for window type "
671                                    + mWindowAttributes.type);
672                        case WindowManagerGlobal.ADD_INVALID_DISPLAY:
673                            throw new WindowManager.InvalidDisplayException("Unable to add window "
674                                    + mWindow + " -- the specified display can not be found");
675                        case WindowManagerGlobal.ADD_INVALID_TYPE:
676                            throw new WindowManager.InvalidDisplayException("Unable to add window "
677                                    + mWindow + " -- the specified window type "
678                                    + mWindowAttributes.type + " is not valid");
679                    }
680                    throw new RuntimeException(
681                            "Unable to add window -- unknown error code " + res);
682                }
683
684                if (view instanceof RootViewSurfaceTaker) {
685                    mInputQueueCallback =
686                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
687                }
688                if (mInputChannel != null) {
689                    if (mInputQueueCallback != null) {
690                        mInputQueue = new InputQueue();
691                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
692                    }
693                    mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
694                            Looper.myLooper());
695                }
696
697                view.assignParent(this);
698                mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
699                mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
700
701                if (mAccessibilityManager.isEnabled()) {
702                    mAccessibilityInteractionConnectionManager.ensureConnection();
703                }
704
705                if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
706                    view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
707                }
708
709                // Set up the input pipeline.
710                CharSequence counterSuffix = attrs.getTitle();
711                mSyntheticInputStage = new SyntheticInputStage();
712                InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
713                InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
714                        "aq:native-post-ime:" + counterSuffix);
715                InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
716                InputStage imeStage = new ImeInputStage(earlyPostImeStage,
717                        "aq:ime:" + counterSuffix);
718                InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
719                InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
720                        "aq:native-pre-ime:" + counterSuffix);
721
722                mFirstInputStage = nativePreImeStage;
723                mFirstPostImeInputStage = earlyPostImeStage;
724                mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
725            }
726        }
727    }
728
729    private void setTag() {
730        final String[] split = mWindowAttributes.getTitle().toString().split("\\.");
731        if (split.length > 0) {
732            mTag = TAG + "[" + split[split.length - 1] + "]";
733        }
734    }
735
736    /** Whether the window is in local focus mode or not */
737    private boolean isInLocalFocusMode() {
738        return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0;
739    }
740
741    public int getWindowFlags() {
742        return mWindowAttributes.flags;
743    }
744
745    public int getDisplayId() {
746        return mDisplay.getDisplayId();
747    }
748
749    public CharSequence getTitle() {
750        return mWindowAttributes.getTitle();
751    }
752
753    void destroyHardwareResources() {
754        if (mAttachInfo.mHardwareRenderer != null) {
755            mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
756            mAttachInfo.mHardwareRenderer.destroy();
757        }
758    }
759
760    public void detachFunctor(long functor) {
761        if (mAttachInfo.mHardwareRenderer != null) {
762            // Fence so that any pending invokeFunctor() messages will be processed
763            // before we return from detachFunctor.
764            mAttachInfo.mHardwareRenderer.stopDrawing();
765        }
766    }
767
768    /**
769     * Schedules the functor for execution in either kModeProcess or
770     * kModeProcessNoContext, depending on whether or not there is an EGLContext.
771     *
772     * @param functor The native functor to invoke
773     * @param waitForCompletion If true, this will not return until the functor
774     *                          has invoked. If false, the functor may be invoked
775     *                          asynchronously.
776     */
777    public void invokeFunctor(long functor, boolean waitForCompletion) {
778        ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
779    }
780
781    public void registerAnimatingRenderNode(RenderNode animator) {
782        if (mAttachInfo.mHardwareRenderer != null) {
783            mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
784        } else {
785            if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
786                mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
787            }
788            mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
789        }
790    }
791
792    private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
793        mAttachInfo.mHardwareAccelerated = false;
794        mAttachInfo.mHardwareAccelerationRequested = false;
795
796        // Don't enable hardware acceleration when the application is in compatibility mode
797        if (mTranslator != null) return;
798
799        // Try to enable hardware acceleration if requested
800        final boolean hardwareAccelerated =
801                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
802
803        if (hardwareAccelerated) {
804            if (!ThreadedRenderer.isAvailable()) {
805                return;
806            }
807
808            // Persistent processes (including the system) should not do
809            // accelerated rendering on low-end devices.  In that case,
810            // sRendererDisabled will be set.  In addition, the system process
811            // itself should never do accelerated rendering.  In that case, both
812            // sRendererDisabled and sSystemRendererDisabled are set.  When
813            // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
814            // can be used by code on the system process to escape that and enable
815            // HW accelerated drawing.  (This is basically for the lock screen.)
816
817            final boolean fakeHwAccelerated = (attrs.privateFlags &
818                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
819            final boolean forceHwAccelerated = (attrs.privateFlags &
820                    WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
821
822            if (fakeHwAccelerated) {
823                // This is exclusively for the preview windows the window manager
824                // shows for launching applications, so they will look more like
825                // the app being launched.
826                mAttachInfo.mHardwareAccelerationRequested = true;
827            } else if (!ThreadedRenderer.sRendererDisabled
828                    || (ThreadedRenderer.sSystemRendererDisabled && forceHwAccelerated)) {
829                if (mAttachInfo.mHardwareRenderer != null) {
830                    mAttachInfo.mHardwareRenderer.destroy();
831                }
832
833                final Rect insets = attrs.surfaceInsets;
834                final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
835                        || insets.top != 0 || insets.bottom != 0;
836                final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
837                mAttachInfo.mHardwareRenderer = ThreadedRenderer.create(mContext, translucent);
838                if (mAttachInfo.mHardwareRenderer != null) {
839                    mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
840                    mAttachInfo.mHardwareAccelerated =
841                            mAttachInfo.mHardwareAccelerationRequested = true;
842                }
843            }
844        }
845    }
846
847    public View getView() {
848        return mView;
849    }
850
851    final WindowLeaked getLocation() {
852        return mLocation;
853    }
854
855    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
856        synchronized (this) {
857            final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
858            final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
859            final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
860            final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
861            final int oldSoftInputMode = mWindowAttributes.softInputMode;
862            final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
863
864            // Keep track of the actual window flags supplied by the client.
865            mClientWindowLayoutFlags = attrs.flags;
866
867            // Preserve compatible window flag if exists.
868            final int compatibleWindowFlag = mWindowAttributes.privateFlags
869                    & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
870
871            // Transfer over system UI visibility values as they carry current state.
872            attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
873            attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
874
875            mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
876            if ((mWindowAttributesChangesFlag
877                    & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
878                // Recompute system ui visibility.
879                mAttachInfo.mRecomputeGlobalAttributes = true;
880            }
881            if (mWindowAttributes.packageName == null) {
882                mWindowAttributes.packageName = mBasePackageName;
883            }
884            mWindowAttributes.privateFlags |= compatibleWindowFlag;
885
886            // Restore old surface insets.
887            mWindowAttributes.surfaceInsets.set(
888                    oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
889            mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
890
891            applyKeepScreenOnFlag(mWindowAttributes);
892
893            if (newView) {
894                mSoftInputMode = attrs.softInputMode;
895                requestLayout();
896            }
897
898            // Don't lose the mode we last auto-computed.
899            if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
900                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
901                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
902                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
903                        | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
904            }
905
906            mWindowAttributesChanged = true;
907            scheduleTraversals();
908        }
909    }
910
911    void handleAppVisibility(boolean visible) {
912        if (mAppVisible != visible) {
913            mAppVisible = visible;
914            scheduleTraversals();
915            if (!mAppVisible) {
916                WindowManagerGlobal.trimForeground();
917            }
918        }
919    }
920
921    void handleGetNewSurface() {
922        mNewSurfaceNeeded = true;
923        mFullRedrawNeeded = true;
924        scheduleTraversals();
925    }
926
927    private final DisplayListener mDisplayListener = new DisplayListener() {
928        @Override
929        public void onDisplayChanged(int displayId) {
930            if (mView != null && mDisplay.getDisplayId() == displayId) {
931                final int oldDisplayState = mAttachInfo.mDisplayState;
932                final int newDisplayState = mDisplay.getState();
933                if (oldDisplayState != newDisplayState) {
934                    mAttachInfo.mDisplayState = newDisplayState;
935                    pokeDrawLockIfNeeded();
936                    if (oldDisplayState != Display.STATE_UNKNOWN) {
937                        final int oldScreenState = toViewScreenState(oldDisplayState);
938                        final int newScreenState = toViewScreenState(newDisplayState);
939                        if (oldScreenState != newScreenState) {
940                            mView.dispatchScreenStateChanged(newScreenState);
941                        }
942                        if (oldDisplayState == Display.STATE_OFF) {
943                            // Draw was suppressed so we need to for it to happen here.
944                            mFullRedrawNeeded = true;
945                            scheduleTraversals();
946                        }
947                    }
948                }
949            }
950        }
951
952        @Override
953        public void onDisplayRemoved(int displayId) {
954        }
955
956        @Override
957        public void onDisplayAdded(int displayId) {
958        }
959
960        private int toViewScreenState(int displayState) {
961            return displayState == Display.STATE_OFF ?
962                    View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
963        }
964    };
965
966    void pokeDrawLockIfNeeded() {
967        final int displayState = mAttachInfo.mDisplayState;
968        if (mView != null && mAdded && mTraversalScheduled
969                && (displayState == Display.STATE_DOZE
970                        || displayState == Display.STATE_DOZE_SUSPEND)) {
971            try {
972                mWindowSession.pokeDrawLock(mWindow);
973            } catch (RemoteException ex) {
974                // System server died, oh well.
975            }
976        }
977    }
978
979    @Override
980    public void requestFitSystemWindows() {
981        checkThread();
982        mApplyInsetsRequested = true;
983        scheduleTraversals();
984    }
985
986    @Override
987    public void requestLayout() {
988        if (!mHandlingLayoutInLayoutRequest) {
989            checkThread();
990            mLayoutRequested = true;
991            scheduleTraversals();
992        }
993    }
994
995    @Override
996    public boolean isLayoutRequested() {
997        return mLayoutRequested;
998    }
999
1000    void invalidate() {
1001        mDirty.set(0, 0, mWidth, mHeight);
1002        if (!mWillDrawSoon) {
1003            scheduleTraversals();
1004        }
1005    }
1006
1007    void invalidateWorld(View view) {
1008        view.invalidate();
1009        if (view instanceof ViewGroup) {
1010            ViewGroup parent = (ViewGroup) view;
1011            for (int i = 0; i < parent.getChildCount(); i++) {
1012                invalidateWorld(parent.getChildAt(i));
1013            }
1014        }
1015    }
1016
1017    @Override
1018    public void invalidateChild(View child, Rect dirty) {
1019        invalidateChildInParent(null, dirty);
1020    }
1021
1022    @Override
1023    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
1024        checkThread();
1025        if (DEBUG_DRAW) Log.v(mTag, "Invalidate child: " + dirty);
1026
1027        if (dirty == null) {
1028            invalidate();
1029            return null;
1030        } else if (dirty.isEmpty() && !mIsAnimating) {
1031            return null;
1032        }
1033
1034        if (mCurScrollY != 0 || mTranslator != null) {
1035            mTempRect.set(dirty);
1036            dirty = mTempRect;
1037            if (mCurScrollY != 0) {
1038                dirty.offset(0, -mCurScrollY);
1039            }
1040            if (mTranslator != null) {
1041                mTranslator.translateRectInAppWindowToScreen(dirty);
1042            }
1043            if (mAttachInfo.mScalingRequired) {
1044                dirty.inset(-1, -1);
1045            }
1046        }
1047
1048        invalidateRectOnScreen(dirty);
1049
1050        return null;
1051    }
1052
1053    private void invalidateRectOnScreen(Rect dirty) {
1054        final Rect localDirty = mDirty;
1055        if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
1056            mAttachInfo.mSetIgnoreDirtyState = true;
1057            mAttachInfo.mIgnoreDirtyState = true;
1058        }
1059
1060        // Add the new dirty rect to the current one
1061        localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
1062        // Intersect with the bounds of the window to skip
1063        // updates that lie outside of the visible region
1064        final float appScale = mAttachInfo.mApplicationScale;
1065        final boolean intersected = localDirty.intersect(0, 0,
1066                (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1067        if (!intersected) {
1068            localDirty.setEmpty();
1069        }
1070        if (!mWillDrawSoon && (intersected || mIsAnimating)) {
1071            scheduleTraversals();
1072        }
1073    }
1074
1075    public void setIsAmbientMode(boolean ambient) {
1076        mIsAmbientMode = ambient;
1077    }
1078
1079    void setWindowStopped(boolean stopped) {
1080        if (mStopped != stopped) {
1081            mStopped = stopped;
1082            if (!mStopped) {
1083                scheduleTraversals();
1084            } else {
1085                if (mAttachInfo.mHardwareRenderer != null) {
1086                    if (DEBUG_DRAW) Log.d(mTag, "WindowStopped on " + getTitle());
1087                    mAttachInfo.mHardwareRenderer.updateSurface(null);
1088                    mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
1089                }
1090            }
1091        }
1092    }
1093
1094    /**
1095     * Block the input events during an Activity Transition. The KEYCODE_BACK event is allowed
1096     * through to allow quick reversal of the Activity Transition.
1097     *
1098     * @param paused true to pause, false to resume.
1099     */
1100    public void setPausedForTransition(boolean paused) {
1101        mPausedForTransition = paused;
1102    }
1103
1104    @Override
1105    public ViewParent getParent() {
1106        return null;
1107    }
1108
1109    @Override
1110    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
1111        if (child != mView) {
1112            throw new RuntimeException("child is not mine, honest!");
1113        }
1114        // Note: don't apply scroll offset, because we want to know its
1115        // visibility in the virtual canvas being given to the view hierarchy.
1116        return r.intersect(0, 0, mWidth, mHeight);
1117    }
1118
1119    @Override
1120    public void bringChildToFront(View child) {
1121    }
1122
1123    int getHostVisibility() {
1124        return (mAppVisible || mForceDecorViewVisibility) ? mView.getVisibility() : View.GONE;
1125    }
1126
1127    /**
1128     * Add LayoutTransition to the list of transitions to be started in the next traversal.
1129     * This list will be cleared after the transitions on the list are start()'ed. These
1130     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
1131     * happens during the layout phase of traversal, which we want to complete before any of the
1132     * animations are started (because those animations may side-effect properties that layout
1133     * depends upon, like the bounding rectangles of the affected views). So we add the transition
1134     * to the list and it is started just prior to starting the drawing phase of traversal.
1135     *
1136     * @param transition The LayoutTransition to be started on the next traversal.
1137     *
1138     * @hide
1139     */
1140    public void requestTransitionStart(LayoutTransition transition) {
1141        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1142            if (mPendingTransitions == null) {
1143                 mPendingTransitions = new ArrayList<LayoutTransition>();
1144            }
1145            mPendingTransitions.add(transition);
1146        }
1147    }
1148
1149    /**
1150     * Notifies the HardwareRenderer that a new frame will be coming soon.
1151     * Currently only {@link ThreadedRenderer} cares about this, and uses
1152     * this knowledge to adjust the scheduling of off-thread animations
1153     */
1154    void notifyRendererOfFramePending() {
1155        if (mAttachInfo.mHardwareRenderer != null) {
1156            mAttachInfo.mHardwareRenderer.notifyFramePending();
1157        }
1158    }
1159
1160    void scheduleTraversals() {
1161        if (!mTraversalScheduled) {
1162            mTraversalScheduled = true;
1163            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
1164            mChoreographer.postCallback(
1165                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1166            if (!mUnbufferedInputDispatch) {
1167                scheduleConsumeBatchedInput();
1168            }
1169            notifyRendererOfFramePending();
1170            pokeDrawLockIfNeeded();
1171        }
1172    }
1173
1174    void unscheduleTraversals() {
1175        if (mTraversalScheduled) {
1176            mTraversalScheduled = false;
1177            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1178            mChoreographer.removeCallbacks(
1179                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1180        }
1181    }
1182
1183    void doTraversal() {
1184        if (mTraversalScheduled) {
1185            mTraversalScheduled = false;
1186            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1187
1188            if (mProfile) {
1189                Debug.startMethodTracing("ViewAncestor");
1190            }
1191
1192            performTraversals();
1193
1194            if (mProfile) {
1195                Debug.stopMethodTracing();
1196                mProfile = false;
1197            }
1198        }
1199    }
1200
1201    private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1202        // Update window's global keep screen on flag: if a view has requested
1203        // that the screen be kept on, then it is always set; otherwise, it is
1204        // set to whatever the client last requested for the global state.
1205        if (mAttachInfo.mKeepScreenOn) {
1206            params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1207        } else {
1208            params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1209                    | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1210        }
1211    }
1212
1213    private boolean collectViewAttributes() {
1214        if (mAttachInfo.mRecomputeGlobalAttributes) {
1215            //Log.i(mTag, "Computing view hierarchy attributes!");
1216            mAttachInfo.mRecomputeGlobalAttributes = false;
1217            boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
1218            mAttachInfo.mKeepScreenOn = false;
1219            mAttachInfo.mSystemUiVisibility = 0;
1220            mAttachInfo.mHasSystemUiListeners = false;
1221            mView.dispatchCollectViewAttributes(mAttachInfo, 0);
1222            mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
1223            WindowManager.LayoutParams params = mWindowAttributes;
1224            mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
1225            if (mAttachInfo.mKeepScreenOn != oldScreenOn
1226                    || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1227                    || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1228                applyKeepScreenOnFlag(params);
1229                params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1230                params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
1231                mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
1232                return true;
1233            }
1234        }
1235        return false;
1236    }
1237
1238    private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
1239        int vis = 0;
1240        // Translucent decor window flags imply stable system ui visibility.
1241        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
1242            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
1243        }
1244        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
1245            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
1246        }
1247        return vis;
1248    }
1249
1250    private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1251            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1252        int childWidthMeasureSpec;
1253        int childHeightMeasureSpec;
1254        boolean windowSizeMayChange = false;
1255
1256        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(mTag,
1257                "Measuring " + host + " in display " + desiredWindowWidth
1258                + "x" + desiredWindowHeight + "...");
1259
1260        boolean goodMeasure = false;
1261        if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1262            // On large screens, we don't want to allow dialogs to just
1263            // stretch to fill the entire width of the screen to display
1264            // one line of text.  First try doing the layout at a smaller
1265            // size to see if it will fit.
1266            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1267            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1268            int baseSize = 0;
1269            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1270                baseSize = (int)mTmpValue.getDimension(packageMetrics);
1271            }
1272            if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": baseSize=" + baseSize
1273                    + ", desiredWindowWidth=" + desiredWindowWidth);
1274            if (baseSize != 0 && desiredWindowWidth > baseSize) {
1275                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1276                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1277                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1278                if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
1279                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight()
1280                        + ") from width spec: " + MeasureSpec.toString(childWidthMeasureSpec)
1281                        + " and height spec: " + MeasureSpec.toString(childHeightMeasureSpec));
1282                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1283                    goodMeasure = true;
1284                } else {
1285                    // Didn't fit in that size... try expanding a bit.
1286                    baseSize = (baseSize+desiredWindowWidth)/2;
1287                    if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": next baseSize="
1288                            + baseSize);
1289                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1290                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1291                    if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
1292                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1293                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1294                        if (DEBUG_DIALOG) Log.v(mTag, "Good!");
1295                        goodMeasure = true;
1296                    }
1297                }
1298            }
1299        }
1300
1301        if (!goodMeasure) {
1302            childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1303            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1304            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1305            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1306                windowSizeMayChange = true;
1307            }
1308        }
1309
1310        if (DBG) {
1311            System.out.println("======================================");
1312            System.out.println("performTraversals -- after measure");
1313            host.debug();
1314        }
1315
1316        return windowSizeMayChange;
1317    }
1318
1319    /**
1320     * Modifies the input matrix such that it maps view-local coordinates to
1321     * on-screen coordinates.
1322     *
1323     * @param m input matrix to modify
1324     */
1325    void transformMatrixToGlobal(Matrix m) {
1326        m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
1327    }
1328
1329    /**
1330     * Modifies the input matrix such that it maps on-screen coordinates to
1331     * view-local coordinates.
1332     *
1333     * @param m input matrix to modify
1334     */
1335    void transformMatrixToLocal(Matrix m) {
1336        m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
1337    }
1338
1339    /* package */ WindowInsets getWindowInsets(boolean forceConstruct) {
1340        if (mLastWindowInsets == null || forceConstruct) {
1341            mDispatchContentInsets.set(mAttachInfo.mContentInsets);
1342            mDispatchStableInsets.set(mAttachInfo.mStableInsets);
1343            Rect contentInsets = mDispatchContentInsets;
1344            Rect stableInsets = mDispatchStableInsets;
1345            // For dispatch we preserve old logic, but for direct requests from Views we allow to
1346            // immediately use pending insets.
1347            if (!forceConstruct
1348                    && (!mPendingContentInsets.equals(contentInsets) ||
1349                        !mPendingStableInsets.equals(stableInsets))) {
1350                contentInsets = mPendingContentInsets;
1351                stableInsets = mPendingStableInsets;
1352            }
1353            Rect outsets = mAttachInfo.mOutsets;
1354            if (outsets.left > 0 || outsets.top > 0 || outsets.right > 0 || outsets.bottom > 0) {
1355                contentInsets = new Rect(contentInsets.left + outsets.left,
1356                        contentInsets.top + outsets.top, contentInsets.right + outsets.right,
1357                        contentInsets.bottom + outsets.bottom);
1358            }
1359            mLastWindowInsets = new WindowInsets(contentInsets,
1360                    null /* windowDecorInsets */, stableInsets,
1361                    mContext.getResources().getConfiguration().isScreenRound(),
1362                    mAttachInfo.mAlwaysConsumeNavBar);
1363        }
1364        return mLastWindowInsets;
1365    }
1366
1367    void dispatchApplyInsets(View host) {
1368        host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
1369    }
1370
1371    private static boolean shouldUseDisplaySize(final WindowManager.LayoutParams lp) {
1372        return lp.type == TYPE_STATUS_BAR_PANEL
1373                || lp.type == TYPE_INPUT_METHOD
1374                || lp.type == TYPE_VOLUME_OVERLAY;
1375    }
1376
1377    private int dipToPx(int dip) {
1378        final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
1379        return (int) (displayMetrics.density * dip + 0.5f);
1380    }
1381
1382    private void performTraversals() {
1383        // cache mView since it is used so much below...
1384        final View host = mView;
1385
1386        if (DBG) {
1387            System.out.println("======================================");
1388            System.out.println("performTraversals");
1389            host.debug();
1390        }
1391
1392        if (host == null || !mAdded)
1393            return;
1394
1395        mIsInTraversal = true;
1396        mWillDrawSoon = true;
1397        boolean windowSizeMayChange = false;
1398        boolean newSurface = false;
1399        boolean surfaceChanged = false;
1400        WindowManager.LayoutParams lp = mWindowAttributes;
1401
1402        int desiredWindowWidth;
1403        int desiredWindowHeight;
1404
1405        final int viewVisibility = getHostVisibility();
1406        final boolean viewVisibilityChanged = !mFirst
1407                && (mViewVisibility != viewVisibility || mNewSurfaceNeeded);
1408
1409        WindowManager.LayoutParams params = null;
1410        if (mWindowAttributesChanged) {
1411            mWindowAttributesChanged = false;
1412            surfaceChanged = true;
1413            params = lp;
1414        }
1415        CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
1416        if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1417            params = lp;
1418            mFullRedrawNeeded = true;
1419            mLayoutRequested = true;
1420            if (mLastInCompatMode) {
1421                params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1422                mLastInCompatMode = false;
1423            } else {
1424                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1425                mLastInCompatMode = true;
1426            }
1427        }
1428
1429        mWindowAttributesChangesFlag = 0;
1430
1431        Rect frame = mWinFrame;
1432        if (mFirst) {
1433            mFullRedrawNeeded = true;
1434            mLayoutRequested = true;
1435
1436            if (shouldUseDisplaySize(lp)) {
1437                // NOTE -- system code, won't try to do compat mode.
1438                Point size = new Point();
1439                mDisplay.getRealSize(size);
1440                desiredWindowWidth = size.x;
1441                desiredWindowHeight = size.y;
1442            } else {
1443                Configuration config = mContext.getResources().getConfiguration();
1444                desiredWindowWidth = dipToPx(config.screenWidthDp);
1445                desiredWindowHeight = dipToPx(config.screenHeightDp);
1446            }
1447
1448            // We used to use the following condition to choose 32 bits drawing caches:
1449            // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1450            // However, windows are now always 32 bits by default, so choose 32 bits
1451            mAttachInfo.mUse32BitDrawingCache = true;
1452            mAttachInfo.mHasWindowFocus = false;
1453            mAttachInfo.mWindowVisibility = viewVisibility;
1454            mAttachInfo.mRecomputeGlobalAttributes = false;
1455            mLastConfiguration.setTo(host.getResources().getConfiguration());
1456            mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1457            // Set the layout direction if it has not been set before (inherit is the default)
1458            if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1459                host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1460            }
1461            host.dispatchAttachedToWindow(mAttachInfo, 0);
1462            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1463            dispatchApplyInsets(host);
1464            //Log.i(mTag, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1465
1466        } else {
1467            desiredWindowWidth = frame.width();
1468            desiredWindowHeight = frame.height();
1469            if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1470                if (DEBUG_ORIENTATION) Log.v(mTag, "View " + host + " resized to: " + frame);
1471                mFullRedrawNeeded = true;
1472                mLayoutRequested = true;
1473                windowSizeMayChange = true;
1474            }
1475        }
1476
1477        if (viewVisibilityChanged) {
1478            mAttachInfo.mWindowVisibility = viewVisibility;
1479            host.dispatchWindowVisibilityChanged(viewVisibility);
1480            host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE);
1481            if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1482                endDragResizing();
1483                destroyHardwareResources();
1484            }
1485            if (viewVisibility == View.GONE) {
1486                // After making a window gone, we will count it as being
1487                // shown for the first time the next time it gets focus.
1488                mHasHadWindowFocus = false;
1489            }
1490        }
1491
1492        // Non-visible windows can't hold accessibility focus.
1493        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1494            host.clearAccessibilityFocus();
1495        }
1496
1497        // Execute enqueued actions on every traversal in case a detached view enqueued an action
1498        getRunQueue().executeActions(mAttachInfo.mHandler);
1499
1500        boolean insetsChanged = false;
1501
1502        boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
1503        if (layoutRequested) {
1504
1505            final Resources res = mView.getContext().getResources();
1506
1507            if (mFirst) {
1508                // make sure touch mode code executes by setting cached value
1509                // to opposite of the added touch mode.
1510                mAttachInfo.mInTouchMode = !mAddedTouchMode;
1511                ensureTouchModeLocally(mAddedTouchMode);
1512            } else {
1513                if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1514                    insetsChanged = true;
1515                }
1516                if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1517                    insetsChanged = true;
1518                }
1519                if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) {
1520                    insetsChanged = true;
1521                }
1522                if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1523                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1524                    if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
1525                            + mAttachInfo.mVisibleInsets);
1526                }
1527                if (!mPendingOutsets.equals(mAttachInfo.mOutsets)) {
1528                    insetsChanged = true;
1529                }
1530                if (mPendingAlwaysConsumeNavBar != mAttachInfo.mAlwaysConsumeNavBar) {
1531                    insetsChanged = true;
1532                }
1533                if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1534                        || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1535                    windowSizeMayChange = true;
1536
1537                    if (shouldUseDisplaySize(lp)) {
1538                        // NOTE -- system code, won't try to do compat mode.
1539                        Point size = new Point();
1540                        mDisplay.getRealSize(size);
1541                        desiredWindowWidth = size.x;
1542                        desiredWindowHeight = size.y;
1543                    } else {
1544                        Configuration config = res.getConfiguration();
1545                        desiredWindowWidth = dipToPx(config.screenWidthDp);
1546                        desiredWindowHeight = dipToPx(config.screenHeightDp);
1547                    }
1548                }
1549            }
1550
1551            // Ask host how big it wants to be
1552            windowSizeMayChange |= measureHierarchy(host, lp, res,
1553                    desiredWindowWidth, desiredWindowHeight);
1554        }
1555
1556        if (collectViewAttributes()) {
1557            params = lp;
1558        }
1559        if (mAttachInfo.mForceReportNewAttributes) {
1560            mAttachInfo.mForceReportNewAttributes = false;
1561            params = lp;
1562        }
1563
1564        if (mFirst || mAttachInfo.mViewVisibilityChanged) {
1565            mAttachInfo.mViewVisibilityChanged = false;
1566            int resizeMode = mSoftInputMode &
1567                    WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1568            // If we are in auto resize mode, then we need to determine
1569            // what mode to use now.
1570            if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1571                final int N = mAttachInfo.mScrollContainers.size();
1572                for (int i=0; i<N; i++) {
1573                    if (mAttachInfo.mScrollContainers.get(i).isShown()) {
1574                        resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1575                    }
1576                }
1577                if (resizeMode == 0) {
1578                    resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1579                }
1580                if ((lp.softInputMode &
1581                        WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1582                    lp.softInputMode = (lp.softInputMode &
1583                            ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1584                            resizeMode;
1585                    params = lp;
1586                }
1587            }
1588        }
1589
1590        if (params != null) {
1591            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1592                if (!PixelFormat.formatHasAlpha(params.format)) {
1593                    params.format = PixelFormat.TRANSLUCENT;
1594                }
1595            }
1596            mAttachInfo.mOverscanRequested = (params.flags
1597                    & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
1598        }
1599
1600        if (mApplyInsetsRequested) {
1601            mApplyInsetsRequested = false;
1602            mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1603            dispatchApplyInsets(host);
1604            if (mLayoutRequested) {
1605                // Short-circuit catching a new layout request here, so
1606                // we don't need to go through two layout passes when things
1607                // change due to fitting system windows, which can happen a lot.
1608                windowSizeMayChange |= measureHierarchy(host, lp,
1609                        mView.getContext().getResources(),
1610                        desiredWindowWidth, desiredWindowHeight);
1611            }
1612        }
1613
1614        if (layoutRequested) {
1615            // Clear this now, so that if anything requests a layout in the
1616            // rest of this function we will catch it and re-run a full
1617            // layout pass.
1618            mLayoutRequested = false;
1619        }
1620
1621        boolean windowShouldResize = layoutRequested && windowSizeMayChange
1622            && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1623                || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1624                        frame.width() < desiredWindowWidth && frame.width() != mWidth)
1625                || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1626                        frame.height() < desiredWindowHeight && frame.height() != mHeight));
1627        windowShouldResize |= mDragResizing && mResizeMode == RESIZE_MODE_FREEFORM;
1628
1629        // If the activity was just relaunched, it might have unfrozen the task bounds (while
1630        // relaunching), so we need to force a call into window manager to pick up the latest
1631        // bounds.
1632        windowShouldResize |= mActivityRelaunched;
1633
1634        // Determine whether to compute insets.
1635        // If there are no inset listeners remaining then we may still need to compute
1636        // insets in case the old insets were non-empty and must be reset.
1637        final boolean computesInternalInsets =
1638                mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners()
1639                || mAttachInfo.mHasNonEmptyGivenInternalInsets;
1640
1641        boolean insetsPending = false;
1642        int relayoutResult = 0;
1643
1644        final boolean isViewVisible = viewVisibility == View.VISIBLE;
1645        if (mFirst || windowShouldResize || insetsChanged ||
1646                viewVisibilityChanged || params != null || mForceNextWindowRelayout) {
1647            mForceNextWindowRelayout = false;
1648
1649            if (isViewVisible) {
1650                // If this window is giving internal insets to the window
1651                // manager, and it is being added or changing its visibility,
1652                // then we want to first give the window manager "fake"
1653                // insets to cause it to effectively ignore the content of
1654                // the window during layout.  This avoids it briefly causing
1655                // other windows to resize/move based on the raw frame of the
1656                // window, waiting until we can finish laying out this window
1657                // and get back to the window manager with the ultimately
1658                // computed insets.
1659                insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1660            }
1661
1662            if (mSurfaceHolder != null) {
1663                mSurfaceHolder.mSurfaceLock.lock();
1664                mDrawingAllowed = true;
1665            }
1666
1667            boolean hwInitialized = false;
1668            boolean contentInsetsChanged = false;
1669            boolean hadSurface = mSurface.isValid();
1670
1671            try {
1672                if (DEBUG_LAYOUT) {
1673                    Log.i(mTag, "host=w:" + host.getMeasuredWidth() + ", h:" +
1674                            host.getMeasuredHeight() + ", params=" + params);
1675                }
1676
1677                if (mAttachInfo.mHardwareRenderer != null) {
1678                    // relayoutWindow may decide to destroy mSurface. As that decision
1679                    // happens in WindowManager service, we need to be defensive here
1680                    // and stop using the surface in case it gets destroyed.
1681                    if (mAttachInfo.mHardwareRenderer.pauseSurface(mSurface)) {
1682                        // Animations were running so we need to push a frame
1683                        // to resume them
1684                        mDirty.set(0, 0, mWidth, mHeight);
1685                    }
1686                    mChoreographer.mFrameInfo.addFlags(FrameInfo.FLAG_WINDOW_LAYOUT_CHANGED);
1687                }
1688                final int surfaceGenerationId = mSurface.getGenerationId();
1689                relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1690
1691                if (DEBUG_LAYOUT) Log.v(mTag, "relayout: frame=" + frame.toShortString()
1692                        + " overscan=" + mPendingOverscanInsets.toShortString()
1693                        + " content=" + mPendingContentInsets.toShortString()
1694                        + " visible=" + mPendingVisibleInsets.toShortString()
1695                        + " visible=" + mPendingStableInsets.toShortString()
1696                        + " outsets=" + mPendingOutsets.toShortString()
1697                        + " surface=" + mSurface);
1698
1699                if (mPendingConfiguration.seq != 0) {
1700                    if (DEBUG_CONFIGURATION) Log.v(mTag, "Visible with new config: "
1701                            + mPendingConfiguration);
1702                    updateConfiguration(new Configuration(mPendingConfiguration), !mFirst);
1703                    mPendingConfiguration.seq = 0;
1704                }
1705
1706                final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals(
1707                        mAttachInfo.mOverscanInsets);
1708                contentInsetsChanged = !mPendingContentInsets.equals(
1709                        mAttachInfo.mContentInsets);
1710                final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals(
1711                        mAttachInfo.mVisibleInsets);
1712                final boolean stableInsetsChanged = !mPendingStableInsets.equals(
1713                        mAttachInfo.mStableInsets);
1714                final boolean outsetsChanged = !mPendingOutsets.equals(mAttachInfo.mOutsets);
1715                final boolean surfaceSizeChanged = (relayoutResult
1716                        & WindowManagerGlobal.RELAYOUT_RES_SURFACE_RESIZED) != 0;
1717                final boolean alwaysConsumeNavBarChanged =
1718                        mPendingAlwaysConsumeNavBar != mAttachInfo.mAlwaysConsumeNavBar;
1719                if (contentInsetsChanged) {
1720                    mAttachInfo.mContentInsets.set(mPendingContentInsets);
1721                    if (DEBUG_LAYOUT) Log.v(mTag, "Content insets changing to: "
1722                            + mAttachInfo.mContentInsets);
1723                }
1724                if (overscanInsetsChanged) {
1725                    mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets);
1726                    if (DEBUG_LAYOUT) Log.v(mTag, "Overscan insets changing to: "
1727                            + mAttachInfo.mOverscanInsets);
1728                    // Need to relayout with content insets.
1729                    contentInsetsChanged = true;
1730                }
1731                if (stableInsetsChanged) {
1732                    mAttachInfo.mStableInsets.set(mPendingStableInsets);
1733                    if (DEBUG_LAYOUT) Log.v(mTag, "Decor insets changing to: "
1734                            + mAttachInfo.mStableInsets);
1735                    // Need to relayout with content insets.
1736                    contentInsetsChanged = true;
1737                }
1738                if (alwaysConsumeNavBarChanged) {
1739                    mAttachInfo.mAlwaysConsumeNavBar = mPendingAlwaysConsumeNavBar;
1740                    contentInsetsChanged = true;
1741                }
1742                if (contentInsetsChanged || mLastSystemUiVisibility !=
1743                        mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested
1744                        || mLastOverscanRequested != mAttachInfo.mOverscanRequested
1745                        || outsetsChanged) {
1746                    mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1747                    mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1748                    mAttachInfo.mOutsets.set(mPendingOutsets);
1749                    mApplyInsetsRequested = false;
1750                    dispatchApplyInsets(host);
1751                }
1752                if (visibleInsetsChanged) {
1753                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1754                    if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
1755                            + mAttachInfo.mVisibleInsets);
1756                }
1757
1758                if (!hadSurface) {
1759                    if (mSurface.isValid()) {
1760                        // If we are creating a new surface, then we need to
1761                        // completely redraw it.  Also, when we get to the
1762                        // point of drawing it we will hold off and schedule
1763                        // a new traversal instead.  This is so we can tell the
1764                        // window manager about all of the windows being displayed
1765                        // before actually drawing them, so it can display then
1766                        // all at once.
1767                        newSurface = true;
1768                        mFullRedrawNeeded = true;
1769                        mPreviousTransparentRegion.setEmpty();
1770
1771                        // Only initialize up-front if transparent regions are not
1772                        // requested, otherwise defer to see if the entire window
1773                        // will be transparent
1774                        if (mAttachInfo.mHardwareRenderer != null) {
1775                            try {
1776                                hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1777                                        mSurface);
1778                                if (hwInitialized && (host.mPrivateFlags
1779                                        & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) {
1780                                    // Don't pre-allocate if transparent regions
1781                                    // are requested as they may not be needed
1782                                    mSurface.allocateBuffers();
1783                                }
1784                            } catch (OutOfResourcesException e) {
1785                                handleOutOfResourcesException(e);
1786                                return;
1787                            }
1788                        }
1789                    }
1790                } else if (!mSurface.isValid()) {
1791                    // If the surface has been removed, then reset the scroll
1792                    // positions.
1793                    if (mLastScrolledFocus != null) {
1794                        mLastScrolledFocus.clear();
1795                    }
1796                    mScrollY = mCurScrollY = 0;
1797                    if (mView instanceof RootViewSurfaceTaker) {
1798                        ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
1799                    }
1800                    if (mScroller != null) {
1801                        mScroller.abortAnimation();
1802                    }
1803                    // Our surface is gone
1804                    if (mAttachInfo.mHardwareRenderer != null &&
1805                            mAttachInfo.mHardwareRenderer.isEnabled()) {
1806                        mAttachInfo.mHardwareRenderer.destroy();
1807                    }
1808                } else if ((surfaceGenerationId != mSurface.getGenerationId()
1809                        || surfaceSizeChanged)
1810                        && mSurfaceHolder == null
1811                        && mAttachInfo.mHardwareRenderer != null) {
1812                    mFullRedrawNeeded = true;
1813                    try {
1814                        // Need to do updateSurface (which leads to CanvasContext::setSurface and
1815                        // re-create the EGLSurface) if either the Surface changed (as indicated by
1816                        // generation id), or WindowManager changed the surface size. The latter is
1817                        // because on some chips, changing the consumer side's BufferQueue size may
1818                        // not take effect immediately unless we create a new EGLSurface.
1819                        // Note that frame size change doesn't always imply surface size change (eg.
1820                        // drag resizing uses fullscreen surface), need to check surfaceSizeChanged
1821                        // flag from WindowManager.
1822                        mAttachInfo.mHardwareRenderer.updateSurface(mSurface);
1823                    } catch (OutOfResourcesException e) {
1824                        handleOutOfResourcesException(e);
1825                        return;
1826                    }
1827                }
1828
1829                final boolean freeformResizing = (relayoutResult
1830                        & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_FREEFORM) != 0;
1831                final boolean dockedResizing = (relayoutResult
1832                        & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_DOCKED) != 0;
1833                final boolean dragResizing = freeformResizing || dockedResizing;
1834                if (mDragResizing != dragResizing) {
1835                    if (dragResizing) {
1836                        mResizeMode = freeformResizing
1837                                ? RESIZE_MODE_FREEFORM
1838                                : RESIZE_MODE_DOCKED_DIVIDER;
1839                        startDragResizing(mPendingBackDropFrame,
1840                                mWinFrame.equals(mPendingBackDropFrame), mPendingVisibleInsets,
1841                                mPendingStableInsets, mResizeMode);
1842                    } else {
1843                        // We shouldn't come here, but if we come we should end the resize.
1844                        endDragResizing();
1845                    }
1846                }
1847                if (!USE_MT_RENDERER) {
1848                    if (dragResizing) {
1849                        mCanvasOffsetX = mWinFrame.left;
1850                        mCanvasOffsetY = mWinFrame.top;
1851                    } else {
1852                        mCanvasOffsetX = mCanvasOffsetY = 0;
1853                    }
1854                }
1855            } catch (RemoteException e) {
1856            }
1857
1858            if (DEBUG_ORIENTATION) Log.v(
1859                    TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1860
1861            mAttachInfo.mWindowLeft = frame.left;
1862            mAttachInfo.mWindowTop = frame.top;
1863
1864            // !!FIXME!! This next section handles the case where we did not get the
1865            // window size we asked for. We should avoid this by getting a maximum size from
1866            // the window session beforehand.
1867            if (mWidth != frame.width() || mHeight != frame.height()) {
1868                mWidth = frame.width();
1869                mHeight = frame.height();
1870            }
1871
1872            if (mSurfaceHolder != null) {
1873                // The app owns the surface; tell it about what is going on.
1874                if (mSurface.isValid()) {
1875                    // XXX .copyFrom() doesn't work!
1876                    //mSurfaceHolder.mSurface.copyFrom(mSurface);
1877                    mSurfaceHolder.mSurface = mSurface;
1878                }
1879                mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1880                mSurfaceHolder.mSurfaceLock.unlock();
1881                if (mSurface.isValid()) {
1882                    if (!hadSurface) {
1883                        mSurfaceHolder.ungetCallbacks();
1884
1885                        mIsCreating = true;
1886                        mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1887                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1888                        if (callbacks != null) {
1889                            for (SurfaceHolder.Callback c : callbacks) {
1890                                c.surfaceCreated(mSurfaceHolder);
1891                            }
1892                        }
1893                        surfaceChanged = true;
1894                    }
1895                    if (surfaceChanged) {
1896                        mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1897                                lp.format, mWidth, mHeight);
1898                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1899                        if (callbacks != null) {
1900                            for (SurfaceHolder.Callback c : callbacks) {
1901                                c.surfaceChanged(mSurfaceHolder, lp.format,
1902                                        mWidth, mHeight);
1903                            }
1904                        }
1905                    }
1906                    mIsCreating = false;
1907                } else if (hadSurface) {
1908                    mSurfaceHolder.ungetCallbacks();
1909                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1910                    mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1911                    if (callbacks != null) {
1912                        for (SurfaceHolder.Callback c : callbacks) {
1913                            c.surfaceDestroyed(mSurfaceHolder);
1914                        }
1915                    }
1916                    mSurfaceHolder.mSurfaceLock.lock();
1917                    try {
1918                        mSurfaceHolder.mSurface = new Surface();
1919                    } finally {
1920                        mSurfaceHolder.mSurfaceLock.unlock();
1921                    }
1922                }
1923            }
1924
1925            final ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
1926            if (hardwareRenderer != null && hardwareRenderer.isEnabled()) {
1927                if (hwInitialized
1928                        || mWidth != hardwareRenderer.getWidth()
1929                        || mHeight != hardwareRenderer.getHeight()) {
1930                    hardwareRenderer.setup(mWidth, mHeight, mAttachInfo,
1931                            mWindowAttributes.surfaceInsets);
1932                }
1933            }
1934
1935            if (!mStopped || mReportNextDraw) {
1936                boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1937                        (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1938                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1939                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged) {
1940                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1941                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
1942
1943                    if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
1944                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
1945                            + " mHeight=" + mHeight
1946                            + " measuredHeight=" + host.getMeasuredHeight()
1947                            + " coveredInsetsChanged=" + contentInsetsChanged);
1948
1949                     // Ask host how big it wants to be
1950                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1951
1952                    // Implementation of weights from WindowManager.LayoutParams
1953                    // We just grow the dimensions as needed and re-measure if
1954                    // needs be
1955                    int width = host.getMeasuredWidth();
1956                    int height = host.getMeasuredHeight();
1957                    boolean measureAgain = false;
1958
1959                    if (lp.horizontalWeight > 0.0f) {
1960                        width += (int) ((mWidth - width) * lp.horizontalWeight);
1961                        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
1962                                MeasureSpec.EXACTLY);
1963                        measureAgain = true;
1964                    }
1965                    if (lp.verticalWeight > 0.0f) {
1966                        height += (int) ((mHeight - height) * lp.verticalWeight);
1967                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
1968                                MeasureSpec.EXACTLY);
1969                        measureAgain = true;
1970                    }
1971
1972                    if (measureAgain) {
1973                        if (DEBUG_LAYOUT) Log.v(mTag,
1974                                "And hey let's measure once more: width=" + width
1975                                + " height=" + height);
1976                        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1977                    }
1978
1979                    layoutRequested = true;
1980                }
1981            }
1982        } else {
1983            // Not the first pass and no window/insets/visibility change but the window
1984            // may have moved and we need check that and if so to update the left and right
1985            // in the attach info. We translate only the window frame since on window move
1986            // the window manager tells us only for the new frame but the insets are the
1987            // same and we do not want to translate them more than once.
1988            maybeHandleWindowMove(frame);
1989        }
1990
1991        final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
1992        boolean triggerGlobalLayoutListener = didLayout
1993                || mAttachInfo.mRecomputeGlobalAttributes;
1994        if (didLayout) {
1995            performLayout(lp, mWidth, mHeight);
1996
1997            // By this point all views have been sized and positioned
1998            // We can compute the transparent area
1999
2000            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
2001                // start out transparent
2002                // TODO: AVOID THAT CALL BY CACHING THE RESULT?
2003                host.getLocationInWindow(mTmpLocation);
2004                mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
2005                        mTmpLocation[0] + host.mRight - host.mLeft,
2006                        mTmpLocation[1] + host.mBottom - host.mTop);
2007
2008                host.gatherTransparentRegion(mTransparentRegion);
2009                if (mTranslator != null) {
2010                    mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
2011                }
2012
2013                if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
2014                    mPreviousTransparentRegion.set(mTransparentRegion);
2015                    mFullRedrawNeeded = true;
2016                    // reconfigure window manager
2017                    try {
2018                        mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
2019                    } catch (RemoteException e) {
2020                    }
2021                }
2022            }
2023
2024            if (DBG) {
2025                System.out.println("======================================");
2026                System.out.println("performTraversals -- after setFrame");
2027                host.debug();
2028            }
2029        }
2030
2031        if (triggerGlobalLayoutListener) {
2032            mAttachInfo.mRecomputeGlobalAttributes = false;
2033            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
2034        }
2035
2036        if (computesInternalInsets) {
2037            // Clear the original insets.
2038            final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
2039            insets.reset();
2040
2041            // Compute new insets in place.
2042            mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
2043            mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
2044
2045            // Tell the window manager.
2046            if (insetsPending || !mLastGivenInsets.equals(insets)) {
2047                mLastGivenInsets.set(insets);
2048
2049                // Translate insets to screen coordinates if needed.
2050                final Rect contentInsets;
2051                final Rect visibleInsets;
2052                final Region touchableRegion;
2053                if (mTranslator != null) {
2054                    contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
2055                    visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
2056                    touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
2057                } else {
2058                    contentInsets = insets.contentInsets;
2059                    visibleInsets = insets.visibleInsets;
2060                    touchableRegion = insets.touchableRegion;
2061                }
2062
2063                try {
2064                    mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
2065                            contentInsets, visibleInsets, touchableRegion);
2066                } catch (RemoteException e) {
2067                }
2068            }
2069        }
2070
2071        if (mFirst) {
2072            // handle first focus request
2073            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: mView.hasFocus()="
2074                    + mView.hasFocus());
2075            if (mView != null) {
2076                if (!mView.hasFocus()) {
2077                    mView.requestFocus(View.FOCUS_FORWARD);
2078                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: requested focused view="
2079                            + mView.findFocus());
2080                } else {
2081                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: existing focused view="
2082                            + mView.findFocus());
2083                }
2084            }
2085        }
2086
2087        final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible;
2088        final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible;
2089        final boolean regainedFocus = hasWindowFocus && mLostWindowFocus;
2090        if (regainedFocus) {
2091            mLostWindowFocus = false;
2092        } else if (!hasWindowFocus && mHadWindowFocus) {
2093            mLostWindowFocus = true;
2094        }
2095
2096        if (changedVisibility || regainedFocus) {
2097            host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2098        }
2099
2100        mFirst = false;
2101        mWillDrawSoon = false;
2102        mNewSurfaceNeeded = false;
2103        mActivityRelaunched = false;
2104        mViewVisibility = viewVisibility;
2105        mHadWindowFocus = hasWindowFocus;
2106
2107        if (hasWindowFocus && !isInLocalFocusMode()) {
2108            final boolean imTarget = WindowManager.LayoutParams
2109                    .mayUseInputMethod(mWindowAttributes.flags);
2110            if (imTarget != mLastWasImTarget) {
2111                mLastWasImTarget = imTarget;
2112                InputMethodManager imm = InputMethodManager.peekInstance();
2113                if (imm != null && imTarget) {
2114                    imm.onPreWindowFocus(mView, hasWindowFocus);
2115                    imm.onPostWindowFocus(mView, mView.findFocus(),
2116                            mWindowAttributes.softInputMode,
2117                            !mHasHadWindowFocus, mWindowAttributes.flags);
2118                }
2119            }
2120        }
2121
2122        // Remember if we must report the next draw.
2123        if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
2124            mReportNextDraw = true;
2125        }
2126
2127        boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
2128
2129        if (!cancelDraw) {
2130            if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2131                for (int i = 0; i < mPendingTransitions.size(); ++i) {
2132                    mPendingTransitions.get(i).startChangingAnimations();
2133                }
2134                mPendingTransitions.clear();
2135            }
2136
2137            performDraw();
2138        } else {
2139            if (isViewVisible) {
2140                // Try again
2141                scheduleTraversals();
2142            } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2143                for (int i = 0; i < mPendingTransitions.size(); ++i) {
2144                    mPendingTransitions.get(i).endChangingAnimations();
2145                }
2146                mPendingTransitions.clear();
2147            }
2148        }
2149
2150        mIsInTraversal = false;
2151    }
2152
2153    private void maybeHandleWindowMove(Rect frame) {
2154
2155        // TODO: Well, we are checking whether the frame has changed similarly
2156        // to how this is done for the insets. This is however incorrect since
2157        // the insets and the frame are translated. For example, the old frame
2158        // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
2159        // reported frame is (2, 2 - 2, 2) which implies no change but this is not
2160        // true since we are comparing a not translated value to a translated one.
2161        // This scenario is rare but we may want to fix that.
2162
2163        final boolean windowMoved = mAttachInfo.mWindowLeft != frame.left
2164                || mAttachInfo.mWindowTop != frame.top;
2165        if (windowMoved) {
2166            if (mTranslator != null) {
2167                mTranslator.translateRectInScreenToAppWinFrame(frame);
2168            }
2169            mAttachInfo.mWindowLeft = frame.left;
2170            mAttachInfo.mWindowTop = frame.top;
2171
2172            // Update the light position for the new window offsets.
2173            if (mAttachInfo.mHardwareRenderer != null) {
2174                mAttachInfo.mHardwareRenderer.setLightCenter(mAttachInfo);
2175            }
2176        }
2177    }
2178
2179    private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
2180        Log.e(mTag, "OutOfResourcesException initializing HW surface", e);
2181        try {
2182            if (!mWindowSession.outOfMemory(mWindow) &&
2183                    Process.myUid() != Process.SYSTEM_UID) {
2184                Slog.w(mTag, "No processes killed for memory; killing self");
2185                Process.killProcess(Process.myPid());
2186            }
2187        } catch (RemoteException ex) {
2188        }
2189        mLayoutRequested = true;    // ask wm for a new surface next time.
2190    }
2191
2192    private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2193        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2194        try {
2195            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2196        } finally {
2197            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2198        }
2199    }
2200
2201    /**
2202     * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2203     * is currently undergoing a layout pass.
2204     *
2205     * @return whether the view hierarchy is currently undergoing a layout pass
2206     */
2207    boolean isInLayout() {
2208        return mInLayout;
2209    }
2210
2211    /**
2212     * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
2213     * undergoing a layout pass. requestLayout() should not generally be called during layout,
2214     * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
2215     * all children in that container hierarchy are measured and laid out at the end of the layout
2216     * pass for that container). If requestLayout() is called anyway, we handle it correctly
2217     * by registering all requesters during a frame as it proceeds. At the end of the frame,
2218     * we check all of those views to see if any still have pending layout requests, which
2219     * indicates that they were not correctly handled by their container hierarchy. If that is
2220     * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
2221     * to blank containers, and force a second request/measure/layout pass in this frame. If
2222     * more requestLayout() calls are received during that second layout pass, we post those
2223     * requests to the next frame to avoid possible infinite loops.
2224     *
2225     * <p>The return value from this method indicates whether the request should proceed
2226     * (if it is a request during the first layout pass) or should be skipped and posted to the
2227     * next frame (if it is a request during the second layout pass).</p>
2228     *
2229     * @param view the view that requested the layout.
2230     *
2231     * @return true if request should proceed, false otherwise.
2232     */
2233    boolean requestLayoutDuringLayout(final View view) {
2234        if (view.mParent == null || view.mAttachInfo == null) {
2235            // Would not normally trigger another layout, so just let it pass through as usual
2236            return true;
2237        }
2238        if (!mLayoutRequesters.contains(view)) {
2239            mLayoutRequesters.add(view);
2240        }
2241        if (!mHandlingLayoutInLayoutRequest) {
2242            // Let the request proceed normally; it will be processed in a second layout pass
2243            // if necessary
2244            return true;
2245        } else {
2246            // Don't let the request proceed during the second layout pass.
2247            // It will post to the next frame instead.
2248            return false;
2249        }
2250    }
2251
2252    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2253            int desiredWindowHeight) {
2254        mLayoutRequested = false;
2255        mScrollMayChange = true;
2256        mInLayout = true;
2257
2258        final View host = mView;
2259        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
2260            Log.v(mTag, "Laying out " + host + " to (" +
2261                    host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2262        }
2263
2264        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2265        try {
2266            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2267
2268            mInLayout = false;
2269            int numViewsRequestingLayout = mLayoutRequesters.size();
2270            if (numViewsRequestingLayout > 0) {
2271                // requestLayout() was called during layout.
2272                // If no layout-request flags are set on the requesting views, there is no problem.
2273                // If some requests are still pending, then we need to clear those flags and do
2274                // a full request/measure/layout pass to handle this situation.
2275                ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
2276                        false);
2277                if (validLayoutRequesters != null) {
2278                    // Set this flag to indicate that any further requests are happening during
2279                    // the second pass, which may result in posting those requests to the next
2280                    // frame instead
2281                    mHandlingLayoutInLayoutRequest = true;
2282
2283                    // Process fresh layout requests, then measure and layout
2284                    int numValidRequests = validLayoutRequesters.size();
2285                    for (int i = 0; i < numValidRequests; ++i) {
2286                        final View view = validLayoutRequesters.get(i);
2287                        Log.w("View", "requestLayout() improperly called by " + view +
2288                                " during layout: running second layout pass");
2289                        view.requestLayout();
2290                    }
2291                    measureHierarchy(host, lp, mView.getContext().getResources(),
2292                            desiredWindowWidth, desiredWindowHeight);
2293                    mInLayout = true;
2294                    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2295
2296                    mHandlingLayoutInLayoutRequest = false;
2297
2298                    // Check the valid requests again, this time without checking/clearing the
2299                    // layout flags, since requests happening during the second pass get noop'd
2300                    validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
2301                    if (validLayoutRequesters != null) {
2302                        final ArrayList<View> finalRequesters = validLayoutRequesters;
2303                        // Post second-pass requests to the next frame
2304                        getRunQueue().post(new Runnable() {
2305                            @Override
2306                            public void run() {
2307                                int numValidRequests = finalRequesters.size();
2308                                for (int i = 0; i < numValidRequests; ++i) {
2309                                    final View view = finalRequesters.get(i);
2310                                    Log.w("View", "requestLayout() improperly called by " + view +
2311                                            " during second layout pass: posting in next frame");
2312                                    view.requestLayout();
2313                                }
2314                            }
2315                        });
2316                    }
2317                }
2318
2319            }
2320        } finally {
2321            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2322        }
2323        mInLayout = false;
2324    }
2325
2326    /**
2327     * This method is called during layout when there have been calls to requestLayout() during
2328     * layout. It walks through the list of views that requested layout to determine which ones
2329     * still need it, based on visibility in the hierarchy and whether they have already been
2330     * handled (as is usually the case with ListView children).
2331     *
2332     * @param layoutRequesters The list of views that requested layout during layout
2333     * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
2334     * If so, the FORCE_LAYOUT flag was not set on requesters.
2335     * @return A list of the actual views that still need to be laid out.
2336     */
2337    private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2338            boolean secondLayoutRequests) {
2339
2340        int numViewsRequestingLayout = layoutRequesters.size();
2341        ArrayList<View> validLayoutRequesters = null;
2342        for (int i = 0; i < numViewsRequestingLayout; ++i) {
2343            View view = layoutRequesters.get(i);
2344            if (view != null && view.mAttachInfo != null && view.mParent != null &&
2345                    (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
2346                            View.PFLAG_FORCE_LAYOUT)) {
2347                boolean gone = false;
2348                View parent = view;
2349                // Only trigger new requests for views in a non-GONE hierarchy
2350                while (parent != null) {
2351                    if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
2352                        gone = true;
2353                        break;
2354                    }
2355                    if (parent.mParent instanceof View) {
2356                        parent = (View) parent.mParent;
2357                    } else {
2358                        parent = null;
2359                    }
2360                }
2361                if (!gone) {
2362                    if (validLayoutRequesters == null) {
2363                        validLayoutRequesters = new ArrayList<View>();
2364                    }
2365                    validLayoutRequesters.add(view);
2366                }
2367            }
2368        }
2369        if (!secondLayoutRequests) {
2370            // If we're checking the layout flags, then we need to clean them up also
2371            for (int i = 0; i < numViewsRequestingLayout; ++i) {
2372                View view = layoutRequesters.get(i);
2373                while (view != null &&
2374                        (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2375                    view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2376                    if (view.mParent instanceof View) {
2377                        view = (View) view.mParent;
2378                    } else {
2379                        view = null;
2380                    }
2381                }
2382            }
2383        }
2384        layoutRequesters.clear();
2385        return validLayoutRequesters;
2386    }
2387
2388    @Override
2389    public void requestTransparentRegion(View child) {
2390        // the test below should not fail unless someone is messing with us
2391        checkThread();
2392        if (mView == child) {
2393            mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2394            // Need to make sure we re-evaluate the window attributes next
2395            // time around, to ensure the window has the correct format.
2396            mWindowAttributesChanged = true;
2397            mWindowAttributesChangesFlag = 0;
2398            requestLayout();
2399        }
2400    }
2401
2402    /**
2403     * Figures out the measure spec for the root view in a window based on it's
2404     * layout params.
2405     *
2406     * @param windowSize
2407     *            The available width or height of the window
2408     *
2409     * @param rootDimension
2410     *            The layout params for one dimension (width or height) of the
2411     *            window.
2412     *
2413     * @return The measure spec to use to measure the root view.
2414     */
2415    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2416        int measureSpec;
2417        switch (rootDimension) {
2418
2419        case ViewGroup.LayoutParams.MATCH_PARENT:
2420            // Window can't resize. Force root view to be windowSize.
2421            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2422            break;
2423        case ViewGroup.LayoutParams.WRAP_CONTENT:
2424            // Window can resize. Set max size for root view.
2425            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2426            break;
2427        default:
2428            // Window wants to be an exact size. Force root view to be that size.
2429            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2430            break;
2431        }
2432        return measureSpec;
2433    }
2434
2435    int mHardwareXOffset;
2436    int mHardwareYOffset;
2437
2438    @Override
2439    public void onHardwarePreDraw(DisplayListCanvas canvas) {
2440        canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
2441    }
2442
2443    @Override
2444    public void onHardwarePostDraw(DisplayListCanvas canvas) {
2445        drawAccessibilityFocusedDrawableIfNeeded(canvas);
2446        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
2447            mWindowCallbacks.get(i).onPostDraw(canvas);
2448        }
2449    }
2450
2451    /**
2452     * @hide
2453     */
2454    void outputDisplayList(View view) {
2455        view.mRenderNode.output();
2456        if (mAttachInfo.mHardwareRenderer != null) {
2457            ((ThreadedRenderer)mAttachInfo.mHardwareRenderer).serializeDisplayListTree();
2458        }
2459    }
2460
2461    /**
2462     * @see #PROPERTY_PROFILE_RENDERING
2463     */
2464    private void profileRendering(boolean enabled) {
2465        if (mProfileRendering) {
2466            mRenderProfilingEnabled = enabled;
2467
2468            if (mRenderProfiler != null) {
2469                mChoreographer.removeFrameCallback(mRenderProfiler);
2470            }
2471            if (mRenderProfilingEnabled) {
2472                if (mRenderProfiler == null) {
2473                    mRenderProfiler = new Choreographer.FrameCallback() {
2474                        @Override
2475                        public void doFrame(long frameTimeNanos) {
2476                            mDirty.set(0, 0, mWidth, mHeight);
2477                            scheduleTraversals();
2478                            if (mRenderProfilingEnabled) {
2479                                mChoreographer.postFrameCallback(mRenderProfiler);
2480                            }
2481                        }
2482                    };
2483                }
2484                mChoreographer.postFrameCallback(mRenderProfiler);
2485            } else {
2486                mRenderProfiler = null;
2487            }
2488        }
2489    }
2490
2491    /**
2492     * Called from draw() when DEBUG_FPS is enabled
2493     */
2494    private void trackFPS() {
2495        // Tracks frames per second drawn. First value in a series of draws may be bogus
2496        // because it down not account for the intervening idle time
2497        long nowTime = System.currentTimeMillis();
2498        if (mFpsStartTime < 0) {
2499            mFpsStartTime = mFpsPrevTime = nowTime;
2500            mFpsNumFrames = 0;
2501        } else {
2502            ++mFpsNumFrames;
2503            String thisHash = Integer.toHexString(System.identityHashCode(this));
2504            long frameTime = nowTime - mFpsPrevTime;
2505            long totalTime = nowTime - mFpsStartTime;
2506            Log.v(mTag, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2507            mFpsPrevTime = nowTime;
2508            if (totalTime > 1000) {
2509                float fps = (float) mFpsNumFrames * 1000 / totalTime;
2510                Log.v(mTag, "0x" + thisHash + "\tFPS:\t" + fps);
2511                mFpsStartTime = nowTime;
2512                mFpsNumFrames = 0;
2513            }
2514        }
2515    }
2516
2517    private void performDraw() {
2518        if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
2519            return;
2520        }
2521
2522        final boolean fullRedrawNeeded = mFullRedrawNeeded;
2523        mFullRedrawNeeded = false;
2524
2525        mIsDrawing = true;
2526        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2527        try {
2528            draw(fullRedrawNeeded);
2529        } finally {
2530            mIsDrawing = false;
2531            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2532        }
2533
2534        // For whatever reason we didn't create a HardwareRenderer, end any
2535        // hardware animations that are now dangling
2536        if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
2537            final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
2538            for (int i = 0; i < count; i++) {
2539                mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
2540            }
2541            mAttachInfo.mPendingAnimatingRenderNodes.clear();
2542        }
2543
2544        if (mReportNextDraw) {
2545            mReportNextDraw = false;
2546
2547            // if we're using multi-thread renderer, wait for the window frame draws
2548            if (mWindowDrawCountDown != null) {
2549                try {
2550                    mWindowDrawCountDown.await();
2551                } catch (InterruptedException e) {
2552                    Log.e(mTag, "Window redraw count down interruped!");
2553                }
2554                mWindowDrawCountDown = null;
2555            }
2556
2557            if (mAttachInfo.mHardwareRenderer != null) {
2558                mAttachInfo.mHardwareRenderer.fence();
2559            }
2560
2561            if (LOCAL_LOGV) {
2562                Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2563            }
2564            if (mSurfaceHolder != null && mSurface.isValid()) {
2565                mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2566                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2567                if (callbacks != null) {
2568                    for (SurfaceHolder.Callback c : callbacks) {
2569                        if (c instanceof SurfaceHolder.Callback2) {
2570                            ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(mSurfaceHolder);
2571                        }
2572                    }
2573                }
2574            }
2575            try {
2576                mWindowSession.finishDrawing(mWindow);
2577            } catch (RemoteException e) {
2578            }
2579        }
2580    }
2581
2582    private void draw(boolean fullRedrawNeeded) {
2583        Surface surface = mSurface;
2584        if (!surface.isValid()) {
2585            return;
2586        }
2587
2588        if (DEBUG_FPS) {
2589            trackFPS();
2590        }
2591
2592        if (!sFirstDrawComplete) {
2593            synchronized (sFirstDrawHandlers) {
2594                sFirstDrawComplete = true;
2595                final int count = sFirstDrawHandlers.size();
2596                for (int i = 0; i< count; i++) {
2597                    mHandler.post(sFirstDrawHandlers.get(i));
2598                }
2599            }
2600        }
2601
2602        scrollToRectOrFocus(null, false);
2603
2604        if (mAttachInfo.mViewScrollChanged) {
2605            mAttachInfo.mViewScrollChanged = false;
2606            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
2607        }
2608
2609        boolean animating = mScroller != null && mScroller.computeScrollOffset();
2610        final int curScrollY;
2611        if (animating) {
2612            curScrollY = mScroller.getCurrY();
2613        } else {
2614            curScrollY = mScrollY;
2615        }
2616        if (mCurScrollY != curScrollY) {
2617            mCurScrollY = curScrollY;
2618            fullRedrawNeeded = true;
2619            if (mView instanceof RootViewSurfaceTaker) {
2620                ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2621            }
2622        }
2623
2624        final float appScale = mAttachInfo.mApplicationScale;
2625        final boolean scalingRequired = mAttachInfo.mScalingRequired;
2626
2627        int resizeAlpha = 0;
2628
2629        final Rect dirty = mDirty;
2630        if (mSurfaceHolder != null) {
2631            // The app owns the surface, we won't draw.
2632            dirty.setEmpty();
2633            if (animating && mScroller != null) {
2634                mScroller.abortAnimation();
2635            }
2636            return;
2637        }
2638
2639        if (fullRedrawNeeded) {
2640            mAttachInfo.mIgnoreDirtyState = true;
2641            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2642        }
2643
2644        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2645            Log.v(mTag, "Draw " + mView + "/"
2646                    + mWindowAttributes.getTitle()
2647                    + ": dirty={" + dirty.left + "," + dirty.top
2648                    + "," + dirty.right + "," + dirty.bottom + "} surface="
2649                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2650                    appScale + ", width=" + mWidth + ", height=" + mHeight);
2651        }
2652
2653        mAttachInfo.mTreeObserver.dispatchOnDraw();
2654
2655        int xOffset = -mCanvasOffsetX;
2656        int yOffset = -mCanvasOffsetY + curScrollY;
2657        final WindowManager.LayoutParams params = mWindowAttributes;
2658        final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
2659        if (surfaceInsets != null) {
2660            xOffset -= surfaceInsets.left;
2661            yOffset -= surfaceInsets.top;
2662
2663            // Offset dirty rect for surface insets.
2664            dirty.offset(surfaceInsets.left, surfaceInsets.right);
2665        }
2666
2667        boolean accessibilityFocusDirty = false;
2668        final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
2669        if (drawable != null) {
2670            final Rect bounds = mAttachInfo.mTmpInvalRect;
2671            final boolean hasFocus = getAccessibilityFocusedRect(bounds);
2672            if (!hasFocus) {
2673                bounds.setEmpty();
2674            }
2675            if (!bounds.equals(drawable.getBounds())) {
2676                accessibilityFocusDirty = true;
2677            }
2678        }
2679
2680        mAttachInfo.mDrawingTime =
2681                mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
2682
2683        if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
2684            if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
2685                // If accessibility focus moved, always invalidate the root.
2686                boolean invalidateRoot = accessibilityFocusDirty || mInvalidateRootRequested;
2687                mInvalidateRootRequested = false;
2688
2689                // Draw with hardware renderer.
2690                mIsAnimating = false;
2691
2692                if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2693                    mHardwareYOffset = yOffset;
2694                    mHardwareXOffset = xOffset;
2695                    invalidateRoot = true;
2696                }
2697
2698                if (invalidateRoot) {
2699                    mAttachInfo.mHardwareRenderer.invalidateRoot();
2700                }
2701
2702                dirty.setEmpty();
2703
2704                // Stage the content drawn size now. It will be transferred to the renderer
2705                // shortly before the draw commands get send to the renderer.
2706                final boolean updated = updateContentDrawBounds();
2707
2708                mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
2709
2710                if (updated) {
2711                    requestDrawWindow();
2712                }
2713            } else {
2714                // If we get here with a disabled & requested hardware renderer, something went
2715                // wrong (an invalidate posted right before we destroyed the hardware surface
2716                // for instance) so we should just bail out. Locking the surface with software
2717                // rendering at this point would lock it forever and prevent hardware renderer
2718                // from doing its job when it comes back.
2719                // Before we request a new frame we must however attempt to reinitiliaze the
2720                // hardware renderer if it's in requested state. This would happen after an
2721                // eglTerminate() for instance.
2722                if (mAttachInfo.mHardwareRenderer != null &&
2723                        !mAttachInfo.mHardwareRenderer.isEnabled() &&
2724                        mAttachInfo.mHardwareRenderer.isRequested()) {
2725
2726                    try {
2727                        mAttachInfo.mHardwareRenderer.initializeIfNeeded(
2728                                mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
2729                    } catch (OutOfResourcesException e) {
2730                        handleOutOfResourcesException(e);
2731                        return;
2732                    }
2733
2734                    mFullRedrawNeeded = true;
2735                    scheduleTraversals();
2736                    return;
2737                }
2738
2739                if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
2740                    return;
2741                }
2742            }
2743        }
2744
2745        if (animating) {
2746            mFullRedrawNeeded = true;
2747            scheduleTraversals();
2748        }
2749    }
2750
2751    /**
2752     * @return true if drawing was successful, false if an error occurred
2753     */
2754    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
2755            boolean scalingRequired, Rect dirty) {
2756
2757        // Draw with software renderer.
2758        final Canvas canvas;
2759        try {
2760            final int left = dirty.left;
2761            final int top = dirty.top;
2762            final int right = dirty.right;
2763            final int bottom = dirty.bottom;
2764
2765            canvas = mSurface.lockCanvas(dirty);
2766
2767            // The dirty rectangle can be modified by Surface.lockCanvas()
2768            //noinspection ConstantConditions
2769            if (left != dirty.left || top != dirty.top || right != dirty.right
2770                    || bottom != dirty.bottom) {
2771                attachInfo.mIgnoreDirtyState = true;
2772            }
2773
2774            // TODO: Do this in native
2775            canvas.setDensity(mDensity);
2776        } catch (Surface.OutOfResourcesException e) {
2777            handleOutOfResourcesException(e);
2778            return false;
2779        } catch (IllegalArgumentException e) {
2780            Log.e(mTag, "Could not lock surface", e);
2781            // Don't assume this is due to out of memory, it could be
2782            // something else, and if it is something else then we could
2783            // kill stuff (or ourself) for no reason.
2784            mLayoutRequested = true;    // ask wm for a new surface next time.
2785            return false;
2786        }
2787
2788        try {
2789            if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2790                Log.v(mTag, "Surface " + surface + " drawing to bitmap w="
2791                        + canvas.getWidth() + ", h=" + canvas.getHeight());
2792                //canvas.drawARGB(255, 255, 0, 0);
2793            }
2794
2795            // If this bitmap's format includes an alpha channel, we
2796            // need to clear it before drawing so that the child will
2797            // properly re-composite its drawing on a transparent
2798            // background. This automatically respects the clip/dirty region
2799            // or
2800            // If we are applying an offset, we need to clear the area
2801            // where the offset doesn't appear to avoid having garbage
2802            // left in the blank areas.
2803            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
2804                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2805            }
2806
2807            dirty.setEmpty();
2808            mIsAnimating = false;
2809            mView.mPrivateFlags |= View.PFLAG_DRAWN;
2810
2811            if (DEBUG_DRAW) {
2812                Context cxt = mView.getContext();
2813                Log.i(mTag, "Drawing: package:" + cxt.getPackageName() +
2814                        ", metrics=" + cxt.getResources().getDisplayMetrics() +
2815                        ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2816            }
2817            try {
2818                canvas.translate(-xoff, -yoff);
2819                if (mTranslator != null) {
2820                    mTranslator.translateCanvas(canvas);
2821                }
2822                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2823                attachInfo.mSetIgnoreDirtyState = false;
2824
2825                mView.draw(canvas);
2826
2827                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2828            } finally {
2829                if (!attachInfo.mSetIgnoreDirtyState) {
2830                    // Only clear the flag if it was not set during the mView.draw() call
2831                    attachInfo.mIgnoreDirtyState = false;
2832                }
2833            }
2834        } finally {
2835            try {
2836                surface.unlockCanvasAndPost(canvas);
2837            } catch (IllegalArgumentException e) {
2838                Log.e(mTag, "Could not unlock surface", e);
2839                mLayoutRequested = true;    // ask wm for a new surface next time.
2840                //noinspection ReturnInsideFinallyBlock
2841                return false;
2842            }
2843
2844            if (LOCAL_LOGV) {
2845                Log.v(mTag, "Surface " + surface + " unlockCanvasAndPost");
2846            }
2847        }
2848        return true;
2849    }
2850
2851    /**
2852     * We want to draw a highlight around the current accessibility focused.
2853     * Since adding a style for all possible view is not a viable option we
2854     * have this specialized drawing method.
2855     *
2856     * Note: We are doing this here to be able to draw the highlight for
2857     *       virtual views in addition to real ones.
2858     *
2859     * @param canvas The canvas on which to draw.
2860     */
2861    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2862        final Rect bounds = mAttachInfo.mTmpInvalRect;
2863        if (getAccessibilityFocusedRect(bounds)) {
2864            final Drawable drawable = getAccessibilityFocusedDrawable();
2865            if (drawable != null) {
2866                drawable.setBounds(bounds);
2867                drawable.draw(canvas);
2868            }
2869        } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2870            mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2871        }
2872    }
2873
2874    private boolean getAccessibilityFocusedRect(Rect bounds) {
2875        final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2876        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2877            return false;
2878        }
2879
2880        final View host = mAccessibilityFocusedHost;
2881        if (host == null || host.mAttachInfo == null) {
2882            return false;
2883        }
2884
2885        final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2886        if (provider == null) {
2887            host.getBoundsOnScreen(bounds, true);
2888        } else if (mAccessibilityFocusedVirtualView != null) {
2889            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2890        } else {
2891            return false;
2892        }
2893
2894        // Transform the rect into window-relative coordinates.
2895        final AttachInfo attachInfo = mAttachInfo;
2896        bounds.offset(0, attachInfo.mViewRootImpl.mScrollY);
2897        bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
2898        if (!bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth,
2899                attachInfo.mViewRootImpl.mHeight)) {
2900            // If no intersection, set bounds to empty.
2901            bounds.setEmpty();
2902        }
2903        return !bounds.isEmpty();
2904    }
2905
2906    private Drawable getAccessibilityFocusedDrawable() {
2907        // Lazily load the accessibility focus drawable.
2908        if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2909            final TypedValue value = new TypedValue();
2910            final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2911                    R.attr.accessibilityFocusedDrawable, value, true);
2912            if (resolved) {
2913                mAttachInfo.mAccessibilityFocusDrawable =
2914                        mView.mContext.getDrawable(value.resourceId);
2915            }
2916        }
2917        return mAttachInfo.mAccessibilityFocusDrawable;
2918    }
2919
2920    /**
2921     * Requests that the root render node is invalidated next time we perform a draw, such that
2922     * {@link WindowCallbacks#onPostDraw} gets called.
2923     */
2924    public void requestInvalidateRootRenderNode() {
2925        mInvalidateRootRequested = true;
2926    }
2927
2928    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2929        final Rect ci = mAttachInfo.mContentInsets;
2930        final Rect vi = mAttachInfo.mVisibleInsets;
2931        int scrollY = 0;
2932        boolean handled = false;
2933
2934        if (vi.left > ci.left || vi.top > ci.top
2935                || vi.right > ci.right || vi.bottom > ci.bottom) {
2936            // We'll assume that we aren't going to change the scroll
2937            // offset, since we want to avoid that unless it is actually
2938            // going to make the focus visible...  otherwise we scroll
2939            // all over the place.
2940            scrollY = mScrollY;
2941            // We can be called for two different situations: during a draw,
2942            // to update the scroll position if the focus has changed (in which
2943            // case 'rectangle' is null), or in response to a
2944            // requestChildRectangleOnScreen() call (in which case 'rectangle'
2945            // is non-null and we just want to scroll to whatever that
2946            // rectangle is).
2947            final View focus = mView.findFocus();
2948            if (focus == null) {
2949                return false;
2950            }
2951            View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
2952            if (focus != lastScrolledFocus) {
2953                // If the focus has changed, then ignore any requests to scroll
2954                // to a rectangle; first we want to make sure the entire focus
2955                // view is visible.
2956                rectangle = null;
2957            }
2958            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Eval scroll: focus=" + focus
2959                    + " rectangle=" + rectangle + " ci=" + ci
2960                    + " vi=" + vi);
2961            if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
2962                // Optimization: if the focus hasn't changed since last
2963                // time, and no layout has happened, then just leave things
2964                // as they are.
2965                if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Keeping scroll y="
2966                        + mScrollY + " vi=" + vi.toShortString());
2967            } else {
2968                // We need to determine if the currently focused view is
2969                // within the visible part of the window and, if not, apply
2970                // a pan so it can be seen.
2971                mLastScrolledFocus = new WeakReference<View>(focus);
2972                mScrollMayChange = false;
2973                if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Need to scroll?");
2974                // Try to find the rectangle from the focus view.
2975                if (focus.getGlobalVisibleRect(mVisRect, null)) {
2976                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Root w="
2977                            + mView.getWidth() + " h=" + mView.getHeight()
2978                            + " ci=" + ci.toShortString()
2979                            + " vi=" + vi.toShortString());
2980                    if (rectangle == null) {
2981                        focus.getFocusedRect(mTempRect);
2982                        if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Focus " + focus
2983                                + ": focusRect=" + mTempRect.toShortString());
2984                        if (mView instanceof ViewGroup) {
2985                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
2986                                    focus, mTempRect);
2987                        }
2988                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
2989                                "Focus in window: focusRect="
2990                                + mTempRect.toShortString()
2991                                + " visRect=" + mVisRect.toShortString());
2992                    } else {
2993                        mTempRect.set(rectangle);
2994                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
2995                                "Request scroll to rect: "
2996                                + mTempRect.toShortString()
2997                                + " visRect=" + mVisRect.toShortString());
2998                    }
2999                    if (mTempRect.intersect(mVisRect)) {
3000                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3001                                "Focus window visible rect: "
3002                                + mTempRect.toShortString());
3003                        if (mTempRect.height() >
3004                                (mView.getHeight()-vi.top-vi.bottom)) {
3005                            // If the focus simply is not going to fit, then
3006                            // best is probably just to leave things as-is.
3007                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3008                                    "Too tall; leaving scrollY=" + scrollY);
3009                        } else if ((mTempRect.top-scrollY) < vi.top) {
3010                            scrollY -= vi.top - (mTempRect.top-scrollY);
3011                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3012                                    "Top covered; scrollY=" + scrollY);
3013                        } else if ((mTempRect.bottom-scrollY)
3014                                > (mView.getHeight()-vi.bottom)) {
3015                            scrollY += (mTempRect.bottom-scrollY)
3016                                    - (mView.getHeight()-vi.bottom);
3017                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3018                                    "Bottom covered; scrollY=" + scrollY);
3019                        }
3020                        handled = true;
3021                    }
3022                }
3023            }
3024        }
3025
3026        if (scrollY != mScrollY) {
3027            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Pan scroll changed: old="
3028                    + mScrollY + " , new=" + scrollY);
3029            if (!immediate) {
3030                if (mScroller == null) {
3031                    mScroller = new Scroller(mView.getContext());
3032                }
3033                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
3034            } else if (mScroller != null) {
3035                mScroller.abortAnimation();
3036            }
3037            mScrollY = scrollY;
3038        }
3039
3040        return handled;
3041    }
3042
3043    /**
3044     * @hide
3045     */
3046    public View getAccessibilityFocusedHost() {
3047        return mAccessibilityFocusedHost;
3048    }
3049
3050    /**
3051     * @hide
3052     */
3053    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
3054        return mAccessibilityFocusedVirtualView;
3055    }
3056
3057    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
3058        // If we have a virtual view with accessibility focus we need
3059        // to clear the focus and invalidate the virtual view bounds.
3060        if (mAccessibilityFocusedVirtualView != null) {
3061
3062            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
3063            View focusHost = mAccessibilityFocusedHost;
3064
3065            // Wipe the state of the current accessibility focus since
3066            // the call into the provider to clear accessibility focus
3067            // will fire an accessibility event which will end up calling
3068            // this method and we want to have clean state when this
3069            // invocation happens.
3070            mAccessibilityFocusedHost = null;
3071            mAccessibilityFocusedVirtualView = null;
3072
3073            // Clear accessibility focus on the host after clearing state since
3074            // this method may be reentrant.
3075            focusHost.clearAccessibilityFocusNoCallbacks();
3076
3077            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
3078            if (provider != null) {
3079                // Invalidate the area of the cleared accessibility focus.
3080                focusNode.getBoundsInParent(mTempRect);
3081                focusHost.invalidate(mTempRect);
3082                // Clear accessibility focus in the virtual node.
3083                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
3084                        focusNode.getSourceNodeId());
3085                provider.performAction(virtualNodeId,
3086                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
3087            }
3088            focusNode.recycle();
3089        }
3090        if (mAccessibilityFocusedHost != null) {
3091            // Clear accessibility focus in the view.
3092            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks();
3093        }
3094
3095        // Set the new focus host and node.
3096        mAccessibilityFocusedHost = view;
3097        mAccessibilityFocusedVirtualView = node;
3098
3099        if (mAttachInfo.mHardwareRenderer != null) {
3100            mAttachInfo.mHardwareRenderer.invalidateRoot();
3101        }
3102    }
3103
3104    void setPointerCapture(View view) {
3105        if (!mAttachInfo.mHasWindowFocus) {
3106            Log.w(mTag, "Can't set capture if it's not focused.");
3107            return;
3108        }
3109        if (mCapturingView == view) {
3110            return;
3111        }
3112        mCapturingView = view;
3113        InputManager.getInstance().setPointerIconDetached(true);
3114    }
3115
3116    void releasePointerCapture(View view) {
3117        if (mCapturingView != view || mCapturingView == null) {
3118            return;
3119        }
3120
3121        mCapturingView = null;
3122        InputManager.getInstance().setPointerIconDetached(false);
3123    }
3124
3125    boolean hasPointerCapture(View view) {
3126        return view != null && mCapturingView == view;
3127    }
3128
3129    @Override
3130    public void requestChildFocus(View child, View focused) {
3131        if (DEBUG_INPUT_RESIZE) {
3132            Log.v(mTag, "Request child focus: focus now " + focused);
3133        }
3134        checkThread();
3135        scheduleTraversals();
3136    }
3137
3138    @Override
3139    public void clearChildFocus(View child) {
3140        if (DEBUG_INPUT_RESIZE) {
3141            Log.v(mTag, "Clearing child focus");
3142        }
3143        checkThread();
3144        scheduleTraversals();
3145    }
3146
3147    @Override
3148    public ViewParent getParentForAccessibility() {
3149        return null;
3150    }
3151
3152    @Override
3153    public void focusableViewAvailable(View v) {
3154        checkThread();
3155        if (mView != null) {
3156            if (!mView.hasFocus()) {
3157                v.requestFocus();
3158            } else {
3159                // the one case where will transfer focus away from the current one
3160                // is if the current view is a view group that prefers to give focus
3161                // to its children first AND the view is a descendant of it.
3162                View focused = mView.findFocus();
3163                if (focused instanceof ViewGroup) {
3164                    ViewGroup group = (ViewGroup) focused;
3165                    if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3166                            && isViewDescendantOf(v, focused)) {
3167                        v.requestFocus();
3168                    }
3169                }
3170            }
3171        }
3172    }
3173
3174    @Override
3175    public void recomputeViewAttributes(View child) {
3176        checkThread();
3177        if (mView == child) {
3178            mAttachInfo.mRecomputeGlobalAttributes = true;
3179            if (!mWillDrawSoon) {
3180                scheduleTraversals();
3181            }
3182        }
3183    }
3184
3185    void dispatchDetachedFromWindow() {
3186        if (mView != null && mView.mAttachInfo != null) {
3187            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3188            mView.dispatchDetachedFromWindow();
3189        }
3190
3191        mAccessibilityInteractionConnectionManager.ensureNoConnection();
3192        mAccessibilityManager.removeAccessibilityStateChangeListener(
3193                mAccessibilityInteractionConnectionManager);
3194        mAccessibilityManager.removeHighTextContrastStateChangeListener(
3195                mHighContrastTextManager);
3196        removeSendWindowContentChangedCallback();
3197
3198        destroyHardwareRenderer();
3199
3200        setAccessibilityFocus(null, null);
3201
3202        mView.assignParent(null);
3203        mView = null;
3204        mAttachInfo.mRootView = null;
3205
3206        if (mCapturingView != null) {
3207            releasePointerCapture(mCapturingView);
3208        }
3209
3210        mSurface.release();
3211
3212        if (mInputQueueCallback != null && mInputQueue != null) {
3213            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3214            mInputQueue.dispose();
3215            mInputQueueCallback = null;
3216            mInputQueue = null;
3217        }
3218        if (mInputEventReceiver != null) {
3219            mInputEventReceiver.dispose();
3220            mInputEventReceiver = null;
3221        }
3222        try {
3223            mWindowSession.remove(mWindow);
3224        } catch (RemoteException e) {
3225        }
3226
3227        // Dispose the input channel after removing the window so the Window Manager
3228        // doesn't interpret the input channel being closed as an abnormal termination.
3229        if (mInputChannel != null) {
3230            mInputChannel.dispose();
3231            mInputChannel = null;
3232        }
3233
3234        mDisplayManager.unregisterDisplayListener(mDisplayListener);
3235
3236        unscheduleTraversals();
3237    }
3238
3239    void updateConfiguration(Configuration config, boolean force) {
3240        if (DEBUG_CONFIGURATION) Log.v(mTag,
3241                "Applying new config to window "
3242                + mWindowAttributes.getTitle()
3243                + ": " + config);
3244
3245        CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3246        if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3247            config = new Configuration(config);
3248            ci.applyToConfiguration(mNoncompatDensity, config);
3249        }
3250
3251        synchronized (sConfigCallbacks) {
3252            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3253                sConfigCallbacks.get(i).onConfigurationChanged(config);
3254            }
3255        }
3256        if (mView != null) {
3257            // At this point the resources have been updated to
3258            // have the most recent config, whatever that is.  Use
3259            // the one in them which may be newer.
3260            config = mView.getResources().getConfiguration();
3261            if (force || mLastConfiguration.diff(config) != 0) {
3262                final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3263                final int currentLayoutDirection = config.getLayoutDirection();
3264                mLastConfiguration.setTo(config);
3265                if (lastLayoutDirection != currentLayoutDirection &&
3266                        mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
3267                    mView.setLayoutDirection(currentLayoutDirection);
3268                }
3269                mView.dispatchConfigurationChanged(config);
3270            }
3271        }
3272    }
3273
3274    /**
3275     * Return true if child is an ancestor of parent, (or equal to the parent).
3276     */
3277    public static boolean isViewDescendantOf(View child, View parent) {
3278        if (child == parent) {
3279            return true;
3280        }
3281
3282        final ViewParent theParent = child.getParent();
3283        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3284    }
3285
3286    private static void forceLayout(View view) {
3287        view.forceLayout();
3288        if (view instanceof ViewGroup) {
3289            ViewGroup group = (ViewGroup) view;
3290            final int count = group.getChildCount();
3291            for (int i = 0; i < count; i++) {
3292                forceLayout(group.getChildAt(i));
3293            }
3294        }
3295    }
3296
3297    private final static int MSG_INVALIDATE = 1;
3298    private final static int MSG_INVALIDATE_RECT = 2;
3299    private final static int MSG_DIE = 3;
3300    private final static int MSG_RESIZED = 4;
3301    private final static int MSG_RESIZED_REPORT = 5;
3302    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
3303    private final static int MSG_DISPATCH_INPUT_EVENT = 7;
3304    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3305    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
3306    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3307    private final static int MSG_CHECK_FOCUS = 13;
3308    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3309    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3310    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3311    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3312    private final static int MSG_UPDATE_CONFIGURATION = 18;
3313    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
3314    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
3315    private final static int MSG_INVALIDATE_WORLD = 22;
3316    private final static int MSG_WINDOW_MOVED = 23;
3317    private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
3318    private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
3319    private final static int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
3320    private final static int MSG_UPDATE_POINTER_ICON = 27;
3321
3322    final class ViewRootHandler extends Handler {
3323        @Override
3324        public String getMessageName(Message message) {
3325            switch (message.what) {
3326                case MSG_INVALIDATE:
3327                    return "MSG_INVALIDATE";
3328                case MSG_INVALIDATE_RECT:
3329                    return "MSG_INVALIDATE_RECT";
3330                case MSG_DIE:
3331                    return "MSG_DIE";
3332                case MSG_RESIZED:
3333                    return "MSG_RESIZED";
3334                case MSG_RESIZED_REPORT:
3335                    return "MSG_RESIZED_REPORT";
3336                case MSG_WINDOW_FOCUS_CHANGED:
3337                    return "MSG_WINDOW_FOCUS_CHANGED";
3338                case MSG_DISPATCH_INPUT_EVENT:
3339                    return "MSG_DISPATCH_INPUT_EVENT";
3340                case MSG_DISPATCH_APP_VISIBILITY:
3341                    return "MSG_DISPATCH_APP_VISIBILITY";
3342                case MSG_DISPATCH_GET_NEW_SURFACE:
3343                    return "MSG_DISPATCH_GET_NEW_SURFACE";
3344                case MSG_DISPATCH_KEY_FROM_IME:
3345                    return "MSG_DISPATCH_KEY_FROM_IME";
3346                case MSG_CHECK_FOCUS:
3347                    return "MSG_CHECK_FOCUS";
3348                case MSG_CLOSE_SYSTEM_DIALOGS:
3349                    return "MSG_CLOSE_SYSTEM_DIALOGS";
3350                case MSG_DISPATCH_DRAG_EVENT:
3351                    return "MSG_DISPATCH_DRAG_EVENT";
3352                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3353                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3354                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3355                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3356                case MSG_UPDATE_CONFIGURATION:
3357                    return "MSG_UPDATE_CONFIGURATION";
3358                case MSG_PROCESS_INPUT_EVENTS:
3359                    return "MSG_PROCESS_INPUT_EVENTS";
3360                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3361                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
3362                case MSG_WINDOW_MOVED:
3363                    return "MSG_WINDOW_MOVED";
3364                case MSG_SYNTHESIZE_INPUT_EVENT:
3365                    return "MSG_SYNTHESIZE_INPUT_EVENT";
3366                case MSG_DISPATCH_WINDOW_SHOWN:
3367                    return "MSG_DISPATCH_WINDOW_SHOWN";
3368                case MSG_UPDATE_POINTER_ICON:
3369                    return "MSG_UPDATE_POINTER_ICON";
3370            }
3371            return super.getMessageName(message);
3372        }
3373
3374        @Override
3375        public void handleMessage(Message msg) {
3376            switch (msg.what) {
3377            case MSG_INVALIDATE:
3378                ((View) msg.obj).invalidate();
3379                break;
3380            case MSG_INVALIDATE_RECT:
3381                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3382                info.target.invalidate(info.left, info.top, info.right, info.bottom);
3383                info.recycle();
3384                break;
3385            case MSG_PROCESS_INPUT_EVENTS:
3386                mProcessInputEventsScheduled = false;
3387                doProcessInputEvents();
3388                break;
3389            case MSG_DISPATCH_APP_VISIBILITY:
3390                handleAppVisibility(msg.arg1 != 0);
3391                break;
3392            case MSG_DISPATCH_GET_NEW_SURFACE:
3393                handleGetNewSurface();
3394                break;
3395            case MSG_RESIZED: {
3396                // Recycled in the fall through...
3397                SomeArgs args = (SomeArgs) msg.obj;
3398                if (mWinFrame.equals(args.arg1)
3399                        && mPendingOverscanInsets.equals(args.arg5)
3400                        && mPendingContentInsets.equals(args.arg2)
3401                        && mPendingStableInsets.equals(args.arg6)
3402                        && mPendingVisibleInsets.equals(args.arg3)
3403                        && mPendingOutsets.equals(args.arg7)
3404                        && mPendingBackDropFrame.equals(args.arg8)
3405                        && args.arg4 == null
3406                        && args.argi1 == 0) {
3407                    break;
3408                }
3409                } // fall through...
3410            case MSG_RESIZED_REPORT:
3411                if (mAdded) {
3412                    SomeArgs args = (SomeArgs) msg.obj;
3413
3414                    Configuration config = (Configuration) args.arg4;
3415                    if (config != null) {
3416                        updateConfiguration(config, false);
3417                    }
3418
3419                    mWinFrame.set((Rect) args.arg1);
3420                    mPendingOverscanInsets.set((Rect) args.arg5);
3421                    mPendingContentInsets.set((Rect) args.arg2);
3422                    mPendingStableInsets.set((Rect) args.arg6);
3423                    mPendingVisibleInsets.set((Rect) args.arg3);
3424                    mPendingOutsets.set((Rect) args.arg7);
3425                    mPendingBackDropFrame.set((Rect) args.arg8);
3426                    mForceNextWindowRelayout = args.argi1 != 0;
3427                    mPendingAlwaysConsumeNavBar = args.argi2 != 0;
3428
3429                    args.recycle();
3430
3431                    if (msg.what == MSG_RESIZED_REPORT) {
3432                        mReportNextDraw = true;
3433                    }
3434
3435                    if (mView != null) {
3436                        forceLayout(mView);
3437                    }
3438
3439                    requestLayout();
3440                }
3441                break;
3442            case MSG_WINDOW_MOVED:
3443                if (mAdded) {
3444                    final int w = mWinFrame.width();
3445                    final int h = mWinFrame.height();
3446                    final int l = msg.arg1;
3447                    final int t = msg.arg2;
3448                    mWinFrame.left = l;
3449                    mWinFrame.right = l + w;
3450                    mWinFrame.top = t;
3451                    mWinFrame.bottom = t + h;
3452
3453                    mPendingBackDropFrame.set(mWinFrame);
3454
3455                    // Suppress layouts during resizing - a correct layout will happen when resizing
3456                    // is done, and this just increases system load.
3457                    boolean isDockedDivider = mWindowAttributes.type == TYPE_DOCK_DIVIDER;
3458                    boolean suppress = (mDragResizing && mResizeMode == RESIZE_MODE_DOCKED_DIVIDER)
3459                            || isDockedDivider;
3460                    if (!suppress) {
3461                        if (mView != null) {
3462                            forceLayout(mView);
3463                        }
3464                        requestLayout();
3465                    } else {
3466                        maybeHandleWindowMove(mWinFrame);
3467                    }
3468                }
3469                break;
3470            case MSG_WINDOW_FOCUS_CHANGED: {
3471                if (mAdded) {
3472                    boolean hasWindowFocus = msg.arg1 != 0;
3473                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
3474
3475                    profileRendering(hasWindowFocus);
3476
3477                    if (hasWindowFocus) {
3478                        boolean inTouchMode = msg.arg2 != 0;
3479                        ensureTouchModeLocally(inTouchMode);
3480
3481                        if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3482                            mFullRedrawNeeded = true;
3483                            try {
3484                                final WindowManager.LayoutParams lp = mWindowAttributes;
3485                                final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
3486                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3487                                        mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
3488                            } catch (OutOfResourcesException e) {
3489                                Log.e(mTag, "OutOfResourcesException locking surface", e);
3490                                try {
3491                                    if (!mWindowSession.outOfMemory(mWindow)) {
3492                                        Slog.w(mTag, "No processes killed for memory; killing self");
3493                                        Process.killProcess(Process.myPid());
3494                                    }
3495                                } catch (RemoteException ex) {
3496                                }
3497                                // Retry in a bit.
3498                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3499                                return;
3500                            }
3501                        }
3502                    }
3503
3504                    mLastWasImTarget = WindowManager.LayoutParams
3505                            .mayUseInputMethod(mWindowAttributes.flags);
3506
3507                    InputMethodManager imm = InputMethodManager.peekInstance();
3508                    if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3509                        imm.onPreWindowFocus(mView, hasWindowFocus);
3510                    }
3511                    if (mView != null) {
3512                        mAttachInfo.mKeyDispatchState.reset();
3513                        mView.dispatchWindowFocusChanged(hasWindowFocus);
3514                        mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3515                    }
3516
3517                    // Note: must be done after the focus change callbacks,
3518                    // so all of the view state is set up correctly.
3519                    if (hasWindowFocus) {
3520                        if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3521                            imm.onPostWindowFocus(mView, mView.findFocus(),
3522                                    mWindowAttributes.softInputMode,
3523                                    !mHasHadWindowFocus, mWindowAttributes.flags);
3524                        }
3525                        // Clear the forward bit.  We can just do this directly, since
3526                        // the window manager doesn't care about it.
3527                        mWindowAttributes.softInputMode &=
3528                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3529                        ((WindowManager.LayoutParams)mView.getLayoutParams())
3530                                .softInputMode &=
3531                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3532                        mHasHadWindowFocus = true;
3533                    } else if (mCapturingView != null) {
3534                        releasePointerCapture(mCapturingView);
3535                    }
3536                }
3537            } break;
3538            case MSG_DIE:
3539                doDie();
3540                break;
3541            case MSG_DISPATCH_INPUT_EVENT: {
3542                SomeArgs args = (SomeArgs)msg.obj;
3543                InputEvent event = (InputEvent)args.arg1;
3544                InputEventReceiver receiver = (InputEventReceiver)args.arg2;
3545                enqueueInputEvent(event, receiver, 0, true);
3546                args.recycle();
3547            } break;
3548            case MSG_SYNTHESIZE_INPUT_EVENT: {
3549                InputEvent event = (InputEvent)msg.obj;
3550                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true);
3551            } break;
3552            case MSG_DISPATCH_KEY_FROM_IME: {
3553                if (LOCAL_LOGV) Log.v(
3554                    TAG, "Dispatching key "
3555                    + msg.obj + " from IME to " + mView);
3556                KeyEvent event = (KeyEvent)msg.obj;
3557                if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) {
3558                    // The IME is trying to say this event is from the
3559                    // system!  Bad bad bad!
3560                    //noinspection UnusedAssignment
3561                    event = KeyEvent.changeFlags(event, event.getFlags() &
3562                            ~KeyEvent.FLAG_FROM_SYSTEM);
3563                }
3564                enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true);
3565            } break;
3566            case MSG_CHECK_FOCUS: {
3567                InputMethodManager imm = InputMethodManager.peekInstance();
3568                if (imm != null) {
3569                    imm.checkFocus();
3570                }
3571            } break;
3572            case MSG_CLOSE_SYSTEM_DIALOGS: {
3573                if (mView != null) {
3574                    mView.onCloseSystemDialogs((String)msg.obj);
3575                }
3576            } break;
3577            case MSG_DISPATCH_DRAG_EVENT:
3578            case MSG_DISPATCH_DRAG_LOCATION_EVENT: {
3579                DragEvent event = (DragEvent)msg.obj;
3580                event.mLocalState = mLocalDragState;    // only present when this app called startDrag()
3581                handleDragEvent(event);
3582            } break;
3583            case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: {
3584                handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj);
3585            } break;
3586            case MSG_UPDATE_CONFIGURATION: {
3587                Configuration config = (Configuration)msg.obj;
3588                if (config.isOtherSeqNewer(mLastConfiguration)) {
3589                    config = mLastConfiguration;
3590                }
3591                updateConfiguration(config, false);
3592            } break;
3593            case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: {
3594                setAccessibilityFocus(null, null);
3595            } break;
3596            case MSG_INVALIDATE_WORLD: {
3597                if (mView != null) {
3598                    invalidateWorld(mView);
3599                }
3600            } break;
3601            case MSG_DISPATCH_WINDOW_SHOWN: {
3602                handleDispatchWindowShown();
3603            } break;
3604            case MSG_REQUEST_KEYBOARD_SHORTCUTS: {
3605                final IResultReceiver receiver = (IResultReceiver) msg.obj;
3606                final int deviceId = msg.arg1;
3607                handleRequestKeyboardShortcuts(receiver, deviceId);
3608            } break;
3609            case MSG_UPDATE_POINTER_ICON: {
3610                MotionEvent event = (MotionEvent) msg.obj;
3611                resetPointerIcon(event);
3612            } break;
3613            }
3614        }
3615    }
3616
3617    final ViewRootHandler mHandler = new ViewRootHandler();
3618
3619    /**
3620     * Something in the current window tells us we need to change the touch mode.  For
3621     * example, we are not in touch mode, and the user touches the screen.
3622     *
3623     * If the touch mode has changed, tell the window manager, and handle it locally.
3624     *
3625     * @param inTouchMode Whether we want to be in touch mode.
3626     * @return True if the touch mode changed and focus changed was changed as a result
3627     */
3628    boolean ensureTouchMode(boolean inTouchMode) {
3629        if (DBG) Log.d("touchmode", "ensureTouchMode(" + inTouchMode + "), current "
3630                + "touch mode is " + mAttachInfo.mInTouchMode);
3631        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3632
3633        // tell the window manager
3634        try {
3635            mWindowSession.setInTouchMode(inTouchMode);
3636        } catch (RemoteException e) {
3637            throw new RuntimeException(e);
3638        }
3639
3640        // handle the change
3641        return ensureTouchModeLocally(inTouchMode);
3642    }
3643
3644    /**
3645     * Ensure that the touch mode for this window is set, and if it is changing,
3646     * take the appropriate action.
3647     * @param inTouchMode Whether we want to be in touch mode.
3648     * @return True if the touch mode changed and focus changed was changed as a result
3649     */
3650    private boolean ensureTouchModeLocally(boolean inTouchMode) {
3651        if (DBG) Log.d("touchmode", "ensureTouchModeLocally(" + inTouchMode + "), current "
3652                + "touch mode is " + mAttachInfo.mInTouchMode);
3653
3654        if (mAttachInfo.mInTouchMode == inTouchMode) return false;
3655
3656        mAttachInfo.mInTouchMode = inTouchMode;
3657        mAttachInfo.mTreeObserver.dispatchOnTouchModeChanged(inTouchMode);
3658
3659        return (inTouchMode) ? enterTouchMode() : leaveTouchMode();
3660    }
3661
3662    private boolean enterTouchMode() {
3663        if (mView != null && mView.hasFocus()) {
3664            // note: not relying on mFocusedView here because this could
3665            // be when the window is first being added, and mFocused isn't
3666            // set yet.
3667            final View focused = mView.findFocus();
3668            if (focused != null && !focused.isFocusableInTouchMode()) {
3669                final ViewGroup ancestorToTakeFocus = findAncestorToTakeFocusInTouchMode(focused);
3670                if (ancestorToTakeFocus != null) {
3671                    // there is an ancestor that wants focus after its
3672                    // descendants that is focusable in touch mode.. give it
3673                    // focus
3674                    return ancestorToTakeFocus.requestFocus();
3675                } else {
3676                    // There's nothing to focus. Clear and propagate through the
3677                    // hierarchy, but don't attempt to place new focus.
3678                    focused.clearFocusInternal(null, true, false);
3679                    return true;
3680                }
3681            }
3682        }
3683        return false;
3684    }
3685
3686    /**
3687     * Find an ancestor of focused that wants focus after its descendants and is
3688     * focusable in touch mode.
3689     * @param focused The currently focused view.
3690     * @return An appropriate view, or null if no such view exists.
3691     */
3692    private static ViewGroup findAncestorToTakeFocusInTouchMode(View focused) {
3693        ViewParent parent = focused.getParent();
3694        while (parent instanceof ViewGroup) {
3695            final ViewGroup vgParent = (ViewGroup) parent;
3696            if (vgParent.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3697                    && vgParent.isFocusableInTouchMode()) {
3698                return vgParent;
3699            }
3700            if (vgParent.isRootNamespace()) {
3701                return null;
3702            } else {
3703                parent = vgParent.getParent();
3704            }
3705        }
3706        return null;
3707    }
3708
3709    private boolean leaveTouchMode() {
3710        if (mView != null) {
3711            if (mView.hasFocus()) {
3712                View focusedView = mView.findFocus();
3713                if (!(focusedView instanceof ViewGroup)) {
3714                    // some view has focus, let it keep it
3715                    return false;
3716                } else if (((ViewGroup) focusedView).getDescendantFocusability() !=
3717                        ViewGroup.FOCUS_AFTER_DESCENDANTS) {
3718                    // some view group has focus, and doesn't prefer its children
3719                    // over itself for focus, so let them keep it.
3720                    return false;
3721                }
3722            }
3723
3724            // find the best view to give focus to in this brave new non-touch-mode
3725            // world
3726            final View focused = focusSearch(null, View.FOCUS_DOWN);
3727            if (focused != null) {
3728                return focused.requestFocus(View.FOCUS_DOWN);
3729            }
3730        }
3731        return false;
3732    }
3733
3734    /**
3735     * Base class for implementing a stage in the chain of responsibility
3736     * for processing input events.
3737     * <p>
3738     * Events are delivered to the stage by the {@link #deliver} method.  The stage
3739     * then has the choice of finishing the event or forwarding it to the next stage.
3740     * </p>
3741     */
3742    abstract class InputStage {
3743        private final InputStage mNext;
3744
3745        protected static final int FORWARD = 0;
3746        protected static final int FINISH_HANDLED = 1;
3747        protected static final int FINISH_NOT_HANDLED = 2;
3748
3749        /**
3750         * Creates an input stage.
3751         * @param next The next stage to which events should be forwarded.
3752         */
3753        public InputStage(InputStage next) {
3754            mNext = next;
3755        }
3756
3757        /**
3758         * Delivers an event to be processed.
3759         */
3760        public final void deliver(QueuedInputEvent q) {
3761            if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
3762                forward(q);
3763            } else if (shouldDropInputEvent(q)) {
3764                finish(q, false);
3765            } else {
3766                apply(q, onProcess(q));
3767            }
3768        }
3769
3770        /**
3771         * Marks the the input event as finished then forwards it to the next stage.
3772         */
3773        protected void finish(QueuedInputEvent q, boolean handled) {
3774            q.mFlags |= QueuedInputEvent.FLAG_FINISHED;
3775            if (handled) {
3776                q.mFlags |= QueuedInputEvent.FLAG_FINISHED_HANDLED;
3777            }
3778            forward(q);
3779        }
3780
3781        /**
3782         * Forwards the event to the next stage.
3783         */
3784        protected void forward(QueuedInputEvent q) {
3785            onDeliverToNext(q);
3786        }
3787
3788        /**
3789         * Applies a result code from {@link #onProcess} to the specified event.
3790         */
3791        protected void apply(QueuedInputEvent q, int result) {
3792            if (result == FORWARD) {
3793                forward(q);
3794            } else if (result == FINISH_HANDLED) {
3795                finish(q, true);
3796            } else if (result == FINISH_NOT_HANDLED) {
3797                finish(q, false);
3798            } else {
3799                throw new IllegalArgumentException("Invalid result: " + result);
3800            }
3801        }
3802
3803        /**
3804         * Called when an event is ready to be processed.
3805         * @return A result code indicating how the event was handled.
3806         */
3807        protected int onProcess(QueuedInputEvent q) {
3808            return FORWARD;
3809        }
3810
3811        /**
3812         * Called when an event is being delivered to the next stage.
3813         */
3814        protected void onDeliverToNext(QueuedInputEvent q) {
3815            if (DEBUG_INPUT_STAGES) {
3816                Log.v(mTag, "Done with " + getClass().getSimpleName() + ". " + q);
3817            }
3818            if (mNext != null) {
3819                mNext.deliver(q);
3820            } else {
3821                finishInputEvent(q);
3822            }
3823        }
3824
3825        protected boolean shouldDropInputEvent(QueuedInputEvent q) {
3826            if (mView == null || !mAdded) {
3827                Slog.w(mTag, "Dropping event due to root view being removed: " + q.mEvent);
3828                return true;
3829            } else if ((!mAttachInfo.mHasWindowFocus
3830                    && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) || mStopped
3831                    || (mIsAmbientMode && !q.mEvent.isFromSource(InputDevice.SOURCE_CLASS_BUTTON))
3832                    || (mPausedForTransition && !isBack(q.mEvent))) {
3833                // This is a focus event and the window doesn't currently have input focus or
3834                // has stopped. This could be an event that came back from the previous stage
3835                // but the window has lost focus or stopped in the meantime.
3836                if (isTerminalInputEvent(q.mEvent)) {
3837                    // Don't drop terminal input events, however mark them as canceled.
3838                    q.mEvent.cancel();
3839                    Slog.w(mTag, "Cancelling event due to no window focus: " + q.mEvent);
3840                    return false;
3841                }
3842
3843                // Drop non-terminal input events.
3844                Slog.w(mTag, "Dropping event due to no window focus: " + q.mEvent);
3845                return true;
3846            }
3847            return false;
3848        }
3849
3850        void dump(String prefix, PrintWriter writer) {
3851            if (mNext != null) {
3852                mNext.dump(prefix, writer);
3853            }
3854        }
3855
3856        private boolean isBack(InputEvent event) {
3857            if (event instanceof KeyEvent) {
3858                return ((KeyEvent) event).getKeyCode() == KeyEvent.KEYCODE_BACK;
3859            } else {
3860                return false;
3861            }
3862        }
3863    }
3864
3865    /**
3866     * Base class for implementing an input pipeline stage that supports
3867     * asynchronous and out-of-order processing of input events.
3868     * <p>
3869     * In addition to what a normal input stage can do, an asynchronous
3870     * input stage may also defer an input event that has been delivered to it
3871     * and finish or forward it later.
3872     * </p>
3873     */
3874    abstract class AsyncInputStage extends InputStage {
3875        private final String mTraceCounter;
3876
3877        private QueuedInputEvent mQueueHead;
3878        private QueuedInputEvent mQueueTail;
3879        private int mQueueLength;
3880
3881        protected static final int DEFER = 3;
3882
3883        /**
3884         * Creates an asynchronous input stage.
3885         * @param next The next stage to which events should be forwarded.
3886         * @param traceCounter The name of a counter to record the size of
3887         * the queue of pending events.
3888         */
3889        public AsyncInputStage(InputStage next, String traceCounter) {
3890            super(next);
3891            mTraceCounter = traceCounter;
3892        }
3893
3894        /**
3895         * Marks the event as deferred, which is to say that it will be handled
3896         * asynchronously.  The caller is responsible for calling {@link #forward}
3897         * or {@link #finish} later when it is done handling the event.
3898         */
3899        protected void defer(QueuedInputEvent q) {
3900            q.mFlags |= QueuedInputEvent.FLAG_DEFERRED;
3901            enqueue(q);
3902        }
3903
3904        @Override
3905        protected void forward(QueuedInputEvent q) {
3906            // Clear the deferred flag.
3907            q.mFlags &= ~QueuedInputEvent.FLAG_DEFERRED;
3908
3909            // Fast path if the queue is empty.
3910            QueuedInputEvent curr = mQueueHead;
3911            if (curr == null) {
3912                super.forward(q);
3913                return;
3914            }
3915
3916            // Determine whether the event must be serialized behind any others
3917            // before it can be delivered to the next stage.  This is done because
3918            // deferred events might be handled out of order by the stage.
3919            final int deviceId = q.mEvent.getDeviceId();
3920            QueuedInputEvent prev = null;
3921            boolean blocked = false;
3922            while (curr != null && curr != q) {
3923                if (!blocked && deviceId == curr.mEvent.getDeviceId()) {
3924                    blocked = true;
3925                }
3926                prev = curr;
3927                curr = curr.mNext;
3928            }
3929
3930            // If the event is blocked, then leave it in the queue to be delivered later.
3931            // Note that the event might not yet be in the queue if it was not previously
3932            // deferred so we will enqueue it if needed.
3933            if (blocked) {
3934                if (curr == null) {
3935                    enqueue(q);
3936                }
3937                return;
3938            }
3939
3940            // The event is not blocked.  Deliver it immediately.
3941            if (curr != null) {
3942                curr = curr.mNext;
3943                dequeue(q, prev);
3944            }
3945            super.forward(q);
3946
3947            // Dequeuing this event may have unblocked successors.  Deliver them.
3948            while (curr != null) {
3949                if (deviceId == curr.mEvent.getDeviceId()) {
3950                    if ((curr.mFlags & QueuedInputEvent.FLAG_DEFERRED) != 0) {
3951                        break;
3952                    }
3953                    QueuedInputEvent next = curr.mNext;
3954                    dequeue(curr, prev);
3955                    super.forward(curr);
3956                    curr = next;
3957                } else {
3958                    prev = curr;
3959                    curr = curr.mNext;
3960                }
3961            }
3962        }
3963
3964        @Override
3965        protected void apply(QueuedInputEvent q, int result) {
3966            if (result == DEFER) {
3967                defer(q);
3968            } else {
3969                super.apply(q, result);
3970            }
3971        }
3972
3973        private void enqueue(QueuedInputEvent q) {
3974            if (mQueueTail == null) {
3975                mQueueHead = q;
3976                mQueueTail = q;
3977            } else {
3978                mQueueTail.mNext = q;
3979                mQueueTail = q;
3980            }
3981
3982            mQueueLength += 1;
3983            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3984        }
3985
3986        private void dequeue(QueuedInputEvent q, QueuedInputEvent prev) {
3987            if (prev == null) {
3988                mQueueHead = q.mNext;
3989            } else {
3990                prev.mNext = q.mNext;
3991            }
3992            if (mQueueTail == q) {
3993                mQueueTail = prev;
3994            }
3995            q.mNext = null;
3996
3997            mQueueLength -= 1;
3998            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mTraceCounter, mQueueLength);
3999        }
4000
4001        @Override
4002        void dump(String prefix, PrintWriter writer) {
4003            writer.print(prefix);
4004            writer.print(getClass().getName());
4005            writer.print(": mQueueLength=");
4006            writer.println(mQueueLength);
4007
4008            super.dump(prefix, writer);
4009        }
4010    }
4011
4012    /**
4013     * Delivers pre-ime input events to a native activity.
4014     * Does not support pointer events.
4015     */
4016    final class NativePreImeInputStage extends AsyncInputStage
4017            implements InputQueue.FinishedInputEventCallback {
4018        public NativePreImeInputStage(InputStage next, String traceCounter) {
4019            super(next, traceCounter);
4020        }
4021
4022        @Override
4023        protected int onProcess(QueuedInputEvent q) {
4024            if (mInputQueue != null && q.mEvent instanceof KeyEvent) {
4025                mInputQueue.sendInputEvent(q.mEvent, q, true, this);
4026                return DEFER;
4027            }
4028            return FORWARD;
4029        }
4030
4031        @Override
4032        public void onFinishedInputEvent(Object token, boolean handled) {
4033            QueuedInputEvent q = (QueuedInputEvent)token;
4034            if (handled) {
4035                finish(q, true);
4036                return;
4037            }
4038            forward(q);
4039        }
4040    }
4041
4042    /**
4043     * Delivers pre-ime input events to the view hierarchy.
4044     * Does not support pointer events.
4045     */
4046    final class ViewPreImeInputStage extends InputStage {
4047        public ViewPreImeInputStage(InputStage next) {
4048            super(next);
4049        }
4050
4051        @Override
4052        protected int onProcess(QueuedInputEvent q) {
4053            if (q.mEvent instanceof KeyEvent) {
4054                return processKeyEvent(q);
4055            }
4056            return FORWARD;
4057        }
4058
4059        private int processKeyEvent(QueuedInputEvent q) {
4060            final KeyEvent event = (KeyEvent)q.mEvent;
4061            if (mView.dispatchKeyEventPreIme(event)) {
4062                return FINISH_HANDLED;
4063            }
4064            return FORWARD;
4065        }
4066    }
4067
4068    /**
4069     * Delivers input events to the ime.
4070     * Does not support pointer events.
4071     */
4072    final class ImeInputStage extends AsyncInputStage
4073            implements InputMethodManager.FinishedInputEventCallback {
4074        public ImeInputStage(InputStage next, String traceCounter) {
4075            super(next, traceCounter);
4076        }
4077
4078        @Override
4079        protected int onProcess(QueuedInputEvent q) {
4080            if (mLastWasImTarget && !isInLocalFocusMode()) {
4081                InputMethodManager imm = InputMethodManager.peekInstance();
4082                if (imm != null) {
4083                    final InputEvent event = q.mEvent;
4084                    if (DEBUG_IMF) Log.v(mTag, "Sending input event to IME: " + event);
4085                    int result = imm.dispatchInputEvent(event, q, this, mHandler);
4086                    if (result == InputMethodManager.DISPATCH_HANDLED) {
4087                        return FINISH_HANDLED;
4088                    } else if (result == InputMethodManager.DISPATCH_NOT_HANDLED) {
4089                        // The IME could not handle it, so skip along to the next InputStage
4090                        return FORWARD;
4091                    } else {
4092                        return DEFER; // callback will be invoked later
4093                    }
4094                }
4095            }
4096            return FORWARD;
4097        }
4098
4099        @Override
4100        public void onFinishedInputEvent(Object token, boolean handled) {
4101            QueuedInputEvent q = (QueuedInputEvent)token;
4102            if (handled) {
4103                finish(q, true);
4104                return;
4105            }
4106            forward(q);
4107        }
4108    }
4109
4110    /**
4111     * Performs early processing of post-ime input events.
4112     */
4113    final class EarlyPostImeInputStage extends InputStage {
4114        public EarlyPostImeInputStage(InputStage next) {
4115            super(next);
4116        }
4117
4118        @Override
4119        protected int onProcess(QueuedInputEvent q) {
4120            if (q.mEvent instanceof KeyEvent) {
4121                return processKeyEvent(q);
4122            } else {
4123                final int source = q.mEvent.getSource();
4124                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4125                    return processPointerEvent(q);
4126                }
4127            }
4128            return FORWARD;
4129        }
4130
4131        private int processKeyEvent(QueuedInputEvent q) {
4132            final KeyEvent event = (KeyEvent)q.mEvent;
4133
4134            // If the key's purpose is to exit touch mode then we consume it
4135            // and consider it handled.
4136            if (checkForLeavingTouchModeAndConsume(event)) {
4137                return FINISH_HANDLED;
4138            }
4139
4140            // Make sure the fallback event policy sees all keys that will be
4141            // delivered to the view hierarchy.
4142            mFallbackEventHandler.preDispatchKeyEvent(event);
4143            return FORWARD;
4144        }
4145
4146        private int processPointerEvent(QueuedInputEvent q) {
4147            final MotionEvent event = (MotionEvent)q.mEvent;
4148
4149            // Translate the pointer event for compatibility, if needed.
4150            if (mTranslator != null) {
4151                mTranslator.translateEventInScreenToAppWindow(event);
4152            }
4153
4154            // Enter touch mode on down or scroll.
4155            final int action = event.getAction();
4156            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_SCROLL) {
4157                ensureTouchMode(true);
4158            }
4159
4160            // Offset the scroll position.
4161            if (mCurScrollY != 0) {
4162                event.offsetLocation(0, mCurScrollY);
4163            }
4164
4165            // Remember the touch position for possible drag-initiation.
4166            if (event.isTouchEvent()) {
4167                mLastTouchPoint.x = event.getRawX();
4168                mLastTouchPoint.y = event.getRawY();
4169                mLastTouchSource = event.getSource();
4170            }
4171            return FORWARD;
4172        }
4173    }
4174
4175    /**
4176     * Delivers post-ime input events to a native activity.
4177     */
4178    final class NativePostImeInputStage extends AsyncInputStage
4179            implements InputQueue.FinishedInputEventCallback {
4180        public NativePostImeInputStage(InputStage next, String traceCounter) {
4181            super(next, traceCounter);
4182        }
4183
4184        @Override
4185        protected int onProcess(QueuedInputEvent q) {
4186            if (mInputQueue != null) {
4187                mInputQueue.sendInputEvent(q.mEvent, q, false, this);
4188                return DEFER;
4189            }
4190            return FORWARD;
4191        }
4192
4193        @Override
4194        public void onFinishedInputEvent(Object token, boolean handled) {
4195            QueuedInputEvent q = (QueuedInputEvent)token;
4196            if (handled) {
4197                finish(q, true);
4198                return;
4199            }
4200            forward(q);
4201        }
4202    }
4203
4204    /**
4205     * Delivers post-ime input events to the view hierarchy.
4206     */
4207    final class ViewPostImeInputStage extends InputStage {
4208        public ViewPostImeInputStage(InputStage next) {
4209            super(next);
4210        }
4211
4212        @Override
4213        protected int onProcess(QueuedInputEvent q) {
4214            if (q.mEvent instanceof KeyEvent) {
4215                return processKeyEvent(q);
4216            } else {
4217                final int source = q.mEvent.getSource();
4218                if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
4219                    return processPointerEvent(q);
4220                } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4221                    return processTrackballEvent(q);
4222                } else {
4223                    return processGenericMotionEvent(q);
4224                }
4225            }
4226        }
4227
4228        @Override
4229        protected void onDeliverToNext(QueuedInputEvent q) {
4230            if (mUnbufferedInputDispatch
4231                    && q.mEvent instanceof MotionEvent
4232                    && ((MotionEvent)q.mEvent).isTouchEvent()
4233                    && isTerminalInputEvent(q.mEvent)) {
4234                mUnbufferedInputDispatch = false;
4235                scheduleConsumeBatchedInput();
4236            }
4237            super.onDeliverToNext(q);
4238        }
4239
4240        private int processKeyEvent(QueuedInputEvent q) {
4241            final KeyEvent event = (KeyEvent)q.mEvent;
4242
4243            // Deliver the key to the view hierarchy.
4244            if (mView.dispatchKeyEvent(event)) {
4245                return FINISH_HANDLED;
4246            }
4247
4248            if (shouldDropInputEvent(q)) {
4249                return FINISH_NOT_HANDLED;
4250            }
4251
4252            // If the Control modifier is held, try to interpret the key as a shortcut.
4253            if (event.getAction() == KeyEvent.ACTION_DOWN
4254                    && event.isCtrlPressed()
4255                    && event.getRepeatCount() == 0
4256                    && !KeyEvent.isModifierKey(event.getKeyCode())) {
4257                if (mView.dispatchKeyShortcutEvent(event)) {
4258                    return FINISH_HANDLED;
4259                }
4260                if (shouldDropInputEvent(q)) {
4261                    return FINISH_NOT_HANDLED;
4262                }
4263            }
4264
4265            // Apply the fallback event policy.
4266            if (mFallbackEventHandler.dispatchKeyEvent(event)) {
4267                return FINISH_HANDLED;
4268            }
4269            if (shouldDropInputEvent(q)) {
4270                return FINISH_NOT_HANDLED;
4271            }
4272
4273            // Handle automatic focus changes.
4274            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4275                int direction = 0;
4276                switch (event.getKeyCode()) {
4277                    case KeyEvent.KEYCODE_DPAD_LEFT:
4278                        if (event.hasNoModifiers()) {
4279                            direction = View.FOCUS_LEFT;
4280                        }
4281                        break;
4282                    case KeyEvent.KEYCODE_DPAD_RIGHT:
4283                        if (event.hasNoModifiers()) {
4284                            direction = View.FOCUS_RIGHT;
4285                        }
4286                        break;
4287                    case KeyEvent.KEYCODE_DPAD_UP:
4288                        if (event.hasNoModifiers()) {
4289                            direction = View.FOCUS_UP;
4290                        }
4291                        break;
4292                    case KeyEvent.KEYCODE_DPAD_DOWN:
4293                        if (event.hasNoModifiers()) {
4294                            direction = View.FOCUS_DOWN;
4295                        }
4296                        break;
4297                    case KeyEvent.KEYCODE_TAB:
4298                        if (event.hasNoModifiers()) {
4299                            direction = View.FOCUS_FORWARD;
4300                        } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
4301                            direction = View.FOCUS_BACKWARD;
4302                        }
4303                        break;
4304                }
4305                if (direction != 0) {
4306                    View focused = mView.findFocus();
4307                    if (focused != null) {
4308                        View v = focused.focusSearch(direction);
4309                        if (v != null && v != focused) {
4310                            // do the math the get the interesting rect
4311                            // of previous focused into the coord system of
4312                            // newly focused view
4313                            focused.getFocusedRect(mTempRect);
4314                            if (mView instanceof ViewGroup) {
4315                                ((ViewGroup) mView).offsetDescendantRectToMyCoords(
4316                                        focused, mTempRect);
4317                                ((ViewGroup) mView).offsetRectIntoDescendantCoords(
4318                                        v, mTempRect);
4319                            }
4320                            if (v.requestFocus(direction, mTempRect)) {
4321                                playSoundEffect(SoundEffectConstants
4322                                        .getContantForFocusDirection(direction));
4323                                return FINISH_HANDLED;
4324                            }
4325                        }
4326
4327                        // Give the focused view a last chance to handle the dpad key.
4328                        if (mView.dispatchUnhandledMove(focused, direction)) {
4329                            return FINISH_HANDLED;
4330                        }
4331                    } else {
4332                        // find the best view to give focus to in this non-touch-mode with no-focus
4333                        View v = focusSearch(null, direction);
4334                        if (v != null && v.requestFocus(direction)) {
4335                            return FINISH_HANDLED;
4336                        }
4337                    }
4338                }
4339            }
4340            return FORWARD;
4341        }
4342
4343        private int processPointerEvent(QueuedInputEvent q) {
4344            final MotionEvent event = (MotionEvent)q.mEvent;
4345
4346            mAttachInfo.mUnbufferedDispatchRequested = false;
4347            final View eventTarget =
4348                    (event.isFromSource(InputDevice.SOURCE_MOUSE) && mCapturingView != null) ?
4349                            mCapturingView : mView;
4350            mAttachInfo.mHandlingPointerEvent = true;
4351            boolean handled = eventTarget.dispatchPointerEvent(event);
4352            maybeUpdatePointerIcon(event);
4353            mAttachInfo.mHandlingPointerEvent = false;
4354            if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
4355                mUnbufferedInputDispatch = true;
4356                if (mConsumeBatchedInputScheduled) {
4357                    scheduleConsumeBatchedInputImmediately();
4358                }
4359            }
4360            return handled ? FINISH_HANDLED : FORWARD;
4361        }
4362
4363        private void maybeUpdatePointerIcon(MotionEvent event) {
4364            if (event.getPointerCount() == 1
4365                    && event.isFromSource(InputDevice.SOURCE_MOUSE)) {
4366                if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
4367                        || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
4368                    // Other apps or the window manager may change the icon shape outside of
4369                    // this app, therefore the icon shape has to be reset on enter/exit event.
4370                    mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4371                }
4372
4373                if (event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
4374                    if (!updatePointerIcon(event) &&
4375                            event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE) {
4376                        mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4377                    }
4378                }
4379            }
4380        }
4381
4382        private int processTrackballEvent(QueuedInputEvent q) {
4383            final MotionEvent event = (MotionEvent)q.mEvent;
4384
4385            if (mView.dispatchTrackballEvent(event)) {
4386                return FINISH_HANDLED;
4387            }
4388            return FORWARD;
4389        }
4390
4391        private int processGenericMotionEvent(QueuedInputEvent q) {
4392            final MotionEvent event = (MotionEvent)q.mEvent;
4393
4394            // Deliver the event to the view.
4395            if (mView.dispatchGenericMotionEvent(event)) {
4396                return FINISH_HANDLED;
4397            }
4398            return FORWARD;
4399        }
4400    }
4401
4402    private void resetPointerIcon(MotionEvent event) {
4403        mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4404        updatePointerIcon(event);
4405    }
4406
4407    private boolean updatePointerIcon(MotionEvent event) {
4408        final float x = event.getX();
4409        final float y = event.getY();
4410        if (mView == null) {
4411            // E.g. click outside a popup to dismiss it
4412            Slog.d(mTag, "updatePointerIcon called after view was removed");
4413            return false;
4414        }
4415        if (x < 0 || x >= mView.getWidth() || y < 0 || y >= mView.getHeight()) {
4416            // E.g. when moving window divider with mouse
4417            Slog.d(mTag, "updatePointerIcon called with position out of bounds");
4418            return false;
4419        }
4420        final PointerIcon pointerIcon = mView.getPointerIcon(event, x, y);
4421        final int pointerShape = (pointerIcon != null) ?
4422                pointerIcon.getStyle() : PointerIcon.STYLE_DEFAULT;
4423
4424        if (mPointerIconShape != pointerShape) {
4425            mPointerIconShape = pointerShape;
4426            if (mPointerIconShape != PointerIcon.STYLE_CUSTOM) {
4427                mCustomPointerIcon = null;
4428                InputManager.getInstance().setPointerIconShape(pointerShape);
4429                return true;
4430            }
4431        }
4432        if (mPointerIconShape == PointerIcon.STYLE_CUSTOM &&
4433                !pointerIcon.equals(mCustomPointerIcon)) {
4434            mCustomPointerIcon = pointerIcon;
4435            InputManager.getInstance().setCustomPointerIcon(mCustomPointerIcon);
4436        }
4437        return true;
4438    }
4439
4440    /**
4441     * Performs synthesis of new input events from unhandled input events.
4442     */
4443    final class SyntheticInputStage extends InputStage {
4444        private final SyntheticTrackballHandler mTrackball = new SyntheticTrackballHandler();
4445        private final SyntheticJoystickHandler mJoystick = new SyntheticJoystickHandler();
4446        private final SyntheticTouchNavigationHandler mTouchNavigation =
4447                new SyntheticTouchNavigationHandler();
4448        private final SyntheticKeyboardHandler mKeyboard = new SyntheticKeyboardHandler();
4449
4450        public SyntheticInputStage() {
4451            super(null);
4452        }
4453
4454        @Override
4455        protected int onProcess(QueuedInputEvent q) {
4456            q.mFlags |= QueuedInputEvent.FLAG_RESYNTHESIZED;
4457            if (q.mEvent instanceof MotionEvent) {
4458                final MotionEvent event = (MotionEvent)q.mEvent;
4459                final int source = event.getSource();
4460                if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4461                    mTrackball.process(event);
4462                    return FINISH_HANDLED;
4463                } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4464                    mJoystick.process(event);
4465                    return FINISH_HANDLED;
4466                } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4467                        == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4468                    mTouchNavigation.process(event);
4469                    return FINISH_HANDLED;
4470                }
4471            } else if ((q.mFlags & QueuedInputEvent.FLAG_UNHANDLED) != 0) {
4472                mKeyboard.process((KeyEvent)q.mEvent);
4473                return FINISH_HANDLED;
4474            }
4475
4476            return FORWARD;
4477        }
4478
4479        @Override
4480        protected void onDeliverToNext(QueuedInputEvent q) {
4481            if ((q.mFlags & QueuedInputEvent.FLAG_RESYNTHESIZED) == 0) {
4482                // Cancel related synthetic events if any prior stage has handled the event.
4483                if (q.mEvent instanceof MotionEvent) {
4484                    final MotionEvent event = (MotionEvent)q.mEvent;
4485                    final int source = event.getSource();
4486                    if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
4487                        mTrackball.cancel(event);
4488                    } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
4489                        mJoystick.cancel(event);
4490                    } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION)
4491                            == InputDevice.SOURCE_TOUCH_NAVIGATION) {
4492                        mTouchNavigation.cancel(event);
4493                    }
4494                }
4495            }
4496            super.onDeliverToNext(q);
4497        }
4498    }
4499
4500    /**
4501     * Creates dpad events from unhandled trackball movements.
4502     */
4503    final class SyntheticTrackballHandler {
4504        private final TrackballAxis mX = new TrackballAxis();
4505        private final TrackballAxis mY = new TrackballAxis();
4506        private long mLastTime;
4507
4508        public void process(MotionEvent event) {
4509            // Translate the trackball event into DPAD keys and try to deliver those.
4510            long curTime = SystemClock.uptimeMillis();
4511            if ((mLastTime + MAX_TRACKBALL_DELAY) < curTime) {
4512                // It has been too long since the last movement,
4513                // so restart at the beginning.
4514                mX.reset(0);
4515                mY.reset(0);
4516                mLastTime = curTime;
4517            }
4518
4519            final int action = event.getAction();
4520            final int metaState = event.getMetaState();
4521            switch (action) {
4522                case MotionEvent.ACTION_DOWN:
4523                    mX.reset(2);
4524                    mY.reset(2);
4525                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4526                            KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4527                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4528                            InputDevice.SOURCE_KEYBOARD));
4529                    break;
4530                case MotionEvent.ACTION_UP:
4531                    mX.reset(2);
4532                    mY.reset(2);
4533                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4534                            KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER, 0, metaState,
4535                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4536                            InputDevice.SOURCE_KEYBOARD));
4537                    break;
4538            }
4539
4540            if (DEBUG_TRACKBALL) Log.v(mTag, "TB X=" + mX.position + " step="
4541                    + mX.step + " dir=" + mX.dir + " acc=" + mX.acceleration
4542                    + " move=" + event.getX()
4543                    + " / Y=" + mY.position + " step="
4544                    + mY.step + " dir=" + mY.dir + " acc=" + mY.acceleration
4545                    + " move=" + event.getY());
4546            final float xOff = mX.collect(event.getX(), event.getEventTime(), "X");
4547            final float yOff = mY.collect(event.getY(), event.getEventTime(), "Y");
4548
4549            // Generate DPAD events based on the trackball movement.
4550            // We pick the axis that has moved the most as the direction of
4551            // the DPAD.  When we generate DPAD events for one axis, then the
4552            // other axis is reset -- we don't want to perform DPAD jumps due
4553            // to slight movements in the trackball when making major movements
4554            // along the other axis.
4555            int keycode = 0;
4556            int movement = 0;
4557            float accel = 1;
4558            if (xOff > yOff) {
4559                movement = mX.generate();
4560                if (movement != 0) {
4561                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT
4562                            : KeyEvent.KEYCODE_DPAD_LEFT;
4563                    accel = mX.acceleration;
4564                    mY.reset(2);
4565                }
4566            } else if (yOff > 0) {
4567                movement = mY.generate();
4568                if (movement != 0) {
4569                    keycode = movement > 0 ? KeyEvent.KEYCODE_DPAD_DOWN
4570                            : KeyEvent.KEYCODE_DPAD_UP;
4571                    accel = mY.acceleration;
4572                    mX.reset(2);
4573                }
4574            }
4575
4576            if (keycode != 0) {
4577                if (movement < 0) movement = -movement;
4578                int accelMovement = (int)(movement * accel);
4579                if (DEBUG_TRACKBALL) Log.v(mTag, "Move: movement=" + movement
4580                        + " accelMovement=" + accelMovement
4581                        + " accel=" + accel);
4582                if (accelMovement > movement) {
4583                    if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
4584                            + keycode);
4585                    movement--;
4586                    int repeatCount = accelMovement - movement;
4587                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4588                            KeyEvent.ACTION_MULTIPLE, keycode, repeatCount, metaState,
4589                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4590                            InputDevice.SOURCE_KEYBOARD));
4591                }
4592                while (movement > 0) {
4593                    if (DEBUG_TRACKBALL) Log.v(mTag, "Delivering fake DPAD: "
4594                            + keycode);
4595                    movement--;
4596                    curTime = SystemClock.uptimeMillis();
4597                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4598                            KeyEvent.ACTION_DOWN, keycode, 0, metaState,
4599                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4600                            InputDevice.SOURCE_KEYBOARD));
4601                    enqueueInputEvent(new KeyEvent(curTime, curTime,
4602                            KeyEvent.ACTION_UP, keycode, 0, metaState,
4603                            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FALLBACK,
4604                            InputDevice.SOURCE_KEYBOARD));
4605                }
4606                mLastTime = curTime;
4607            }
4608        }
4609
4610        public void cancel(MotionEvent event) {
4611            mLastTime = Integer.MIN_VALUE;
4612
4613            // If we reach this, we consumed a trackball event.
4614            // Because we will not translate the trackball event into a key event,
4615            // touch mode will not exit, so we exit touch mode here.
4616            if (mView != null && mAdded) {
4617                ensureTouchMode(false);
4618            }
4619        }
4620    }
4621
4622    /**
4623     * Maintains state information for a single trackball axis, generating
4624     * discrete (DPAD) movements based on raw trackball motion.
4625     */
4626    static final class TrackballAxis {
4627        /**
4628         * The maximum amount of acceleration we will apply.
4629         */
4630        static final float MAX_ACCELERATION = 20;
4631
4632        /**
4633         * The maximum amount of time (in milliseconds) between events in order
4634         * for us to consider the user to be doing fast trackball movements,
4635         * and thus apply an acceleration.
4636         */
4637        static final long FAST_MOVE_TIME = 150;
4638
4639        /**
4640         * Scaling factor to the time (in milliseconds) between events to how
4641         * much to multiple/divide the current acceleration.  When movement
4642         * is < FAST_MOVE_TIME this multiplies the acceleration; when >
4643         * FAST_MOVE_TIME it divides it.
4644         */
4645        static final float ACCEL_MOVE_SCALING_FACTOR = (1.0f/40);
4646
4647        static final float FIRST_MOVEMENT_THRESHOLD = 0.5f;
4648        static final float SECOND_CUMULATIVE_MOVEMENT_THRESHOLD = 2.0f;
4649        static final float SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD = 1.0f;
4650
4651        float position;
4652        float acceleration = 1;
4653        long lastMoveTime = 0;
4654        int step;
4655        int dir;
4656        int nonAccelMovement;
4657
4658        void reset(int _step) {
4659            position = 0;
4660            acceleration = 1;
4661            lastMoveTime = 0;
4662            step = _step;
4663            dir = 0;
4664        }
4665
4666        /**
4667         * Add trackball movement into the state.  If the direction of movement
4668         * has been reversed, the state is reset before adding the
4669         * movement (so that you don't have to compensate for any previously
4670         * collected movement before see the result of the movement in the
4671         * new direction).
4672         *
4673         * @return Returns the absolute value of the amount of movement
4674         * collected so far.
4675         */
4676        float collect(float off, long time, String axis) {
4677            long normTime;
4678            if (off > 0) {
4679                normTime = (long)(off * FAST_MOVE_TIME);
4680                if (dir < 0) {
4681                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to positive!");
4682                    position = 0;
4683                    step = 0;
4684                    acceleration = 1;
4685                    lastMoveTime = 0;
4686                }
4687                dir = 1;
4688            } else if (off < 0) {
4689                normTime = (long)((-off) * FAST_MOVE_TIME);
4690                if (dir > 0) {
4691                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " reversed to negative!");
4692                    position = 0;
4693                    step = 0;
4694                    acceleration = 1;
4695                    lastMoveTime = 0;
4696                }
4697                dir = -1;
4698            } else {
4699                normTime = 0;
4700            }
4701
4702            // The number of milliseconds between each movement that is
4703            // considered "normal" and will not result in any acceleration
4704            // or deceleration, scaled by the offset we have here.
4705            if (normTime > 0) {
4706                long delta = time - lastMoveTime;
4707                lastMoveTime = time;
4708                float acc = acceleration;
4709                if (delta < normTime) {
4710                    // The user is scrolling rapidly, so increase acceleration.
4711                    float scale = (normTime-delta) * ACCEL_MOVE_SCALING_FACTOR;
4712                    if (scale > 1) acc *= scale;
4713                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " accelerate: off="
4714                            + off + " normTime=" + normTime + " delta=" + delta
4715                            + " scale=" + scale + " acc=" + acc);
4716                    acceleration = acc < MAX_ACCELERATION ? acc : MAX_ACCELERATION;
4717                } else {
4718                    // The user is scrolling slowly, so decrease acceleration.
4719                    float scale = (delta-normTime) * ACCEL_MOVE_SCALING_FACTOR;
4720                    if (scale > 1) acc /= scale;
4721                    if (DEBUG_TRACKBALL) Log.v(TAG, axis + " deccelerate: off="
4722                            + off + " normTime=" + normTime + " delta=" + delta
4723                            + " scale=" + scale + " acc=" + acc);
4724                    acceleration = acc > 1 ? acc : 1;
4725                }
4726            }
4727            position += off;
4728            return Math.abs(position);
4729        }
4730
4731        /**
4732         * Generate the number of discrete movement events appropriate for
4733         * the currently collected trackball movement.
4734         *
4735         * @return Returns the number of discrete movements, either positive
4736         * or negative, or 0 if there is not enough trackball movement yet
4737         * for a discrete movement.
4738         */
4739        int generate() {
4740            int movement = 0;
4741            nonAccelMovement = 0;
4742            do {
4743                final int dir = position >= 0 ? 1 : -1;
4744                switch (step) {
4745                    // If we are going to execute the first step, then we want
4746                    // to do this as soon as possible instead of waiting for
4747                    // a full movement, in order to make things look responsive.
4748                    case 0:
4749                        if (Math.abs(position) < FIRST_MOVEMENT_THRESHOLD) {
4750                            return movement;
4751                        }
4752                        movement += dir;
4753                        nonAccelMovement += dir;
4754                        step = 1;
4755                        break;
4756                    // If we have generated the first movement, then we need
4757                    // to wait for the second complete trackball motion before
4758                    // generating the second discrete movement.
4759                    case 1:
4760                        if (Math.abs(position) < SECOND_CUMULATIVE_MOVEMENT_THRESHOLD) {
4761                            return movement;
4762                        }
4763                        movement += dir;
4764                        nonAccelMovement += dir;
4765                        position -= SECOND_CUMULATIVE_MOVEMENT_THRESHOLD * dir;
4766                        step = 2;
4767                        break;
4768                    // After the first two, we generate discrete movements
4769                    // consistently with the trackball, applying an acceleration
4770                    // if the trackball is moving quickly.  This is a simple
4771                    // acceleration on top of what we already compute based
4772                    // on how quickly the wheel is being turned, to apply
4773                    // a longer increasing acceleration to continuous movement
4774                    // in one direction.
4775                    default:
4776                        if (Math.abs(position) < SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD) {
4777                            return movement;
4778                        }
4779                        movement += dir;
4780                        position -= dir * SUBSEQUENT_INCREMENTAL_MOVEMENT_THRESHOLD;
4781                        float acc = acceleration;
4782                        acc *= 1.1f;
4783                        acceleration = acc < MAX_ACCELERATION ? acc : acceleration;
4784                        break;
4785                }
4786            } while (true);
4787        }
4788    }
4789
4790    /**
4791     * Creates dpad events from unhandled joystick movements.
4792     */
4793    final class SyntheticJoystickHandler extends Handler {
4794        private final static String TAG = "SyntheticJoystickHandler";
4795        private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1;
4796        private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2;
4797
4798        private int mLastXDirection;
4799        private int mLastYDirection;
4800        private int mLastXKeyCode;
4801        private int mLastYKeyCode;
4802
4803        public SyntheticJoystickHandler() {
4804            super(true);
4805        }
4806
4807        @Override
4808        public void handleMessage(Message msg) {
4809            switch (msg.what) {
4810                case MSG_ENQUEUE_X_AXIS_KEY_REPEAT:
4811                case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: {
4812                    KeyEvent oldEvent = (KeyEvent)msg.obj;
4813                    KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent,
4814                            SystemClock.uptimeMillis(),
4815                            oldEvent.getRepeatCount() + 1);
4816                    if (mAttachInfo.mHasWindowFocus) {
4817                        enqueueInputEvent(e);
4818                        Message m = obtainMessage(msg.what, e);
4819                        m.setAsynchronous(true);
4820                        sendMessageDelayed(m, ViewConfiguration.getKeyRepeatDelay());
4821                    }
4822                } break;
4823            }
4824        }
4825
4826        public void process(MotionEvent event) {
4827            switch(event.getActionMasked()) {
4828            case MotionEvent.ACTION_CANCEL:
4829                cancel(event);
4830                break;
4831            case MotionEvent.ACTION_MOVE:
4832                update(event, true);
4833                break;
4834            default:
4835                Log.w(mTag, "Unexpected action: " + event.getActionMasked());
4836            }
4837        }
4838
4839        private void cancel(MotionEvent event) {
4840            removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4841            removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4842            update(event, false);
4843        }
4844
4845        private void update(MotionEvent event, boolean synthesizeNewKeys) {
4846            final long time = event.getEventTime();
4847            final int metaState = event.getMetaState();
4848            final int deviceId = event.getDeviceId();
4849            final int source = event.getSource();
4850
4851            int xDirection = joystickAxisValueToDirection(
4852                    event.getAxisValue(MotionEvent.AXIS_HAT_X));
4853            if (xDirection == 0) {
4854                xDirection = joystickAxisValueToDirection(event.getX());
4855            }
4856
4857            int yDirection = joystickAxisValueToDirection(
4858                    event.getAxisValue(MotionEvent.AXIS_HAT_Y));
4859            if (yDirection == 0) {
4860                yDirection = joystickAxisValueToDirection(event.getY());
4861            }
4862
4863            if (xDirection != mLastXDirection) {
4864                if (mLastXKeyCode != 0) {
4865                    removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT);
4866                    enqueueInputEvent(new KeyEvent(time, time,
4867                            KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState,
4868                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4869                    mLastXKeyCode = 0;
4870                }
4871
4872                mLastXDirection = xDirection;
4873
4874                if (xDirection != 0 && synthesizeNewKeys) {
4875                    mLastXKeyCode = xDirection > 0
4876                            ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT;
4877                    final KeyEvent e = new KeyEvent(time, time,
4878                            KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState,
4879                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4880                    enqueueInputEvent(e);
4881                    Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
4882                    m.setAsynchronous(true);
4883                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4884                }
4885            }
4886
4887            if (yDirection != mLastYDirection) {
4888                if (mLastYKeyCode != 0) {
4889                    removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT);
4890                    enqueueInputEvent(new KeyEvent(time, time,
4891                            KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState,
4892                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source));
4893                    mLastYKeyCode = 0;
4894                }
4895
4896                mLastYDirection = yDirection;
4897
4898                if (yDirection != 0 && synthesizeNewKeys) {
4899                    mLastYKeyCode = yDirection > 0
4900                            ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP;
4901                    final KeyEvent e = new KeyEvent(time, time,
4902                            KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState,
4903                            deviceId, 0, KeyEvent.FLAG_FALLBACK, source);
4904                    enqueueInputEvent(e);
4905                    Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e);
4906                    m.setAsynchronous(true);
4907                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
4908                }
4909            }
4910        }
4911
4912        private int joystickAxisValueToDirection(float value) {
4913            if (value >= 0.5f) {
4914                return 1;
4915            } else if (value <= -0.5f) {
4916                return -1;
4917            } else {
4918                return 0;
4919            }
4920        }
4921    }
4922
4923    /**
4924     * Creates dpad events from unhandled touch navigation movements.
4925     */
4926    final class SyntheticTouchNavigationHandler extends Handler {
4927        private static final String LOCAL_TAG = "SyntheticTouchNavigationHandler";
4928        private static final boolean LOCAL_DEBUG = false;
4929
4930        // Assumed nominal width and height in millimeters of a touch navigation pad,
4931        // if no resolution information is available from the input system.
4932        private static final float DEFAULT_WIDTH_MILLIMETERS = 48;
4933        private static final float DEFAULT_HEIGHT_MILLIMETERS = 48;
4934
4935        /* TODO: These constants should eventually be moved to ViewConfiguration. */
4936
4937        // The nominal distance traveled to move by one unit.
4938        private static final int TICK_DISTANCE_MILLIMETERS = 12;
4939
4940        // Minimum and maximum fling velocity in ticks per second.
4941        // The minimum velocity should be set such that we perform enough ticks per
4942        // second that the fling appears to be fluid.  For example, if we set the minimum
4943        // to 2 ticks per second, then there may be up to half a second delay between the next
4944        // to last and last ticks which is noticeably discrete and jerky.  This value should
4945        // probably not be set to anything less than about 4.
4946        // If fling accuracy is a problem then consider tuning the tick distance instead.
4947        private static final float MIN_FLING_VELOCITY_TICKS_PER_SECOND = 6f;
4948        private static final float MAX_FLING_VELOCITY_TICKS_PER_SECOND = 20f;
4949
4950        // Fling velocity decay factor applied after each new key is emitted.
4951        // This parameter controls the deceleration and overall duration of the fling.
4952        // The fling stops automatically when its velocity drops below the minimum
4953        // fling velocity defined above.
4954        private static final float FLING_TICK_DECAY = 0.8f;
4955
4956        /* The input device that we are tracking. */
4957
4958        private int mCurrentDeviceId = -1;
4959        private int mCurrentSource;
4960        private boolean mCurrentDeviceSupported;
4961
4962        /* Configuration for the current input device. */
4963
4964        // The scaled tick distance.  A movement of this amount should generally translate
4965        // into a single dpad event in a given direction.
4966        private float mConfigTickDistance;
4967
4968        // The minimum and maximum scaled fling velocity.
4969        private float mConfigMinFlingVelocity;
4970        private float mConfigMaxFlingVelocity;
4971
4972        /* Tracking state. */
4973
4974        // The velocity tracker for detecting flings.
4975        private VelocityTracker mVelocityTracker;
4976
4977        // The active pointer id, or -1 if none.
4978        private int mActivePointerId = -1;
4979
4980        // Location where tracking started.
4981        private float mStartX;
4982        private float mStartY;
4983
4984        // Most recently observed position.
4985        private float mLastX;
4986        private float mLastY;
4987
4988        // Accumulated movement delta since the last direction key was sent.
4989        private float mAccumulatedX;
4990        private float mAccumulatedY;
4991
4992        // Set to true if any movement was delivered to the app.
4993        // Implies that tap slop was exceeded.
4994        private boolean mConsumedMovement;
4995
4996        // The most recently sent key down event.
4997        // The keycode remains set until the direction changes or a fling ends
4998        // so that repeated key events may be generated as required.
4999        private long mPendingKeyDownTime;
5000        private int mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
5001        private int mPendingKeyRepeatCount;
5002        private int mPendingKeyMetaState;
5003
5004        // The current fling velocity while a fling is in progress.
5005        private boolean mFlinging;
5006        private float mFlingVelocity;
5007
5008        public SyntheticTouchNavigationHandler() {
5009            super(true);
5010        }
5011
5012        public void process(MotionEvent event) {
5013            // Update the current device information.
5014            final long time = event.getEventTime();
5015            final int deviceId = event.getDeviceId();
5016            final int source = event.getSource();
5017            if (mCurrentDeviceId != deviceId || mCurrentSource != source) {
5018                finishKeys(time);
5019                finishTracking(time);
5020                mCurrentDeviceId = deviceId;
5021                mCurrentSource = source;
5022                mCurrentDeviceSupported = false;
5023                InputDevice device = event.getDevice();
5024                if (device != null) {
5025                    // In order to support an input device, we must know certain
5026                    // characteristics about it, such as its size and resolution.
5027                    InputDevice.MotionRange xRange = device.getMotionRange(MotionEvent.AXIS_X);
5028                    InputDevice.MotionRange yRange = device.getMotionRange(MotionEvent.AXIS_Y);
5029                    if (xRange != null && yRange != null) {
5030                        mCurrentDeviceSupported = true;
5031
5032                        // Infer the resolution if it not actually known.
5033                        float xRes = xRange.getResolution();
5034                        if (xRes <= 0) {
5035                            xRes = xRange.getRange() / DEFAULT_WIDTH_MILLIMETERS;
5036                        }
5037                        float yRes = yRange.getResolution();
5038                        if (yRes <= 0) {
5039                            yRes = yRange.getRange() / DEFAULT_HEIGHT_MILLIMETERS;
5040                        }
5041                        float nominalRes = (xRes + yRes) * 0.5f;
5042
5043                        // Precompute all of the configuration thresholds we will need.
5044                        mConfigTickDistance = TICK_DISTANCE_MILLIMETERS * nominalRes;
5045                        mConfigMinFlingVelocity =
5046                                MIN_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5047                        mConfigMaxFlingVelocity =
5048                                MAX_FLING_VELOCITY_TICKS_PER_SECOND * mConfigTickDistance;
5049
5050                        if (LOCAL_DEBUG) {
5051                            Log.d(LOCAL_TAG, "Configured device " + mCurrentDeviceId
5052                                    + " (" + Integer.toHexString(mCurrentSource) + "): "
5053                                    + ", mConfigTickDistance=" + mConfigTickDistance
5054                                    + ", mConfigMinFlingVelocity=" + mConfigMinFlingVelocity
5055                                    + ", mConfigMaxFlingVelocity=" + mConfigMaxFlingVelocity);
5056                        }
5057                    }
5058                }
5059            }
5060            if (!mCurrentDeviceSupported) {
5061                return;
5062            }
5063
5064            // Handle the event.
5065            final int action = event.getActionMasked();
5066            switch (action) {
5067                case MotionEvent.ACTION_DOWN: {
5068                    boolean caughtFling = mFlinging;
5069                    finishKeys(time);
5070                    finishTracking(time);
5071                    mActivePointerId = event.getPointerId(0);
5072                    mVelocityTracker = VelocityTracker.obtain();
5073                    mVelocityTracker.addMovement(event);
5074                    mStartX = event.getX();
5075                    mStartY = event.getY();
5076                    mLastX = mStartX;
5077                    mLastY = mStartY;
5078                    mAccumulatedX = 0;
5079                    mAccumulatedY = 0;
5080
5081                    // If we caught a fling, then pretend that the tap slop has already
5082                    // been exceeded to suppress taps whose only purpose is to stop the fling.
5083                    mConsumedMovement = caughtFling;
5084                    break;
5085                }
5086
5087                case MotionEvent.ACTION_MOVE:
5088                case MotionEvent.ACTION_UP: {
5089                    if (mActivePointerId < 0) {
5090                        break;
5091                    }
5092                    final int index = event.findPointerIndex(mActivePointerId);
5093                    if (index < 0) {
5094                        finishKeys(time);
5095                        finishTracking(time);
5096                        break;
5097                    }
5098
5099                    mVelocityTracker.addMovement(event);
5100                    final float x = event.getX(index);
5101                    final float y = event.getY(index);
5102                    mAccumulatedX += x - mLastX;
5103                    mAccumulatedY += y - mLastY;
5104                    mLastX = x;
5105                    mLastY = y;
5106
5107                    // Consume any accumulated movement so far.
5108                    final int metaState = event.getMetaState();
5109                    consumeAccumulatedMovement(time, metaState);
5110
5111                    // Detect taps and flings.
5112                    if (action == MotionEvent.ACTION_UP) {
5113                        if (mConsumedMovement && mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
5114                            // It might be a fling.
5115                            mVelocityTracker.computeCurrentVelocity(1000, mConfigMaxFlingVelocity);
5116                            final float vx = mVelocityTracker.getXVelocity(mActivePointerId);
5117                            final float vy = mVelocityTracker.getYVelocity(mActivePointerId);
5118                            if (!startFling(time, vx, vy)) {
5119                                finishKeys(time);
5120                            }
5121                        }
5122                        finishTracking(time);
5123                    }
5124                    break;
5125                }
5126
5127                case MotionEvent.ACTION_CANCEL: {
5128                    finishKeys(time);
5129                    finishTracking(time);
5130                    break;
5131                }
5132            }
5133        }
5134
5135        public void cancel(MotionEvent event) {
5136            if (mCurrentDeviceId == event.getDeviceId()
5137                    && mCurrentSource == event.getSource()) {
5138                final long time = event.getEventTime();
5139                finishKeys(time);
5140                finishTracking(time);
5141            }
5142        }
5143
5144        private void finishKeys(long time) {
5145            cancelFling();
5146            sendKeyUp(time);
5147        }
5148
5149        private void finishTracking(long time) {
5150            if (mActivePointerId >= 0) {
5151                mActivePointerId = -1;
5152                mVelocityTracker.recycle();
5153                mVelocityTracker = null;
5154            }
5155        }
5156
5157        private void consumeAccumulatedMovement(long time, int metaState) {
5158            final float absX = Math.abs(mAccumulatedX);
5159            final float absY = Math.abs(mAccumulatedY);
5160            if (absX >= absY) {
5161                if (absX >= mConfigTickDistance) {
5162                    mAccumulatedX = consumeAccumulatedMovement(time, metaState, mAccumulatedX,
5163                            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT);
5164                    mAccumulatedY = 0;
5165                    mConsumedMovement = true;
5166                }
5167            } else {
5168                if (absY >= mConfigTickDistance) {
5169                    mAccumulatedY = consumeAccumulatedMovement(time, metaState, mAccumulatedY,
5170                            KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN);
5171                    mAccumulatedX = 0;
5172                    mConsumedMovement = true;
5173                }
5174            }
5175        }
5176
5177        private float consumeAccumulatedMovement(long time, int metaState,
5178                float accumulator, int negativeKeyCode, int positiveKeyCode) {
5179            while (accumulator <= -mConfigTickDistance) {
5180                sendKeyDownOrRepeat(time, negativeKeyCode, metaState);
5181                accumulator += mConfigTickDistance;
5182            }
5183            while (accumulator >= mConfigTickDistance) {
5184                sendKeyDownOrRepeat(time, positiveKeyCode, metaState);
5185                accumulator -= mConfigTickDistance;
5186            }
5187            return accumulator;
5188        }
5189
5190        private void sendKeyDownOrRepeat(long time, int keyCode, int metaState) {
5191            if (mPendingKeyCode != keyCode) {
5192                sendKeyUp(time);
5193                mPendingKeyDownTime = time;
5194                mPendingKeyCode = keyCode;
5195                mPendingKeyRepeatCount = 0;
5196            } else {
5197                mPendingKeyRepeatCount += 1;
5198            }
5199            mPendingKeyMetaState = metaState;
5200
5201            // Note: Normally we would pass FLAG_LONG_PRESS when the repeat count is 1
5202            // but it doesn't quite make sense when simulating the events in this way.
5203            if (LOCAL_DEBUG) {
5204                Log.d(LOCAL_TAG, "Sending key down: keyCode=" + mPendingKeyCode
5205                        + ", repeatCount=" + mPendingKeyRepeatCount
5206                        + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5207            }
5208            enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5209                    KeyEvent.ACTION_DOWN, mPendingKeyCode, mPendingKeyRepeatCount,
5210                    mPendingKeyMetaState, mCurrentDeviceId,
5211                    KeyEvent.FLAG_FALLBACK, mCurrentSource));
5212        }
5213
5214        private void sendKeyUp(long time) {
5215            if (mPendingKeyCode != KeyEvent.KEYCODE_UNKNOWN) {
5216                if (LOCAL_DEBUG) {
5217                    Log.d(LOCAL_TAG, "Sending key up: keyCode=" + mPendingKeyCode
5218                            + ", metaState=" + Integer.toHexString(mPendingKeyMetaState));
5219                }
5220                enqueueInputEvent(new KeyEvent(mPendingKeyDownTime, time,
5221                        KeyEvent.ACTION_UP, mPendingKeyCode, 0, mPendingKeyMetaState,
5222                        mCurrentDeviceId, 0, KeyEvent.FLAG_FALLBACK,
5223                        mCurrentSource));
5224                mPendingKeyCode = KeyEvent.KEYCODE_UNKNOWN;
5225            }
5226        }
5227
5228        private boolean startFling(long time, float vx, float vy) {
5229            if (LOCAL_DEBUG) {
5230                Log.d(LOCAL_TAG, "Considering fling: vx=" + vx + ", vy=" + vy
5231                        + ", min=" + mConfigMinFlingVelocity);
5232            }
5233
5234            // Flings must be oriented in the same direction as the preceding movements.
5235            switch (mPendingKeyCode) {
5236                case KeyEvent.KEYCODE_DPAD_LEFT:
5237                    if (-vx >= mConfigMinFlingVelocity
5238                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5239                        mFlingVelocity = -vx;
5240                        break;
5241                    }
5242                    return false;
5243
5244                case KeyEvent.KEYCODE_DPAD_RIGHT:
5245                    if (vx >= mConfigMinFlingVelocity
5246                            && Math.abs(vy) < mConfigMinFlingVelocity) {
5247                        mFlingVelocity = vx;
5248                        break;
5249                    }
5250                    return false;
5251
5252                case KeyEvent.KEYCODE_DPAD_UP:
5253                    if (-vy >= mConfigMinFlingVelocity
5254                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5255                        mFlingVelocity = -vy;
5256                        break;
5257                    }
5258                    return false;
5259
5260                case KeyEvent.KEYCODE_DPAD_DOWN:
5261                    if (vy >= mConfigMinFlingVelocity
5262                            && Math.abs(vx) < mConfigMinFlingVelocity) {
5263                        mFlingVelocity = vy;
5264                        break;
5265                    }
5266                    return false;
5267            }
5268
5269            // Post the first fling event.
5270            mFlinging = postFling(time);
5271            return mFlinging;
5272        }
5273
5274        private boolean postFling(long time) {
5275            // The idea here is to estimate the time when the pointer would have
5276            // traveled one tick distance unit given the current fling velocity.
5277            // This effect creates continuity of motion.
5278            if (mFlingVelocity >= mConfigMinFlingVelocity) {
5279                long delay = (long)(mConfigTickDistance / mFlingVelocity * 1000);
5280                postAtTime(mFlingRunnable, time + delay);
5281                if (LOCAL_DEBUG) {
5282                    Log.d(LOCAL_TAG, "Posted fling: velocity="
5283                            + mFlingVelocity + ", delay=" + delay
5284                            + ", keyCode=" + mPendingKeyCode);
5285                }
5286                return true;
5287            }
5288            return false;
5289        }
5290
5291        private void cancelFling() {
5292            if (mFlinging) {
5293                removeCallbacks(mFlingRunnable);
5294                mFlinging = false;
5295            }
5296        }
5297
5298        private final Runnable mFlingRunnable = new Runnable() {
5299            @Override
5300            public void run() {
5301                final long time = SystemClock.uptimeMillis();
5302                sendKeyDownOrRepeat(time, mPendingKeyCode, mPendingKeyMetaState);
5303                mFlingVelocity *= FLING_TICK_DECAY;
5304                if (!postFling(time)) {
5305                    mFlinging = false;
5306                    finishKeys(time);
5307                }
5308            }
5309        };
5310    }
5311
5312    final class SyntheticKeyboardHandler {
5313        public void process(KeyEvent event) {
5314            if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) != 0) {
5315                return;
5316            }
5317
5318            final KeyCharacterMap kcm = event.getKeyCharacterMap();
5319            final int keyCode = event.getKeyCode();
5320            final int metaState = event.getMetaState();
5321
5322            // Check for fallback actions specified by the key character map.
5323            KeyCharacterMap.FallbackAction fallbackAction =
5324                    kcm.getFallbackAction(keyCode, metaState);
5325            if (fallbackAction != null) {
5326                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
5327                KeyEvent fallbackEvent = KeyEvent.obtain(
5328                        event.getDownTime(), event.getEventTime(),
5329                        event.getAction(), fallbackAction.keyCode,
5330                        event.getRepeatCount(), fallbackAction.metaState,
5331                        event.getDeviceId(), event.getScanCode(),
5332                        flags, event.getSource(), null);
5333                fallbackAction.recycle();
5334                enqueueInputEvent(fallbackEvent);
5335            }
5336        }
5337    }
5338
5339    /**
5340     * Returns true if the key is used for keyboard navigation.
5341     * @param keyEvent The key event.
5342     * @return True if the key is used for keyboard navigation.
5343     */
5344    private static boolean isNavigationKey(KeyEvent keyEvent) {
5345        switch (keyEvent.getKeyCode()) {
5346        case KeyEvent.KEYCODE_DPAD_LEFT:
5347        case KeyEvent.KEYCODE_DPAD_RIGHT:
5348        case KeyEvent.KEYCODE_DPAD_UP:
5349        case KeyEvent.KEYCODE_DPAD_DOWN:
5350        case KeyEvent.KEYCODE_DPAD_CENTER:
5351        case KeyEvent.KEYCODE_PAGE_UP:
5352        case KeyEvent.KEYCODE_PAGE_DOWN:
5353        case KeyEvent.KEYCODE_MOVE_HOME:
5354        case KeyEvent.KEYCODE_MOVE_END:
5355        case KeyEvent.KEYCODE_TAB:
5356        case KeyEvent.KEYCODE_SPACE:
5357        case KeyEvent.KEYCODE_ENTER:
5358            return true;
5359        }
5360        return false;
5361    }
5362
5363    /**
5364     * Returns true if the key is used for typing.
5365     * @param keyEvent The key event.
5366     * @return True if the key is used for typing.
5367     */
5368    private static boolean isTypingKey(KeyEvent keyEvent) {
5369        return keyEvent.getUnicodeChar() > 0;
5370    }
5371
5372    /**
5373     * See if the key event means we should leave touch mode (and leave touch mode if so).
5374     * @param event The key event.
5375     * @return Whether this key event should be consumed (meaning the act of
5376     *   leaving touch mode alone is considered the event).
5377     */
5378    private boolean checkForLeavingTouchModeAndConsume(KeyEvent event) {
5379        // Only relevant in touch mode.
5380        if (!mAttachInfo.mInTouchMode) {
5381            return false;
5382        }
5383
5384        // Only consider leaving touch mode on DOWN or MULTIPLE actions, never on UP.
5385        final int action = event.getAction();
5386        if (action != KeyEvent.ACTION_DOWN && action != KeyEvent.ACTION_MULTIPLE) {
5387            return false;
5388        }
5389
5390        // Don't leave touch mode if the IME told us not to.
5391        if ((event.getFlags() & KeyEvent.FLAG_KEEP_TOUCH_MODE) != 0) {
5392            return false;
5393        }
5394
5395        // If the key can be used for keyboard navigation then leave touch mode
5396        // and select a focused view if needed (in ensureTouchMode).
5397        // When a new focused view is selected, we consume the navigation key because
5398        // navigation doesn't make much sense unless a view already has focus so
5399        // the key's purpose is to set focus.
5400        if (isNavigationKey(event)) {
5401            return ensureTouchMode(false);
5402        }
5403
5404        // If the key can be used for typing then leave touch mode
5405        // and select a focused view if needed (in ensureTouchMode).
5406        // Always allow the view to process the typing key.
5407        if (isTypingKey(event)) {
5408            ensureTouchMode(false);
5409            return false;
5410        }
5411
5412        return false;
5413    }
5414
5415    /* drag/drop */
5416    void setLocalDragState(Object obj) {
5417        mLocalDragState = obj;
5418    }
5419
5420    private void handleDragEvent(DragEvent event) {
5421        // From the root, only drag start/end/location are dispatched.  entered/exited
5422        // are determined and dispatched by the viewgroup hierarchy, who then report
5423        // that back here for ultimate reporting back to the framework.
5424        if (mView != null && mAdded) {
5425            final int what = event.mAction;
5426
5427            if (what == DragEvent.ACTION_DRAG_EXITED) {
5428                // A direct EXITED event means that the window manager knows we've just crossed
5429                // a window boundary, so the current drag target within this one must have
5430                // just been exited.  Send it the usual notifications and then we're done
5431                // for now.
5432                mView.dispatchDragEvent(event);
5433            } else {
5434                // Cache the drag description when the operation starts, then fill it in
5435                // on subsequent calls as a convenience
5436                if (what == DragEvent.ACTION_DRAG_STARTED) {
5437                    mCurrentDragView = null;    // Start the current-recipient tracking
5438                    mDragDescription = event.mClipDescription;
5439                } else {
5440                    event.mClipDescription = mDragDescription;
5441                }
5442
5443                // For events with a [screen] location, translate into window coordinates
5444                if ((what == DragEvent.ACTION_DRAG_LOCATION) || (what == DragEvent.ACTION_DROP)) {
5445                    mDragPoint.set(event.mX, event.mY);
5446                    if (mTranslator != null) {
5447                        mTranslator.translatePointInScreenToAppWindow(mDragPoint);
5448                    }
5449
5450                    if (mCurScrollY != 0) {
5451                        mDragPoint.offset(0, mCurScrollY);
5452                    }
5453
5454                    event.mX = mDragPoint.x;
5455                    event.mY = mDragPoint.y;
5456                }
5457
5458                // Remember who the current drag target is pre-dispatch
5459                final View prevDragView = mCurrentDragView;
5460
5461                // Now dispatch the drag/drop event
5462                boolean result = mView.dispatchDragEvent(event);
5463
5464                // If we changed apparent drag target, tell the OS about it
5465                if (prevDragView != mCurrentDragView) {
5466                    try {
5467                        if (prevDragView != null) {
5468                            mWindowSession.dragRecipientExited(mWindow);
5469                        }
5470                        if (mCurrentDragView != null) {
5471                            mWindowSession.dragRecipientEntered(mWindow);
5472                        }
5473                    } catch (RemoteException e) {
5474                        Slog.e(mTag, "Unable to note drag target change");
5475                    }
5476                }
5477
5478                // Report the drop result when we're done
5479                if (what == DragEvent.ACTION_DROP) {
5480                    mDragDescription = null;
5481                    try {
5482                        Log.i(mTag, "Reporting drop result: " + result);
5483                        mWindowSession.reportDropResult(mWindow, result);
5484                    } catch (RemoteException e) {
5485                        Log.e(mTag, "Unable to report drop result");
5486                    }
5487                }
5488
5489                // When the drag operation ends, reset drag-related state
5490                if (what == DragEvent.ACTION_DRAG_ENDED) {
5491                    setLocalDragState(null);
5492                    mAttachInfo.mDragToken = null;
5493                    if (mAttachInfo.mDragSurface != null) {
5494                        mAttachInfo.mDragSurface.release();
5495                        mAttachInfo.mDragSurface = null;
5496                    }
5497                }
5498            }
5499        }
5500        event.recycle();
5501    }
5502
5503    public void handleDispatchSystemUiVisibilityChanged(SystemUiVisibilityInfo args) {
5504        if (mSeq != args.seq) {
5505            // The sequence has changed, so we need to update our value and make
5506            // sure to do a traversal afterward so the window manager is given our
5507            // most recent data.
5508            mSeq = args.seq;
5509            mAttachInfo.mForceReportNewAttributes = true;
5510            scheduleTraversals();
5511        }
5512        if (mView == null) return;
5513        if (args.localChanges != 0) {
5514            mView.updateLocalSystemUiVisibility(args.localValue, args.localChanges);
5515        }
5516
5517        int visibility = args.globalVisibility&View.SYSTEM_UI_CLEARABLE_FLAGS;
5518        if (visibility != mAttachInfo.mGlobalSystemUiVisibility) {
5519            mAttachInfo.mGlobalSystemUiVisibility = visibility;
5520            mView.dispatchSystemUiVisibilityChanged(visibility);
5521        }
5522    }
5523
5524    public void handleDispatchWindowShown() {
5525        mAttachInfo.mTreeObserver.dispatchOnWindowShown();
5526    }
5527
5528    public void handleRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
5529        Bundle data = new Bundle();
5530        ArrayList<KeyboardShortcutGroup> list = new ArrayList<>();
5531        if (mView != null) {
5532            mView.requestKeyboardShortcuts(list, deviceId);
5533        }
5534        data.putParcelableArrayList(WindowManager.PARCEL_KEY_SHORTCUTS_ARRAY, list);
5535        try {
5536            receiver.send(0, data);
5537        } catch (RemoteException e) {
5538        }
5539    }
5540
5541    public void getLastTouchPoint(Point outLocation) {
5542        outLocation.x = (int) mLastTouchPoint.x;
5543        outLocation.y = (int) mLastTouchPoint.y;
5544    }
5545
5546    public int getLastTouchSource() {
5547        return mLastTouchSource;
5548    }
5549
5550    public void setDragFocus(View newDragTarget) {
5551        if (mCurrentDragView != newDragTarget) {
5552            mCurrentDragView = newDragTarget;
5553        }
5554    }
5555
5556    private AudioManager getAudioManager() {
5557        if (mView == null) {
5558            throw new IllegalStateException("getAudioManager called when there is no mView");
5559        }
5560        if (mAudioManager == null) {
5561            mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
5562        }
5563        return mAudioManager;
5564    }
5565
5566    public AccessibilityInteractionController getAccessibilityInteractionController() {
5567        if (mView == null) {
5568            throw new IllegalStateException("getAccessibilityInteractionController"
5569                    + " called when there is no mView");
5570        }
5571        if (mAccessibilityInteractionController == null) {
5572            mAccessibilityInteractionController = new AccessibilityInteractionController(this);
5573        }
5574        return mAccessibilityInteractionController;
5575    }
5576
5577    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
5578            boolean insetsPending) throws RemoteException {
5579
5580        float appScale = mAttachInfo.mApplicationScale;
5581        boolean restore = false;
5582        if (params != null && mTranslator != null) {
5583            restore = true;
5584            params.backup();
5585            mTranslator.translateWindowLayout(params);
5586        }
5587        if (params != null) {
5588            if (DBG) Log.d(mTag, "WindowLayout in layoutWindow:" + params);
5589        }
5590        mPendingConfiguration.seq = 0;
5591        //Log.d(mTag, ">>>>>> CALLING relayout");
5592        if (params != null && mOrigWindowType != params.type) {
5593            // For compatibility with old apps, don't crash here.
5594            if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
5595                Slog.w(mTag, "Window type can not be changed after "
5596                        + "the window is added; ignoring change of " + mView);
5597                params.type = mOrigWindowType;
5598            }
5599        }
5600        int relayoutResult = mWindowSession.relayout(
5601                mWindow, mSeq, params,
5602                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
5603                (int) (mView.getMeasuredHeight() * appScale + 0.5f),
5604                viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
5605                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
5606                mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingConfiguration,
5607                mSurface);
5608
5609        mPendingAlwaysConsumeNavBar =
5610                (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_CONSUME_ALWAYS_NAV_BAR) != 0;
5611
5612        //Log.d(mTag, "<<<<<< BACK FROM relayout");
5613        if (restore) {
5614            params.restore();
5615        }
5616
5617        if (mTranslator != null) {
5618            mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
5619            mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
5620            mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
5621            mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
5622            mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
5623        }
5624        return relayoutResult;
5625    }
5626
5627    /**
5628     * {@inheritDoc}
5629     */
5630    @Override
5631    public void playSoundEffect(int effectId) {
5632        checkThread();
5633
5634        try {
5635            final AudioManager audioManager = getAudioManager();
5636
5637            switch (effectId) {
5638                case SoundEffectConstants.CLICK:
5639                    audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
5640                    return;
5641                case SoundEffectConstants.NAVIGATION_DOWN:
5642                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
5643                    return;
5644                case SoundEffectConstants.NAVIGATION_LEFT:
5645                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
5646                    return;
5647                case SoundEffectConstants.NAVIGATION_RIGHT:
5648                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
5649                    return;
5650                case SoundEffectConstants.NAVIGATION_UP:
5651                    audioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
5652                    return;
5653                default:
5654                    throw new IllegalArgumentException("unknown effect id " + effectId +
5655                            " not defined in " + SoundEffectConstants.class.getCanonicalName());
5656            }
5657        } catch (IllegalStateException e) {
5658            // Exception thrown by getAudioManager() when mView is null
5659            Log.e(mTag, "FATAL EXCEPTION when attempting to play sound effect: " + e);
5660            e.printStackTrace();
5661        }
5662    }
5663
5664    /**
5665     * {@inheritDoc}
5666     */
5667    @Override
5668    public boolean performHapticFeedback(int effectId, boolean always) {
5669        try {
5670            return mWindowSession.performHapticFeedback(mWindow, effectId, always);
5671        } catch (RemoteException e) {
5672            return false;
5673        }
5674    }
5675
5676    /**
5677     * {@inheritDoc}
5678     */
5679    @Override
5680    public View focusSearch(View focused, int direction) {
5681        checkThread();
5682        if (!(mView instanceof ViewGroup)) {
5683            return null;
5684        }
5685        return FocusFinder.getInstance().findNextFocus((ViewGroup) mView, focused, direction);
5686    }
5687
5688    public void debug() {
5689        mView.debug();
5690    }
5691
5692    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5693        String innerPrefix = prefix + "  ";
5694        writer.print(prefix); writer.println("ViewRoot:");
5695        writer.print(innerPrefix); writer.print("mAdded="); writer.print(mAdded);
5696                writer.print(" mRemoved="); writer.println(mRemoved);
5697        writer.print(innerPrefix); writer.print("mConsumeBatchedInputScheduled=");
5698                writer.println(mConsumeBatchedInputScheduled);
5699        writer.print(innerPrefix); writer.print("mConsumeBatchedInputImmediatelyScheduled=");
5700                writer.println(mConsumeBatchedInputImmediatelyScheduled);
5701        writer.print(innerPrefix); writer.print("mPendingInputEventCount=");
5702                writer.println(mPendingInputEventCount);
5703        writer.print(innerPrefix); writer.print("mProcessInputEventsScheduled=");
5704                writer.println(mProcessInputEventsScheduled);
5705        writer.print(innerPrefix); writer.print("mTraversalScheduled=");
5706                writer.print(mTraversalScheduled);
5707        writer.print(innerPrefix); writer.print("mIsAmbientMode=");
5708                writer.print(mIsAmbientMode);
5709        if (mTraversalScheduled) {
5710            writer.print(" (barrier="); writer.print(mTraversalBarrier); writer.println(")");
5711        } else {
5712            writer.println();
5713        }
5714        mFirstInputStage.dump(innerPrefix, writer);
5715
5716        mChoreographer.dump(prefix, writer);
5717
5718        writer.print(prefix); writer.println("View Hierarchy:");
5719        dumpViewHierarchy(innerPrefix, writer, mView);
5720    }
5721
5722    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
5723        writer.print(prefix);
5724        if (view == null) {
5725            writer.println("null");
5726            return;
5727        }
5728        writer.println(view.toString());
5729        if (!(view instanceof ViewGroup)) {
5730            return;
5731        }
5732        ViewGroup grp = (ViewGroup)view;
5733        final int N = grp.getChildCount();
5734        if (N <= 0) {
5735            return;
5736        }
5737        prefix = prefix + "  ";
5738        for (int i=0; i<N; i++) {
5739            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
5740        }
5741    }
5742
5743    public void dumpGfxInfo(int[] info) {
5744        info[0] = info[1] = 0;
5745        if (mView != null) {
5746            getGfxInfo(mView, info);
5747        }
5748    }
5749
5750    private static void getGfxInfo(View view, int[] info) {
5751        RenderNode renderNode = view.mRenderNode;
5752        info[0]++;
5753        if (renderNode != null) {
5754            info[1] += renderNode.getDebugSize();
5755        }
5756
5757        if (view instanceof ViewGroup) {
5758            ViewGroup group = (ViewGroup) view;
5759
5760            int count = group.getChildCount();
5761            for (int i = 0; i < count; i++) {
5762                getGfxInfo(group.getChildAt(i), info);
5763            }
5764        }
5765    }
5766
5767    /**
5768     * @param immediate True, do now if not in traversal. False, put on queue and do later.
5769     * @return True, request has been queued. False, request has been completed.
5770     */
5771    boolean die(boolean immediate) {
5772        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
5773        // done by dispatchDetachedFromWindow will cause havoc on return.
5774        if (immediate && !mIsInTraversal) {
5775            doDie();
5776            return false;
5777        }
5778
5779        if (!mIsDrawing) {
5780            destroyHardwareRenderer();
5781        } else {
5782            Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
5783                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
5784        }
5785        mHandler.sendEmptyMessage(MSG_DIE);
5786        return true;
5787    }
5788
5789    void doDie() {
5790        checkThread();
5791        if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
5792        synchronized (this) {
5793            if (mRemoved) {
5794                return;
5795            }
5796            mRemoved = true;
5797            if (mAdded) {
5798                dispatchDetachedFromWindow();
5799            }
5800
5801            if (mAdded && !mFirst) {
5802                destroyHardwareRenderer();
5803
5804                if (mView != null) {
5805                    int viewVisibility = mView.getVisibility();
5806                    boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
5807                    if (mWindowAttributesChanged || viewVisibilityChanged) {
5808                        // If layout params have been changed, first give them
5809                        // to the window manager to make sure it has the correct
5810                        // animation info.
5811                        try {
5812                            if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
5813                                    & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
5814                                mWindowSession.finishDrawing(mWindow);
5815                            }
5816                        } catch (RemoteException e) {
5817                        }
5818                    }
5819
5820                    mSurface.release();
5821                }
5822            }
5823
5824            mAdded = false;
5825        }
5826        WindowManagerGlobal.getInstance().doRemoveView(this);
5827    }
5828
5829    public void requestUpdateConfiguration(Configuration config) {
5830        Message msg = mHandler.obtainMessage(MSG_UPDATE_CONFIGURATION, config);
5831        mHandler.sendMessage(msg);
5832    }
5833
5834    public void loadSystemProperties() {
5835        mHandler.post(new Runnable() {
5836            @Override
5837            public void run() {
5838                // Profiling
5839                mProfileRendering = SystemProperties.getBoolean(PROPERTY_PROFILE_RENDERING, false);
5840                profileRendering(mAttachInfo.mHasWindowFocus);
5841
5842                // Hardware rendering
5843                if (mAttachInfo.mHardwareRenderer != null) {
5844                    if (mAttachInfo.mHardwareRenderer.loadSystemProperties()) {
5845                        invalidate();
5846                    }
5847                }
5848
5849                // Layout debugging
5850                boolean layout = SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false);
5851                if (layout != mAttachInfo.mDebugLayout) {
5852                    mAttachInfo.mDebugLayout = layout;
5853                    if (!mHandler.hasMessages(MSG_INVALIDATE_WORLD)) {
5854                        mHandler.sendEmptyMessageDelayed(MSG_INVALIDATE_WORLD, 200);
5855                    }
5856                }
5857            }
5858        });
5859    }
5860
5861    private void destroyHardwareRenderer() {
5862        ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
5863
5864        if (hardwareRenderer != null) {
5865            if (mView != null) {
5866                hardwareRenderer.destroyHardwareResources(mView);
5867            }
5868            hardwareRenderer.destroy();
5869            hardwareRenderer.setRequested(false);
5870
5871            mAttachInfo.mHardwareRenderer = null;
5872            mAttachInfo.mHardwareAccelerated = false;
5873        }
5874    }
5875
5876    public void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
5877            Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
5878            Configuration newConfig, Rect backDropFrame, boolean forceLayout,
5879            boolean alwaysConsumeNavBar) {
5880        if (DEBUG_LAYOUT) Log.v(mTag, "Resizing " + this + ": frame=" + frame.toShortString()
5881                + " contentInsets=" + contentInsets.toShortString()
5882                + " visibleInsets=" + visibleInsets.toShortString()
5883                + " reportDraw=" + reportDraw
5884                + " backDropFrame=" + backDropFrame);
5885
5886        // Tell all listeners that we are resizing the window so that the chrome can get
5887        // updated as fast as possible on a separate thread,
5888        if (mDragResizing) {
5889            boolean fullscreen = frame.equals(backDropFrame);
5890            synchronized (mWindowCallbacks) {
5891                for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
5892                    mWindowCallbacks.get(i).onWindowSizeIsChanging(backDropFrame, fullscreen,
5893                            visibleInsets, stableInsets);
5894                }
5895            }
5896        }
5897
5898        Message msg = mHandler.obtainMessage(reportDraw ? MSG_RESIZED_REPORT : MSG_RESIZED);
5899        if (mTranslator != null) {
5900            mTranslator.translateRectInScreenToAppWindow(frame);
5901            mTranslator.translateRectInScreenToAppWindow(overscanInsets);
5902            mTranslator.translateRectInScreenToAppWindow(contentInsets);
5903            mTranslator.translateRectInScreenToAppWindow(visibleInsets);
5904        }
5905        SomeArgs args = SomeArgs.obtain();
5906        final boolean sameProcessCall = (Binder.getCallingPid() == android.os.Process.myPid());
5907        args.arg1 = sameProcessCall ? new Rect(frame) : frame;
5908        args.arg2 = sameProcessCall ? new Rect(contentInsets) : contentInsets;
5909        args.arg3 = sameProcessCall ? new Rect(visibleInsets) : visibleInsets;
5910        args.arg4 = sameProcessCall && newConfig != null ? new Configuration(newConfig) : newConfig;
5911        args.arg5 = sameProcessCall ? new Rect(overscanInsets) : overscanInsets;
5912        args.arg6 = sameProcessCall ? new Rect(stableInsets) : stableInsets;
5913        args.arg7 = sameProcessCall ? new Rect(outsets) : outsets;
5914        args.arg8 = sameProcessCall ? new Rect(backDropFrame) : backDropFrame;
5915        args.argi1 = forceLayout ? 1 : 0;
5916        args.argi2 = alwaysConsumeNavBar ? 1 : 0;
5917        msg.obj = args;
5918        mHandler.sendMessage(msg);
5919    }
5920
5921    public void dispatchMoved(int newX, int newY) {
5922        if (DEBUG_LAYOUT) Log.v(mTag, "Window moved " + this + ": newX=" + newX + " newY=" + newY);
5923        if (mTranslator != null) {
5924            PointF point = new PointF(newX, newY);
5925            mTranslator.translatePointInScreenToAppWindow(point);
5926            newX = (int) (point.x + 0.5);
5927            newY = (int) (point.y + 0.5);
5928        }
5929        Message msg = mHandler.obtainMessage(MSG_WINDOW_MOVED, newX, newY);
5930        mHandler.sendMessage(msg);
5931    }
5932
5933    /**
5934     * Represents a pending input event that is waiting in a queue.
5935     *
5936     * Input events are processed in serial order by the timestamp specified by
5937     * {@link InputEvent#getEventTimeNano()}.  In general, the input dispatcher delivers
5938     * one input event to the application at a time and waits for the application
5939     * to finish handling it before delivering the next one.
5940     *
5941     * However, because the application or IME can synthesize and inject multiple
5942     * key events at a time without going through the input dispatcher, we end up
5943     * needing a queue on the application's side.
5944     */
5945    private static final class QueuedInputEvent {
5946        public static final int FLAG_DELIVER_POST_IME = 1 << 0;
5947        public static final int FLAG_DEFERRED = 1 << 1;
5948        public static final int FLAG_FINISHED = 1 << 2;
5949        public static final int FLAG_FINISHED_HANDLED = 1 << 3;
5950        public static final int FLAG_RESYNTHESIZED = 1 << 4;
5951        public static final int FLAG_UNHANDLED = 1 << 5;
5952
5953        public QueuedInputEvent mNext;
5954
5955        public InputEvent mEvent;
5956        public InputEventReceiver mReceiver;
5957        public int mFlags;
5958
5959        public boolean shouldSkipIme() {
5960            if ((mFlags & FLAG_DELIVER_POST_IME) != 0) {
5961                return true;
5962            }
5963            return mEvent instanceof MotionEvent
5964                    && mEvent.isFromSource(InputDevice.SOURCE_CLASS_POINTER);
5965        }
5966
5967        public boolean shouldSendToSynthesizer() {
5968            if ((mFlags & FLAG_UNHANDLED) != 0) {
5969                return true;
5970            }
5971
5972            return false;
5973        }
5974
5975        @Override
5976        public String toString() {
5977            StringBuilder sb = new StringBuilder("QueuedInputEvent{flags=");
5978            boolean hasPrevious = false;
5979            hasPrevious = flagToString("DELIVER_POST_IME", FLAG_DELIVER_POST_IME, hasPrevious, sb);
5980            hasPrevious = flagToString("DEFERRED", FLAG_DEFERRED, hasPrevious, sb);
5981            hasPrevious = flagToString("FINISHED", FLAG_FINISHED, hasPrevious, sb);
5982            hasPrevious = flagToString("FINISHED_HANDLED", FLAG_FINISHED_HANDLED, hasPrevious, sb);
5983            hasPrevious = flagToString("RESYNTHESIZED", FLAG_RESYNTHESIZED, hasPrevious, sb);
5984            hasPrevious = flagToString("UNHANDLED", FLAG_UNHANDLED, hasPrevious, sb);
5985            if (!hasPrevious) {
5986                sb.append("0");
5987            }
5988            sb.append(", hasNextQueuedEvent=" + (mEvent != null ? "true" : "false"));
5989            sb.append(", hasInputEventReceiver=" + (mReceiver != null ? "true" : "false"));
5990            sb.append(", mEvent=" + mEvent + "}");
5991            return sb.toString();
5992        }
5993
5994        private boolean flagToString(String name, int flag,
5995                boolean hasPrevious, StringBuilder sb) {
5996            if ((mFlags & flag) != 0) {
5997                if (hasPrevious) {
5998                    sb.append("|");
5999                }
6000                sb.append(name);
6001                return true;
6002            }
6003            return hasPrevious;
6004        }
6005    }
6006
6007    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
6008            InputEventReceiver receiver, int flags) {
6009        QueuedInputEvent q = mQueuedInputEventPool;
6010        if (q != null) {
6011            mQueuedInputEventPoolSize -= 1;
6012            mQueuedInputEventPool = q.mNext;
6013            q.mNext = null;
6014        } else {
6015            q = new QueuedInputEvent();
6016        }
6017
6018        q.mEvent = event;
6019        q.mReceiver = receiver;
6020        q.mFlags = flags;
6021        return q;
6022    }
6023
6024    private void recycleQueuedInputEvent(QueuedInputEvent q) {
6025        q.mEvent = null;
6026        q.mReceiver = null;
6027
6028        if (mQueuedInputEventPoolSize < MAX_QUEUED_INPUT_EVENT_POOL_SIZE) {
6029            mQueuedInputEventPoolSize += 1;
6030            q.mNext = mQueuedInputEventPool;
6031            mQueuedInputEventPool = q;
6032        }
6033    }
6034
6035    void enqueueInputEvent(InputEvent event) {
6036        enqueueInputEvent(event, null, 0, false);
6037    }
6038
6039    void enqueueInputEvent(InputEvent event,
6040            InputEventReceiver receiver, int flags, boolean processImmediately) {
6041        adjustInputEventForCompatibility(event);
6042        QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);
6043
6044        // Always enqueue the input event in order, regardless of its time stamp.
6045        // We do this because the application or the IME may inject key events
6046        // in response to touch events and we want to ensure that the injected keys
6047        // are processed in the order they were received and we cannot trust that
6048        // the time stamp of injected events are monotonic.
6049        QueuedInputEvent last = mPendingInputEventTail;
6050        if (last == null) {
6051            mPendingInputEventHead = q;
6052            mPendingInputEventTail = q;
6053        } else {
6054            last.mNext = q;
6055            mPendingInputEventTail = q;
6056        }
6057        mPendingInputEventCount += 1;
6058        Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6059                mPendingInputEventCount);
6060
6061        if (processImmediately) {
6062            doProcessInputEvents();
6063        } else {
6064            scheduleProcessInputEvents();
6065        }
6066    }
6067
6068    private void scheduleProcessInputEvents() {
6069        if (!mProcessInputEventsScheduled) {
6070            mProcessInputEventsScheduled = true;
6071            Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);
6072            msg.setAsynchronous(true);
6073            mHandler.sendMessage(msg);
6074        }
6075    }
6076
6077    void doProcessInputEvents() {
6078        // Deliver all pending input events in the queue.
6079        while (mPendingInputEventHead != null) {
6080            QueuedInputEvent q = mPendingInputEventHead;
6081            mPendingInputEventHead = q.mNext;
6082            if (mPendingInputEventHead == null) {
6083                mPendingInputEventTail = null;
6084            }
6085            q.mNext = null;
6086
6087            mPendingInputEventCount -= 1;
6088            Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,
6089                    mPendingInputEventCount);
6090
6091            long eventTime = q.mEvent.getEventTimeNano();
6092            long oldestEventTime = eventTime;
6093            if (q.mEvent instanceof MotionEvent) {
6094                MotionEvent me = (MotionEvent)q.mEvent;
6095                if (me.getHistorySize() > 0) {
6096                    oldestEventTime = me.getHistoricalEventTimeNano(0);
6097                }
6098            }
6099            mChoreographer.mFrameInfo.updateInputEventTime(eventTime, oldestEventTime);
6100
6101            deliverInputEvent(q);
6102        }
6103
6104        // We are done processing all input events that we can process right now
6105        // so we can clear the pending flag immediately.
6106        if (mProcessInputEventsScheduled) {
6107            mProcessInputEventsScheduled = false;
6108            mHandler.removeMessages(MSG_PROCESS_INPUT_EVENTS);
6109        }
6110    }
6111
6112    private void deliverInputEvent(QueuedInputEvent q) {
6113        Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6114                q.mEvent.getSequenceNumber());
6115        if (mInputEventConsistencyVerifier != null) {
6116            mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
6117        }
6118
6119        InputStage stage;
6120        if (q.shouldSendToSynthesizer()) {
6121            stage = mSyntheticInputStage;
6122        } else {
6123            stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
6124        }
6125
6126        if (stage != null) {
6127            stage.deliver(q);
6128        } else {
6129            finishInputEvent(q);
6130        }
6131    }
6132
6133    private void finishInputEvent(QueuedInputEvent q) {
6134        Trace.asyncTraceEnd(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
6135                q.mEvent.getSequenceNumber());
6136
6137        if (q.mReceiver != null) {
6138            boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;
6139            q.mReceiver.finishInputEvent(q.mEvent, handled);
6140        } else {
6141            q.mEvent.recycleIfNeededAfterDispatch();
6142        }
6143
6144        recycleQueuedInputEvent(q);
6145    }
6146
6147    private void adjustInputEventForCompatibility(InputEvent e) {
6148        if (mTargetSdkVersion < Build.VERSION_CODES.M && e instanceof MotionEvent) {
6149            MotionEvent motion = (MotionEvent) e;
6150            final int mask =
6151                MotionEvent.BUTTON_STYLUS_PRIMARY | MotionEvent.BUTTON_STYLUS_SECONDARY;
6152            final int buttonState = motion.getButtonState();
6153            final int compatButtonState = (buttonState & mask) >> 4;
6154            if (compatButtonState != 0) {
6155                motion.setButtonState(buttonState | compatButtonState);
6156            }
6157        }
6158    }
6159
6160    static boolean isTerminalInputEvent(InputEvent event) {
6161        if (event instanceof KeyEvent) {
6162            final KeyEvent keyEvent = (KeyEvent)event;
6163            return keyEvent.getAction() == KeyEvent.ACTION_UP;
6164        } else {
6165            final MotionEvent motionEvent = (MotionEvent)event;
6166            final int action = motionEvent.getAction();
6167            return action == MotionEvent.ACTION_UP
6168                    || action == MotionEvent.ACTION_CANCEL
6169                    || action == MotionEvent.ACTION_HOVER_EXIT;
6170        }
6171    }
6172
6173    void scheduleConsumeBatchedInput() {
6174        if (!mConsumeBatchedInputScheduled) {
6175            mConsumeBatchedInputScheduled = true;
6176            mChoreographer.postCallback(Choreographer.CALLBACK_INPUT,
6177                    mConsumedBatchedInputRunnable, null);
6178        }
6179    }
6180
6181    void unscheduleConsumeBatchedInput() {
6182        if (mConsumeBatchedInputScheduled) {
6183            mConsumeBatchedInputScheduled = false;
6184            mChoreographer.removeCallbacks(Choreographer.CALLBACK_INPUT,
6185                    mConsumedBatchedInputRunnable, null);
6186        }
6187    }
6188
6189    void scheduleConsumeBatchedInputImmediately() {
6190        if (!mConsumeBatchedInputImmediatelyScheduled) {
6191            unscheduleConsumeBatchedInput();
6192            mConsumeBatchedInputImmediatelyScheduled = true;
6193            mHandler.post(mConsumeBatchedInputImmediatelyRunnable);
6194        }
6195    }
6196
6197    void doConsumeBatchedInput(long frameTimeNanos) {
6198        if (mConsumeBatchedInputScheduled) {
6199            mConsumeBatchedInputScheduled = false;
6200            if (mInputEventReceiver != null) {
6201                if (mInputEventReceiver.consumeBatchedInputEvents(frameTimeNanos)
6202                        && frameTimeNanos != -1) {
6203                    // If we consumed a batch here, we want to go ahead and schedule the
6204                    // consumption of batched input events on the next frame. Otherwise, we would
6205                    // wait until we have more input events pending and might get starved by other
6206                    // things occurring in the process. If the frame time is -1, however, then
6207                    // we're in a non-batching mode, so there's no need to schedule this.
6208                    scheduleConsumeBatchedInput();
6209                }
6210            }
6211            doProcessInputEvents();
6212        }
6213    }
6214
6215    final class TraversalRunnable implements Runnable {
6216        @Override
6217        public void run() {
6218            doTraversal();
6219        }
6220    }
6221    final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
6222
6223    final class WindowInputEventReceiver extends InputEventReceiver {
6224        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
6225            super(inputChannel, looper);
6226        }
6227
6228        @Override
6229        public void onInputEvent(InputEvent event) {
6230            enqueueInputEvent(event, this, 0, true);
6231        }
6232
6233        @Override
6234        public void onBatchedInputEventPending() {
6235            if (mUnbufferedInputDispatch) {
6236                super.onBatchedInputEventPending();
6237            } else {
6238                scheduleConsumeBatchedInput();
6239            }
6240        }
6241
6242        @Override
6243        public void dispose() {
6244            unscheduleConsumeBatchedInput();
6245            super.dispose();
6246        }
6247    }
6248    WindowInputEventReceiver mInputEventReceiver;
6249
6250    final class ConsumeBatchedInputRunnable implements Runnable {
6251        @Override
6252        public void run() {
6253            doConsumeBatchedInput(mChoreographer.getFrameTimeNanos());
6254        }
6255    }
6256    final ConsumeBatchedInputRunnable mConsumedBatchedInputRunnable =
6257            new ConsumeBatchedInputRunnable();
6258    boolean mConsumeBatchedInputScheduled;
6259
6260    final class ConsumeBatchedInputImmediatelyRunnable implements Runnable {
6261        @Override
6262        public void run() {
6263            doConsumeBatchedInput(-1);
6264        }
6265    }
6266    final ConsumeBatchedInputImmediatelyRunnable mConsumeBatchedInputImmediatelyRunnable =
6267            new ConsumeBatchedInputImmediatelyRunnable();
6268    boolean mConsumeBatchedInputImmediatelyScheduled;
6269
6270    final class InvalidateOnAnimationRunnable implements Runnable {
6271        private boolean mPosted;
6272        private final ArrayList<View> mViews = new ArrayList<View>();
6273        private final ArrayList<AttachInfo.InvalidateInfo> mViewRects =
6274                new ArrayList<AttachInfo.InvalidateInfo>();
6275        private View[] mTempViews;
6276        private AttachInfo.InvalidateInfo[] mTempViewRects;
6277
6278        public void addView(View view) {
6279            synchronized (this) {
6280                mViews.add(view);
6281                postIfNeededLocked();
6282            }
6283        }
6284
6285        public void addViewRect(AttachInfo.InvalidateInfo info) {
6286            synchronized (this) {
6287                mViewRects.add(info);
6288                postIfNeededLocked();
6289            }
6290        }
6291
6292        public void removeView(View view) {
6293            synchronized (this) {
6294                mViews.remove(view);
6295
6296                for (int i = mViewRects.size(); i-- > 0; ) {
6297                    AttachInfo.InvalidateInfo info = mViewRects.get(i);
6298                    if (info.target == view) {
6299                        mViewRects.remove(i);
6300                        info.recycle();
6301                    }
6302                }
6303
6304                if (mPosted && mViews.isEmpty() && mViewRects.isEmpty()) {
6305                    mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, this, null);
6306                    mPosted = false;
6307                }
6308            }
6309        }
6310
6311        @Override
6312        public void run() {
6313            final int viewCount;
6314            final int viewRectCount;
6315            synchronized (this) {
6316                mPosted = false;
6317
6318                viewCount = mViews.size();
6319                if (viewCount != 0) {
6320                    mTempViews = mViews.toArray(mTempViews != null
6321                            ? mTempViews : new View[viewCount]);
6322                    mViews.clear();
6323                }
6324
6325                viewRectCount = mViewRects.size();
6326                if (viewRectCount != 0) {
6327                    mTempViewRects = mViewRects.toArray(mTempViewRects != null
6328                            ? mTempViewRects : new AttachInfo.InvalidateInfo[viewRectCount]);
6329                    mViewRects.clear();
6330                }
6331            }
6332
6333            for (int i = 0; i < viewCount; i++) {
6334                mTempViews[i].invalidate();
6335                mTempViews[i] = null;
6336            }
6337
6338            for (int i = 0; i < viewRectCount; i++) {
6339                final View.AttachInfo.InvalidateInfo info = mTempViewRects[i];
6340                info.target.invalidate(info.left, info.top, info.right, info.bottom);
6341                info.recycle();
6342            }
6343        }
6344
6345        private void postIfNeededLocked() {
6346            if (!mPosted) {
6347                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
6348                mPosted = true;
6349            }
6350        }
6351    }
6352    final InvalidateOnAnimationRunnable mInvalidateOnAnimationRunnable =
6353            new InvalidateOnAnimationRunnable();
6354
6355    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
6356        Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
6357        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6358    }
6359
6360    public void dispatchInvalidateRectDelayed(AttachInfo.InvalidateInfo info,
6361            long delayMilliseconds) {
6362        final Message msg = mHandler.obtainMessage(MSG_INVALIDATE_RECT, info);
6363        mHandler.sendMessageDelayed(msg, delayMilliseconds);
6364    }
6365
6366    public void dispatchInvalidateOnAnimation(View view) {
6367        mInvalidateOnAnimationRunnable.addView(view);
6368    }
6369
6370    public void dispatchInvalidateRectOnAnimation(AttachInfo.InvalidateInfo info) {
6371        mInvalidateOnAnimationRunnable.addViewRect(info);
6372    }
6373
6374    public void cancelInvalidate(View view) {
6375        mHandler.removeMessages(MSG_INVALIDATE, view);
6376        // fixme: might leak the AttachInfo.InvalidateInfo objects instead of returning
6377        // them to the pool
6378        mHandler.removeMessages(MSG_INVALIDATE_RECT, view);
6379        mInvalidateOnAnimationRunnable.removeView(view);
6380    }
6381
6382    public void dispatchInputEvent(InputEvent event) {
6383        dispatchInputEvent(event, null);
6384    }
6385
6386    public void dispatchInputEvent(InputEvent event, InputEventReceiver receiver) {
6387        SomeArgs args = SomeArgs.obtain();
6388        args.arg1 = event;
6389        args.arg2 = receiver;
6390        Message msg = mHandler.obtainMessage(MSG_DISPATCH_INPUT_EVENT, args);
6391        msg.setAsynchronous(true);
6392        mHandler.sendMessage(msg);
6393    }
6394
6395    public void synthesizeInputEvent(InputEvent event) {
6396        Message msg = mHandler.obtainMessage(MSG_SYNTHESIZE_INPUT_EVENT, event);
6397        msg.setAsynchronous(true);
6398        mHandler.sendMessage(msg);
6399    }
6400
6401    public void dispatchKeyFromIme(KeyEvent event) {
6402        Message msg = mHandler.obtainMessage(MSG_DISPATCH_KEY_FROM_IME, event);
6403        msg.setAsynchronous(true);
6404        mHandler.sendMessage(msg);
6405    }
6406
6407    /**
6408     * Reinject unhandled {@link InputEvent}s in order to synthesize fallbacks events.
6409     *
6410     * Note that it is the responsibility of the caller of this API to recycle the InputEvent it
6411     * passes in.
6412     */
6413    public void dispatchUnhandledInputEvent(InputEvent event) {
6414        if (event instanceof MotionEvent) {
6415            event = MotionEvent.obtain((MotionEvent) event);
6416        }
6417        synthesizeInputEvent(event);
6418    }
6419
6420    public void dispatchAppVisibility(boolean visible) {
6421        Message msg = mHandler.obtainMessage(MSG_DISPATCH_APP_VISIBILITY);
6422        msg.arg1 = visible ? 1 : 0;
6423        mHandler.sendMessage(msg);
6424    }
6425
6426    public void dispatchGetNewSurface() {
6427        Message msg = mHandler.obtainMessage(MSG_DISPATCH_GET_NEW_SURFACE);
6428        mHandler.sendMessage(msg);
6429    }
6430
6431    public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6432        Message msg = Message.obtain();
6433        msg.what = MSG_WINDOW_FOCUS_CHANGED;
6434        msg.arg1 = hasFocus ? 1 : 0;
6435        msg.arg2 = inTouchMode ? 1 : 0;
6436        mHandler.sendMessage(msg);
6437    }
6438
6439    public void dispatchWindowShown() {
6440        mHandler.sendEmptyMessage(MSG_DISPATCH_WINDOW_SHOWN);
6441    }
6442
6443    public void dispatchCloseSystemDialogs(String reason) {
6444        Message msg = Message.obtain();
6445        msg.what = MSG_CLOSE_SYSTEM_DIALOGS;
6446        msg.obj = reason;
6447        mHandler.sendMessage(msg);
6448    }
6449
6450    public void dispatchDragEvent(DragEvent event) {
6451        final int what;
6452        if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) {
6453            what = MSG_DISPATCH_DRAG_LOCATION_EVENT;
6454            mHandler.removeMessages(what);
6455        } else {
6456            what = MSG_DISPATCH_DRAG_EVENT;
6457        }
6458        Message msg = mHandler.obtainMessage(what, event);
6459        mHandler.sendMessage(msg);
6460    }
6461
6462    public void updatePointerIcon(float x, float y) {
6463        final int what = MSG_UPDATE_POINTER_ICON;
6464        mHandler.removeMessages(what);
6465        final long now = SystemClock.uptimeMillis();
6466        final MotionEvent event = MotionEvent.obtain(
6467                0, now, MotionEvent.ACTION_HOVER_MOVE, x, y, 0);
6468        Message msg = mHandler.obtainMessage(what, event);
6469        mHandler.sendMessage(msg);
6470    }
6471
6472    public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
6473            int localValue, int localChanges) {
6474        SystemUiVisibilityInfo args = new SystemUiVisibilityInfo();
6475        args.seq = seq;
6476        args.globalVisibility = globalVisibility;
6477        args.localValue = localValue;
6478        args.localChanges = localChanges;
6479        mHandler.sendMessage(mHandler.obtainMessage(MSG_DISPATCH_SYSTEM_UI_VISIBILITY, args));
6480    }
6481
6482    public void dispatchCheckFocus() {
6483        if (!mHandler.hasMessages(MSG_CHECK_FOCUS)) {
6484            // This will result in a call to checkFocus() below.
6485            mHandler.sendEmptyMessage(MSG_CHECK_FOCUS);
6486        }
6487    }
6488
6489    public void dispatchRequestKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
6490        mHandler.obtainMessage(
6491                MSG_REQUEST_KEYBOARD_SHORTCUTS, deviceId, 0, receiver).sendToTarget();
6492    }
6493
6494    /**
6495     * Post a callback to send a
6496     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6497     * This event is send at most once every
6498     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
6499     */
6500    private void postSendWindowContentChangedCallback(View source, int changeType) {
6501        if (mSendWindowContentChangedAccessibilityEvent == null) {
6502            mSendWindowContentChangedAccessibilityEvent =
6503                new SendWindowContentChangedAccessibilityEvent();
6504        }
6505        mSendWindowContentChangedAccessibilityEvent.runOrPost(source, changeType);
6506    }
6507
6508    /**
6509     * Remove a posted callback to send a
6510     * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED} event.
6511     */
6512    private void removeSendWindowContentChangedCallback() {
6513        if (mSendWindowContentChangedAccessibilityEvent != null) {
6514            mHandler.removeCallbacks(mSendWindowContentChangedAccessibilityEvent);
6515        }
6516    }
6517
6518    @Override
6519    public boolean showContextMenuForChild(View originalView) {
6520        return false;
6521    }
6522
6523    @Override
6524    public boolean showContextMenuForChild(View originalView, float x, float y) {
6525        return false;
6526    }
6527
6528    @Override
6529    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
6530        return null;
6531    }
6532
6533    @Override
6534    public ActionMode startActionModeForChild(
6535            View originalView, ActionMode.Callback callback, int type) {
6536        return null;
6537    }
6538
6539    @Override
6540    public void createContextMenu(ContextMenu menu) {
6541    }
6542
6543    @Override
6544    public void childDrawableStateChanged(View child) {
6545    }
6546
6547    @Override
6548    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
6549        if (mView == null || mStopped || mPausedForTransition) {
6550            return false;
6551        }
6552        // Intercept accessibility focus events fired by virtual nodes to keep
6553        // track of accessibility focus position in such nodes.
6554        final int eventType = event.getEventType();
6555        switch (eventType) {
6556            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
6557                final long sourceNodeId = event.getSourceNodeId();
6558                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6559                        sourceNodeId);
6560                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6561                if (source != null) {
6562                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6563                    if (provider != null) {
6564                        final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
6565                                sourceNodeId);
6566                        final AccessibilityNodeInfo node;
6567                        if (virtualNodeId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6568                            node = provider.createAccessibilityNodeInfo(
6569                                    AccessibilityNodeProvider.HOST_VIEW_ID);
6570                        } else {
6571                            node = provider.createAccessibilityNodeInfo(virtualNodeId);
6572                        }
6573                        setAccessibilityFocus(source, node);
6574                    }
6575                }
6576            } break;
6577            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
6578                final long sourceNodeId = event.getSourceNodeId();
6579                final int accessibilityViewId = AccessibilityNodeInfo.getAccessibilityViewId(
6580                        sourceNodeId);
6581                View source = mView.findViewByAccessibilityId(accessibilityViewId);
6582                if (source != null) {
6583                    AccessibilityNodeProvider provider = source.getAccessibilityNodeProvider();
6584                    if (provider != null) {
6585                        setAccessibilityFocus(null, null);
6586                    }
6587                }
6588            } break;
6589
6590
6591            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
6592                handleWindowContentChangedEvent(event);
6593            } break;
6594        }
6595        mAccessibilityManager.sendAccessibilityEvent(event);
6596        return true;
6597    }
6598
6599    /**
6600     * Updates the focused virtual view, when necessary, in response to a
6601     * content changed event.
6602     * <p>
6603     * This is necessary to get updated bounds after a position change.
6604     *
6605     * @param event an accessibility event of type
6606     *              {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
6607     */
6608    private void handleWindowContentChangedEvent(AccessibilityEvent event) {
6609        final View focusedHost = mAccessibilityFocusedHost;
6610        if (focusedHost == null || mAccessibilityFocusedVirtualView == null) {
6611            // No virtual view focused, nothing to do here.
6612            return;
6613        }
6614
6615        final AccessibilityNodeProvider provider = focusedHost.getAccessibilityNodeProvider();
6616        if (provider == null) {
6617            // Error state: virtual view with no provider. Clear focus.
6618            mAccessibilityFocusedHost = null;
6619            mAccessibilityFocusedVirtualView = null;
6620            focusedHost.clearAccessibilityFocusNoCallbacks();
6621            return;
6622        }
6623
6624        // We only care about change types that may affect the bounds of the
6625        // focused virtual view.
6626        final int changes = event.getContentChangeTypes();
6627        if ((changes & AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE) == 0
6628                && changes != AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
6629            return;
6630        }
6631
6632        final long eventSourceNodeId = event.getSourceNodeId();
6633        final int changedViewId = AccessibilityNodeInfo.getAccessibilityViewId(eventSourceNodeId);
6634
6635        // Search up the tree for subtree containment.
6636        boolean hostInSubtree = false;
6637        View root = mAccessibilityFocusedHost;
6638        while (root != null && !hostInSubtree) {
6639            if (changedViewId == root.getAccessibilityViewId()) {
6640                hostInSubtree = true;
6641            } else {
6642                final ViewParent parent = root.getParent();
6643                if (parent instanceof View) {
6644                    root = (View) parent;
6645                } else {
6646                    root = null;
6647                }
6648            }
6649        }
6650
6651        // We care only about changes in subtrees containing the host view.
6652        if (!hostInSubtree) {
6653            return;
6654        }
6655
6656        final long focusedSourceNodeId = mAccessibilityFocusedVirtualView.getSourceNodeId();
6657        int focusedChildId = AccessibilityNodeInfo.getVirtualDescendantId(focusedSourceNodeId);
6658        if (focusedChildId == AccessibilityNodeInfo.UNDEFINED_ITEM_ID) {
6659            // TODO: Should we clear the focused virtual view?
6660            focusedChildId = AccessibilityNodeProvider.HOST_VIEW_ID;
6661        }
6662
6663        // Refresh the node for the focused virtual view.
6664        final Rect oldBounds = mTempRect;
6665        mAccessibilityFocusedVirtualView.getBoundsInScreen(oldBounds);
6666        mAccessibilityFocusedVirtualView = provider.createAccessibilityNodeInfo(focusedChildId);
6667        if (mAccessibilityFocusedVirtualView == null) {
6668            // Error state: The node no longer exists. Clear focus.
6669            mAccessibilityFocusedHost = null;
6670            focusedHost.clearAccessibilityFocusNoCallbacks();
6671
6672            // This will probably fail, but try to keep the provider's internal
6673            // state consistent by clearing focus.
6674            provider.performAction(focusedChildId,
6675                    AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS.getId(), null);
6676            invalidateRectOnScreen(oldBounds);
6677        } else {
6678            // The node was refreshed, invalidate bounds if necessary.
6679            final Rect newBounds = mAccessibilityFocusedVirtualView.getBoundsInScreen();
6680            if (!oldBounds.equals(newBounds)) {
6681                oldBounds.union(newBounds);
6682                invalidateRectOnScreen(oldBounds);
6683            }
6684        }
6685    }
6686
6687    @Override
6688    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
6689        postSendWindowContentChangedCallback(source, changeType);
6690    }
6691
6692    @Override
6693    public boolean canResolveLayoutDirection() {
6694        return true;
6695    }
6696
6697    @Override
6698    public boolean isLayoutDirectionResolved() {
6699        return true;
6700    }
6701
6702    @Override
6703    public int getLayoutDirection() {
6704        return View.LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6705    }
6706
6707    @Override
6708    public boolean canResolveTextDirection() {
6709        return true;
6710    }
6711
6712    @Override
6713    public boolean isTextDirectionResolved() {
6714        return true;
6715    }
6716
6717    @Override
6718    public int getTextDirection() {
6719        return View.TEXT_DIRECTION_RESOLVED_DEFAULT;
6720    }
6721
6722    @Override
6723    public boolean canResolveTextAlignment() {
6724        return true;
6725    }
6726
6727    @Override
6728    public boolean isTextAlignmentResolved() {
6729        return true;
6730    }
6731
6732    @Override
6733    public int getTextAlignment() {
6734        return View.TEXT_ALIGNMENT_RESOLVED_DEFAULT;
6735    }
6736
6737    private View getCommonPredecessor(View first, View second) {
6738        if (mTempHashSet == null) {
6739            mTempHashSet = new HashSet<View>();
6740        }
6741        HashSet<View> seen = mTempHashSet;
6742        seen.clear();
6743        View firstCurrent = first;
6744        while (firstCurrent != null) {
6745            seen.add(firstCurrent);
6746            ViewParent firstCurrentParent = firstCurrent.mParent;
6747            if (firstCurrentParent instanceof View) {
6748                firstCurrent = (View) firstCurrentParent;
6749            } else {
6750                firstCurrent = null;
6751            }
6752        }
6753        View secondCurrent = second;
6754        while (secondCurrent != null) {
6755            if (seen.contains(secondCurrent)) {
6756                seen.clear();
6757                return secondCurrent;
6758            }
6759            ViewParent secondCurrentParent = secondCurrent.mParent;
6760            if (secondCurrentParent instanceof View) {
6761                secondCurrent = (View) secondCurrentParent;
6762            } else {
6763                secondCurrent = null;
6764            }
6765        }
6766        seen.clear();
6767        return null;
6768    }
6769
6770    void checkThread() {
6771        if (mThread != Thread.currentThread()) {
6772            throw new CalledFromWrongThreadException(
6773                    "Only the original thread that created a view hierarchy can touch its views.");
6774        }
6775    }
6776
6777    @Override
6778    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
6779        // ViewAncestor never intercepts touch event, so this can be a no-op
6780    }
6781
6782    @Override
6783    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
6784        if (rectangle == null) {
6785            return scrollToRectOrFocus(null, immediate);
6786        }
6787        rectangle.offset(child.getLeft() - child.getScrollX(),
6788                child.getTop() - child.getScrollY());
6789        final boolean scrolled = scrollToRectOrFocus(rectangle, immediate);
6790        mTempRect.set(rectangle);
6791        mTempRect.offset(0, -mCurScrollY);
6792        mTempRect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
6793        try {
6794            mWindowSession.onRectangleOnScreenRequested(mWindow, mTempRect);
6795        } catch (RemoteException re) {
6796            /* ignore */
6797        }
6798        return scrolled;
6799    }
6800
6801    @Override
6802    public void childHasTransientStateChanged(View child, boolean hasTransientState) {
6803        // Do nothing.
6804    }
6805
6806    @Override
6807    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6808        return false;
6809    }
6810
6811    @Override
6812    public void onStopNestedScroll(View target) {
6813    }
6814
6815    @Override
6816    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
6817    }
6818
6819    @Override
6820    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6821            int dxUnconsumed, int dyUnconsumed) {
6822    }
6823
6824    @Override
6825    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6826    }
6827
6828    @Override
6829    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6830        return false;
6831    }
6832
6833    @Override
6834    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6835        return false;
6836    }
6837
6838    @Override
6839    public boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args) {
6840        return false;
6841    }
6842
6843    /**
6844     * Force the window to report its next draw.
6845     * <p>
6846     * This method is only supposed to be used to speed up the interaction from SystemUI and window
6847     * manager when waiting for the first frame to be drawn when turning on the screen. DO NOT USE
6848     * unless you fully understand this interaction.
6849     * @hide
6850     */
6851    public void setReportNextDraw() {
6852        mReportNextDraw = true;
6853        invalidate();
6854    }
6855
6856    void changeCanvasOpacity(boolean opaque) {
6857        Log.d(mTag, "changeCanvasOpacity: opaque=" + opaque);
6858        if (mAttachInfo.mHardwareRenderer != null) {
6859            mAttachInfo.mHardwareRenderer.setOpaque(opaque);
6860        }
6861    }
6862
6863    class TakenSurfaceHolder extends BaseSurfaceHolder {
6864        @Override
6865        public boolean onAllowLockCanvas() {
6866            return mDrawingAllowed;
6867        }
6868
6869        @Override
6870        public void onRelayoutContainer() {
6871            // Not currently interesting -- from changing between fixed and layout size.
6872        }
6873
6874        @Override
6875        public void setFormat(int format) {
6876            ((RootViewSurfaceTaker)mView).setSurfaceFormat(format);
6877        }
6878
6879        @Override
6880        public void setType(int type) {
6881            ((RootViewSurfaceTaker)mView).setSurfaceType(type);
6882        }
6883
6884        @Override
6885        public void onUpdateSurface() {
6886            // We take care of format and type changes on our own.
6887            throw new IllegalStateException("Shouldn't be here");
6888        }
6889
6890        @Override
6891        public boolean isCreating() {
6892            return mIsCreating;
6893        }
6894
6895        @Override
6896        public void setFixedSize(int width, int height) {
6897            throw new UnsupportedOperationException(
6898                    "Currently only support sizing from layout");
6899        }
6900
6901        @Override
6902        public void setKeepScreenOn(boolean screenOn) {
6903            ((RootViewSurfaceTaker)mView).setSurfaceKeepScreenOn(screenOn);
6904        }
6905    }
6906
6907    static class W extends IWindow.Stub {
6908        private final WeakReference<ViewRootImpl> mViewAncestor;
6909        private final IWindowSession mWindowSession;
6910
6911        W(ViewRootImpl viewAncestor) {
6912            mViewAncestor = new WeakReference<ViewRootImpl>(viewAncestor);
6913            mWindowSession = viewAncestor.mWindowSession;
6914        }
6915
6916        @Override
6917        public void resized(Rect frame, Rect overscanInsets, Rect contentInsets,
6918                Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
6919                Configuration newConfig, Rect backDropFrame, boolean forceLayout,
6920                boolean alwaysConsumeNavBar) {
6921            final ViewRootImpl viewAncestor = mViewAncestor.get();
6922            if (viewAncestor != null) {
6923                viewAncestor.dispatchResized(frame, overscanInsets, contentInsets,
6924                        visibleInsets, stableInsets, outsets, reportDraw, newConfig, backDropFrame,
6925                        forceLayout, alwaysConsumeNavBar);
6926            }
6927        }
6928
6929        @Override
6930        public void moved(int newX, int newY) {
6931            final ViewRootImpl viewAncestor = mViewAncestor.get();
6932            if (viewAncestor != null) {
6933                viewAncestor.dispatchMoved(newX, newY);
6934            }
6935        }
6936
6937        @Override
6938        public void dispatchAppVisibility(boolean visible) {
6939            final ViewRootImpl viewAncestor = mViewAncestor.get();
6940            if (viewAncestor != null) {
6941                viewAncestor.dispatchAppVisibility(visible);
6942            }
6943        }
6944
6945        @Override
6946        public void dispatchGetNewSurface() {
6947            final ViewRootImpl viewAncestor = mViewAncestor.get();
6948            if (viewAncestor != null) {
6949                viewAncestor.dispatchGetNewSurface();
6950            }
6951        }
6952
6953        @Override
6954        public void windowFocusChanged(boolean hasFocus, boolean inTouchMode) {
6955            final ViewRootImpl viewAncestor = mViewAncestor.get();
6956            if (viewAncestor != null) {
6957                viewAncestor.windowFocusChanged(hasFocus, inTouchMode);
6958            }
6959        }
6960
6961        private static int checkCallingPermission(String permission) {
6962            try {
6963                return ActivityManagerNative.getDefault().checkPermission(
6964                        permission, Binder.getCallingPid(), Binder.getCallingUid());
6965            } catch (RemoteException e) {
6966                return PackageManager.PERMISSION_DENIED;
6967            }
6968        }
6969
6970        @Override
6971        public void executeCommand(String command, String parameters, ParcelFileDescriptor out) {
6972            final ViewRootImpl viewAncestor = mViewAncestor.get();
6973            if (viewAncestor != null) {
6974                final View view = viewAncestor.mView;
6975                if (view != null) {
6976                    if (checkCallingPermission(Manifest.permission.DUMP) !=
6977                            PackageManager.PERMISSION_GRANTED) {
6978                        throw new SecurityException("Insufficient permissions to invoke"
6979                                + " executeCommand() from pid=" + Binder.getCallingPid()
6980                                + ", uid=" + Binder.getCallingUid());
6981                    }
6982
6983                    OutputStream clientStream = null;
6984                    try {
6985                        clientStream = new ParcelFileDescriptor.AutoCloseOutputStream(out);
6986                        ViewDebug.dispatchCommand(view, command, parameters, clientStream);
6987                    } catch (IOException e) {
6988                        e.printStackTrace();
6989                    } finally {
6990                        if (clientStream != null) {
6991                            try {
6992                                clientStream.close();
6993                            } catch (IOException e) {
6994                                e.printStackTrace();
6995                            }
6996                        }
6997                    }
6998                }
6999            }
7000        }
7001
7002        @Override
7003        public void closeSystemDialogs(String reason) {
7004            final ViewRootImpl viewAncestor = mViewAncestor.get();
7005            if (viewAncestor != null) {
7006                viewAncestor.dispatchCloseSystemDialogs(reason);
7007            }
7008        }
7009
7010        @Override
7011        public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
7012                boolean sync) {
7013            if (sync) {
7014                try {
7015                    mWindowSession.wallpaperOffsetsComplete(asBinder());
7016                } catch (RemoteException e) {
7017                }
7018            }
7019        }
7020
7021        @Override
7022        public void dispatchWallpaperCommand(String action, int x, int y,
7023                int z, Bundle extras, boolean sync) {
7024            if (sync) {
7025                try {
7026                    mWindowSession.wallpaperCommandComplete(asBinder(), null);
7027                } catch (RemoteException e) {
7028                }
7029            }
7030        }
7031
7032        /* Drag/drop */
7033        @Override
7034        public void dispatchDragEvent(DragEvent event) {
7035            final ViewRootImpl viewAncestor = mViewAncestor.get();
7036            if (viewAncestor != null) {
7037                viewAncestor.dispatchDragEvent(event);
7038            }
7039        }
7040
7041        @Override
7042        public void updatePointerIcon(float x, float y) {
7043            final ViewRootImpl viewAncestor = mViewAncestor.get();
7044            if (viewAncestor != null) {
7045                viewAncestor.updatePointerIcon(x, y);
7046            }
7047        }
7048
7049        @Override
7050        public void dispatchSystemUiVisibilityChanged(int seq, int globalVisibility,
7051                int localValue, int localChanges) {
7052            final ViewRootImpl viewAncestor = mViewAncestor.get();
7053            if (viewAncestor != null) {
7054                viewAncestor.dispatchSystemUiVisibilityChanged(seq, globalVisibility,
7055                        localValue, localChanges);
7056            }
7057        }
7058
7059        @Override
7060        public void dispatchWindowShown() {
7061            final ViewRootImpl viewAncestor = mViewAncestor.get();
7062            if (viewAncestor != null) {
7063                viewAncestor.dispatchWindowShown();
7064            }
7065        }
7066
7067        @Override
7068        public void requestAppKeyboardShortcuts(IResultReceiver receiver, int deviceId) {
7069            ViewRootImpl viewAncestor = mViewAncestor.get();
7070            if (viewAncestor != null) {
7071                viewAncestor.dispatchRequestKeyboardShortcuts(receiver, deviceId);
7072            }
7073        }
7074    }
7075
7076    public static final class CalledFromWrongThreadException extends AndroidRuntimeException {
7077        public CalledFromWrongThreadException(String msg) {
7078            super(msg);
7079        }
7080    }
7081
7082    static HandlerActionQueue getRunQueue() {
7083        HandlerActionQueue rq = sRunQueues.get();
7084        if (rq != null) {
7085            return rq;
7086        }
7087        rq = new HandlerActionQueue();
7088        sRunQueues.set(rq);
7089        return rq;
7090    }
7091
7092    /**
7093     * Start a drag resizing which will inform all listeners that a window resize is taking place.
7094     */
7095    private void startDragResizing(Rect initialBounds, boolean fullscreen, Rect systemInsets,
7096            Rect stableInsets, int resizeMode) {
7097        if (!mDragResizing) {
7098            mDragResizing = true;
7099            for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7100                mWindowCallbacks.get(i).onWindowDragResizeStart(initialBounds, fullscreen,
7101                        systemInsets, stableInsets, resizeMode);
7102            }
7103            mFullRedrawNeeded = true;
7104        }
7105    }
7106
7107    /**
7108     * End a drag resize which will inform all listeners that a window resize has ended.
7109     */
7110    private void endDragResizing() {
7111        if (mDragResizing) {
7112            mDragResizing = false;
7113            for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7114                mWindowCallbacks.get(i).onWindowDragResizeEnd();
7115            }
7116            mFullRedrawNeeded = true;
7117        }
7118    }
7119
7120    private boolean updateContentDrawBounds() {
7121        boolean updated = false;
7122        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7123            updated |= mWindowCallbacks.get(i).onContentDrawn(
7124                    mWindowAttributes.surfaceInsets.left,
7125                    mWindowAttributes.surfaceInsets.top,
7126                    mWidth, mHeight);
7127        }
7128        return updated | (mDragResizing && mReportNextDraw);
7129    }
7130
7131    private void requestDrawWindow() {
7132        if (mReportNextDraw) {
7133            mWindowDrawCountDown = new CountDownLatch(mWindowCallbacks.size());
7134        }
7135        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
7136            mWindowCallbacks.get(i).onRequestDraw(mReportNextDraw);
7137        }
7138    }
7139
7140    /**
7141     * Tells this instance that its corresponding activity has just relaunched. In this case, we
7142     * need to force a relayout of the window to make sure we get the correct bounds from window
7143     * manager.
7144     */
7145    public void reportActivityRelaunched() {
7146        mActivityRelaunched = true;
7147    }
7148
7149    /**
7150     * Class for managing the accessibility interaction connection
7151     * based on the global accessibility state.
7152     */
7153    final class AccessibilityInteractionConnectionManager
7154            implements AccessibilityStateChangeListener {
7155        @Override
7156        public void onAccessibilityStateChanged(boolean enabled) {
7157            if (enabled) {
7158                ensureConnection();
7159                if (mAttachInfo.mHasWindowFocus) {
7160                    mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
7161                    View focusedView = mView.findFocus();
7162                    if (focusedView != null && focusedView != mView) {
7163                        focusedView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
7164                    }
7165                }
7166            } else {
7167                ensureNoConnection();
7168                mHandler.obtainMessage(MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST).sendToTarget();
7169            }
7170        }
7171
7172        public void ensureConnection() {
7173            final boolean registered =
7174                    mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7175            if (!registered) {
7176                mAttachInfo.mAccessibilityWindowId =
7177                        mAccessibilityManager.addAccessibilityInteractionConnection(mWindow,
7178                                new AccessibilityInteractionConnection(ViewRootImpl.this));
7179            }
7180        }
7181
7182        public void ensureNoConnection() {
7183            final boolean registered =
7184                mAttachInfo.mAccessibilityWindowId != AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7185            if (registered) {
7186                mAttachInfo.mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID;
7187                mAccessibilityManager.removeAccessibilityInteractionConnection(mWindow);
7188            }
7189        }
7190    }
7191
7192    final class HighContrastTextManager implements HighTextContrastChangeListener {
7193        HighContrastTextManager() {
7194            mAttachInfo.mHighContrastText = mAccessibilityManager.isHighTextContrastEnabled();
7195        }
7196        @Override
7197        public void onHighTextContrastStateChanged(boolean enabled) {
7198            mAttachInfo.mHighContrastText = enabled;
7199
7200            // Destroy Displaylists so they can be recreated with high contrast recordings
7201            destroyHardwareResources();
7202
7203            // Schedule redraw, which will rerecord + redraw all text
7204            invalidate();
7205        }
7206    }
7207
7208    /**
7209     * This class is an interface this ViewAncestor provides to the
7210     * AccessibilityManagerService to the latter can interact with
7211     * the view hierarchy in this ViewAncestor.
7212     */
7213    static final class AccessibilityInteractionConnection
7214            extends IAccessibilityInteractionConnection.Stub {
7215        private final WeakReference<ViewRootImpl> mViewRootImpl;
7216
7217        AccessibilityInteractionConnection(ViewRootImpl viewRootImpl) {
7218            mViewRootImpl = new WeakReference<ViewRootImpl>(viewRootImpl);
7219        }
7220
7221        @Override
7222        public void findAccessibilityNodeInfoByAccessibilityId(long accessibilityNodeId,
7223                Region interactiveRegion, int interactionId,
7224                IAccessibilityInteractionConnectionCallback callback, int flags,
7225                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7226            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7227            if (viewRootImpl != null && viewRootImpl.mView != null) {
7228                viewRootImpl.getAccessibilityInteractionController()
7229                    .findAccessibilityNodeInfoByAccessibilityIdClientThread(accessibilityNodeId,
7230                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
7231                            interrogatingTid, spec);
7232            } else {
7233                // We cannot make the call and notify the caller so it does not wait.
7234                try {
7235                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7236                } catch (RemoteException re) {
7237                    /* best effort - ignore */
7238                }
7239            }
7240        }
7241
7242        @Override
7243        public void performAccessibilityAction(long accessibilityNodeId, int action,
7244                Bundle arguments, int interactionId,
7245                IAccessibilityInteractionConnectionCallback callback, int flags,
7246                int interrogatingPid, long interrogatingTid) {
7247            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7248            if (viewRootImpl != null && viewRootImpl.mView != null) {
7249                viewRootImpl.getAccessibilityInteractionController()
7250                    .performAccessibilityActionClientThread(accessibilityNodeId, action, arguments,
7251                            interactionId, callback, flags, interrogatingPid, interrogatingTid);
7252            } else {
7253                // We cannot make the call and notify the caller so it does not wait.
7254                try {
7255                    callback.setPerformAccessibilityActionResult(false, interactionId);
7256                } catch (RemoteException re) {
7257                    /* best effort - ignore */
7258                }
7259            }
7260        }
7261
7262        @Override
7263        public void findAccessibilityNodeInfosByViewId(long accessibilityNodeId,
7264                String viewId, Region interactiveRegion, int interactionId,
7265                IAccessibilityInteractionConnectionCallback callback, int flags,
7266                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7267            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7268            if (viewRootImpl != null && viewRootImpl.mView != null) {
7269                viewRootImpl.getAccessibilityInteractionController()
7270                    .findAccessibilityNodeInfosByViewIdClientThread(accessibilityNodeId,
7271                            viewId, interactiveRegion, interactionId, callback, flags,
7272                            interrogatingPid, interrogatingTid, spec);
7273            } else {
7274                // We cannot make the call and notify the caller so it does not wait.
7275                try {
7276                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7277                } catch (RemoteException re) {
7278                    /* best effort - ignore */
7279                }
7280            }
7281        }
7282
7283        @Override
7284        public void findAccessibilityNodeInfosByText(long accessibilityNodeId, String text,
7285                Region interactiveRegion, int interactionId,
7286                IAccessibilityInteractionConnectionCallback callback, int flags,
7287                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7288            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7289            if (viewRootImpl != null && viewRootImpl.mView != null) {
7290                viewRootImpl.getAccessibilityInteractionController()
7291                    .findAccessibilityNodeInfosByTextClientThread(accessibilityNodeId, text,
7292                            interactiveRegion, interactionId, callback, flags, interrogatingPid,
7293                            interrogatingTid, spec);
7294            } else {
7295                // We cannot make the call and notify the caller so it does not wait.
7296                try {
7297                    callback.setFindAccessibilityNodeInfosResult(null, interactionId);
7298                } catch (RemoteException re) {
7299                    /* best effort - ignore */
7300                }
7301            }
7302        }
7303
7304        @Override
7305        public void findFocus(long accessibilityNodeId, int focusType, Region interactiveRegion,
7306                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7307                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7308            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7309            if (viewRootImpl != null && viewRootImpl.mView != null) {
7310                viewRootImpl.getAccessibilityInteractionController()
7311                    .findFocusClientThread(accessibilityNodeId, focusType, interactiveRegion,
7312                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7313                            spec);
7314            } else {
7315                // We cannot make the call and notify the caller so it does not wait.
7316                try {
7317                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7318                } catch (RemoteException re) {
7319                    /* best effort - ignore */
7320                }
7321            }
7322        }
7323
7324        @Override
7325        public void focusSearch(long accessibilityNodeId, int direction, Region interactiveRegion,
7326                int interactionId, IAccessibilityInteractionConnectionCallback callback, int flags,
7327                int interrogatingPid, long interrogatingTid, MagnificationSpec spec) {
7328            ViewRootImpl viewRootImpl = mViewRootImpl.get();
7329            if (viewRootImpl != null && viewRootImpl.mView != null) {
7330                viewRootImpl.getAccessibilityInteractionController()
7331                    .focusSearchClientThread(accessibilityNodeId, direction, interactiveRegion,
7332                            interactionId, callback, flags, interrogatingPid, interrogatingTid,
7333                            spec);
7334            } else {
7335                // We cannot make the call and notify the caller so it does not wait.
7336                try {
7337                    callback.setFindAccessibilityNodeInfoResult(null, interactionId);
7338                } catch (RemoteException re) {
7339                    /* best effort - ignore */
7340                }
7341            }
7342        }
7343    }
7344
7345    private class SendWindowContentChangedAccessibilityEvent implements Runnable {
7346        private int mChangeTypes = 0;
7347
7348        public View mSource;
7349        public long mLastEventTimeMillis;
7350
7351        @Override
7352        public void run() {
7353            // The accessibility may be turned off while we were waiting so check again.
7354            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7355                mLastEventTimeMillis = SystemClock.uptimeMillis();
7356                AccessibilityEvent event = AccessibilityEvent.obtain();
7357                event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
7358                event.setContentChangeTypes(mChangeTypes);
7359                mSource.sendAccessibilityEventUnchecked(event);
7360            } else {
7361                mLastEventTimeMillis = 0;
7362            }
7363            // In any case reset to initial state.
7364            mSource.resetSubtreeAccessibilityStateChanged();
7365            mSource = null;
7366            mChangeTypes = 0;
7367        }
7368
7369        public void runOrPost(View source, int changeType) {
7370            if (mSource != null) {
7371                // If there is no common predecessor, then mSource points to
7372                // a removed view, hence in this case always prefer the source.
7373                View predecessor = getCommonPredecessor(mSource, source);
7374                mSource = (predecessor != null) ? predecessor : source;
7375                mChangeTypes |= changeType;
7376                return;
7377            }
7378            mSource = source;
7379            mChangeTypes = changeType;
7380            final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis;
7381            final long minEventIntevalMillis =
7382                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval();
7383            if (timeSinceLastMillis >= minEventIntevalMillis) {
7384                mSource.removeCallbacks(this);
7385                run();
7386            } else {
7387                mSource.postDelayed(this, minEventIntevalMillis - timeSinceLastMillis);
7388            }
7389        }
7390    }
7391}
7392