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