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