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