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