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