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