ViewRootImpl.java revision 2757128940c35d8007e1817b32e7128e2569ad6e
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.app.ActivityManagerNative;
30import android.content.ClipDescription;
31import android.content.ComponentCallbacks;
32import android.content.Context;
33import android.content.pm.PackageManager;
34import android.content.res.CompatibilityInfo;
35import android.content.res.Configuration;
36import android.content.res.Resources;
37import android.graphics.Canvas;
38import android.graphics.Matrix;
39import android.graphics.PixelFormat;
40import android.graphics.Point;
41import android.graphics.PointF;
42import android.graphics.PorterDuff;
43import android.graphics.Rect;
44import android.graphics.Region;
45import android.graphics.drawable.Drawable;
46import android.hardware.display.DisplayManager;
47import android.hardware.display.DisplayManager.DisplayListener;
48import android.hardware.input.InputManager;
49import android.media.AudioManager;
50import android.os.Binder;
51import android.os.Build;
52import android.os.Bundle;
53import android.os.Debug;
54import android.os.Handler;
55import android.os.Looper;
56import android.os.Message;
57import android.os.ParcelFileDescriptor;
58import android.os.Process;
59import android.os.RemoteException;
60import android.os.SystemClock;
61import android.os.SystemProperties;
62import android.os.Trace;
63import android.util.AndroidRuntimeException;
64import android.util.DisplayMetrics;
65import android.util.Log;
66import android.util.Slog;
67import android.util.TimeUtils;
68import android.util.TypedValue;
69import android.view.Surface.OutOfResourcesException;
70import android.view.View.AttachInfo;
71import android.view.View.MeasureSpec;
72import android.view.accessibility.AccessibilityEvent;
73import android.view.accessibility.AccessibilityManager;
74import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
75import android.view.accessibility.AccessibilityManager.HighTextContrastChangeListener;
76import android.view.accessibility.AccessibilityNodeInfo;
77import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
78import android.view.accessibility.AccessibilityNodeProvider;
79import android.view.accessibility.IAccessibilityInteractionConnection;
80import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
81import android.view.animation.AccelerateDecelerateInterpolator;
82import android.view.animation.Interpolator;
83import android.view.inputmethod.InputMethodManager;
84import android.widget.Scroller;
85
86import com.android.internal.R;
87import com.android.internal.annotations.GuardedBy;
88import com.android.internal.os.IResultReceiver;
89import com.android.internal.os.SomeArgs;
90import com.android.internal.policy.PhoneFallbackEventHandler;
91import com.android.internal.view.BaseSurfaceHolder;
92import com.android.internal.view.RootViewSurfaceTaker;
93
94import java.io.FileDescriptor;
95import java.io.IOException;
96import java.io.OutputStream;
97import java.io.PrintWriter;
98import java.lang.ref.WeakReference;
99import java.util.ArrayList;
100import java.util.HashSet;
101import java.util.concurrent.CountDownLatch;
102
103/**
104 * The top of a view hierarchy, implementing the needed protocol between View
105 * and the WindowManager.  This is for the most part an internal implementation
106 * detail of {@link WindowManagerGlobal}.
107 *
108 * {@hide}
109 */
110@SuppressWarnings({"EmptyCatchBlock", "PointlessBooleanExpression"})
111public final class ViewRootImpl implements ViewParent,
112        View.AttachInfo.Callbacks, ThreadedRenderer.HardwareDrawCallbacks {
113    private static final String TAG = "ViewRootImpl";
114    private static final boolean DBG = false;
115    private static final boolean LOCAL_LOGV = false;
116    /** @noinspection PointlessBooleanExpression*/
117    private static final boolean DEBUG_DRAW = false || LOCAL_LOGV;
118    private static final boolean DEBUG_LAYOUT = false || LOCAL_LOGV;
119    private static final boolean DEBUG_DIALOG = false || LOCAL_LOGV;
120    private static final boolean DEBUG_INPUT_RESIZE = false || LOCAL_LOGV;
121    private static final boolean DEBUG_ORIENTATION = false || LOCAL_LOGV;
122    private static final boolean DEBUG_TRACKBALL = false || LOCAL_LOGV;
123    private static final boolean DEBUG_IMF = false || LOCAL_LOGV;
124    private static final boolean DEBUG_CONFIGURATION = false || LOCAL_LOGV;
125    private static final boolean DEBUG_FPS = false;
126    private static final boolean DEBUG_INPUT_STAGES = false || LOCAL_LOGV;
127
128    /**
129     * Set to false if we do not want to use the multi threaded renderer. Note that by disabling
130     * this, WindowCallbacks will not fire.
131     */
132    private static final boolean USE_MT_RENDERER = true;
133
134    /**
135     * Set this system property to true to force the view hierarchy to render
136     * at 60 Hz. This can be used to measure the potential framerate.
137     */
138    private static final String PROPERTY_PROFILE_RENDERING = "viewroot.profile_rendering";
139
140    // properties used by emulator to determine display shape
141    public static final String PROPERTY_EMULATOR_WIN_OUTSET_BOTTOM_PX =
142            "ro.emu.win_outset_bottom_px";
143
144    /**
145     * Maximum time we allow the user to roll the trackball enough to generate
146     * a key event, before resetting the counters.
147     */
148    static final int MAX_TRACKBALL_DELAY = 250;
149
150    static final ThreadLocal<HandlerActionQueue> sRunQueues = new ThreadLocal<HandlerActionQueue>();
151
152    static final ArrayList<Runnable> sFirstDrawHandlers = new ArrayList();
153    static boolean sFirstDrawComplete = false;
154
155    static final ArrayList<ComponentCallbacks> sConfigCallbacks = new ArrayList();
156
157    /**
158     * This list must only be modified by the main thread, so a lock is only needed when changing
159     * the list or when accessing the list from a non-main thread.
160     */
161    @GuardedBy("mWindowCallbacks")
162    final ArrayList<WindowCallbacks> mWindowCallbacks = new ArrayList<>();
163    final Context mContext;
164    final IWindowSession mWindowSession;
165    final Display mDisplay;
166    final DisplayManager mDisplayManager;
167    final String mBasePackageName;
168
169    final int[] mTmpLocation = new int[2];
170
171    final TypedValue mTmpValue = new TypedValue();
172
173    final Thread mThread;
174
175    final WindowLeaked mLocation;
176
177    final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
178
179    final W mWindow;
180
181    final int mTargetSdkVersion;
182
183    int mSeq;
184
185    View mView;
186
187    View mAccessibilityFocusedHost;
188    AccessibilityNodeInfo mAccessibilityFocusedVirtualView;
189
190    // The view which captures mouse input, or null when no one is capturing.
191    View mCapturingView;
192
193    int mViewVisibility;
194    boolean mAppVisible = true;
195    // For recents to freeform transition we need to keep drawing after the app receives information
196    // that it became invisible. This will ignore that information and depend on the decor view
197    // visibility to control drawing. The decor view visibility will get adjusted when the app get
198    // stopped and that's when the app will stop drawing further frames.
199    private boolean mForceDecorViewVisibility = false;
200    int mOrigWindowType = -1;
201
202    /** Whether the window had focus during the most recent traversal. */
203    boolean mHadWindowFocus;
204
205    /**
206     * Whether the window lost focus during a previous traversal and has not
207     * yet gained it back. Used to determine whether a WINDOW_STATE_CHANGE
208     * accessibility events should be sent during traversal.
209     */
210    boolean mLostWindowFocus;
211
212    // Set to true if the owner of this window is in the stopped state,
213    // so the window should no longer be active.
214    boolean mStopped = false;
215
216    // Set to true if the owner of this window is in ambient mode,
217    // which means it won't receive input events.
218    boolean mIsAmbientMode = false;
219
220    // Set to true to stop input during an Activity Transition.
221    boolean mPausedForTransition = false;
222
223    boolean mLastInCompatMode = false;
224
225    SurfaceHolder.Callback2 mSurfaceHolderCallback;
226    BaseSurfaceHolder mSurfaceHolder;
227    boolean mIsCreating;
228    boolean mDrawingAllowed;
229
230    final Region mTransparentRegion;
231    final Region mPreviousTransparentRegion;
232
233    int mWidth;
234    int mHeight;
235    Rect mDirty;
236    boolean mIsAnimating;
237
238    private boolean mDragResizing;
239    private boolean mInvalidateRootRequested;
240    private int mResizeMode;
241    private int mCanvasOffsetX;
242    private int mCanvasOffsetY;
243    private boolean mActivityRelaunched;
244
245    CompatibilityInfo.Translator mTranslator;
246
247    final View.AttachInfo mAttachInfo;
248    InputChannel mInputChannel;
249    InputQueue.Callback mInputQueueCallback;
250    InputQueue mInputQueue;
251    FallbackEventHandler mFallbackEventHandler;
252    Choreographer mChoreographer;
253
254    final Rect mTempRect; // used in the transaction to not thrash the heap.
255    final Rect mVisRect; // used to retrieve visible rect of focused view.
256
257    boolean mTraversalScheduled;
258    int mTraversalBarrier;
259    boolean mWillDrawSoon;
260    /** Set to true while in performTraversals for detecting when die(true) is called from internal
261     * callbacks such as onMeasure, onPreDraw, onDraw and deferring doDie() until later. */
262    boolean mIsInTraversal;
263    boolean mApplyInsetsRequested;
264    boolean mLayoutRequested;
265    boolean mFirst;
266    boolean mReportNextDraw;
267    boolean mFullRedrawNeeded;
268    boolean mNewSurfaceNeeded;
269    boolean mHasHadWindowFocus;
270    boolean mLastWasImTarget;
271    boolean mForceNextWindowRelayout;
272    CountDownLatch mWindowDrawCountDown;
273
274    boolean mIsDrawing;
275    int mLastSystemUiVisibility;
276    int mClientWindowLayoutFlags;
277    boolean mLastOverscanRequested;
278
279    // Pool of queued input events.
280    private static final int MAX_QUEUED_INPUT_EVENT_POOL_SIZE = 10;
281    private QueuedInputEvent mQueuedInputEventPool;
282    private int mQueuedInputEventPoolSize;
283
284    /* Input event queue.
285     * Pending input events are input events waiting to be delivered to the input stages
286     * and handled by the application.
287     */
288    QueuedInputEvent mPendingInputEventHead;
289    QueuedInputEvent mPendingInputEventTail;
290    int mPendingInputEventCount;
291    boolean mProcessInputEventsScheduled;
292    boolean mUnbufferedInputDispatch;
293    String mPendingInputEventQueueLengthCounterName = "pq";
294
295    InputStage mFirstInputStage;
296    InputStage mFirstPostImeInputStage;
297    InputStage mSyntheticInputStage;
298
299    boolean mWindowAttributesChanged = false;
300    int mWindowAttributesChangesFlag = 0;
301
302    // These can be accessed by any thread, must be protected with a lock.
303    // Surface can never be reassigned or cleared (use Surface.clear()).
304    final Surface mSurface = new Surface();
305
306    boolean mAdded;
307    boolean mAddedTouchMode;
308
309    final DisplayAdjustments mDisplayAdjustments;
310
311    // These are accessed by multiple threads.
312    final Rect mWinFrame; // frame given by window manager.
313
314    final Rect mPendingOverscanInsets = new Rect();
315    final Rect mPendingVisibleInsets = new Rect();
316    final Rect mPendingStableInsets = new Rect();
317    final Rect mPendingContentInsets = new Rect();
318    final Rect mPendingOutsets = new Rect();
319    final Rect mPendingBackDropFrame = new Rect();
320    boolean mPendingAlwaysConsumeNavBar;
321    final ViewTreeObserver.InternalInsetsInfo mLastGivenInsets
322            = new ViewTreeObserver.InternalInsetsInfo();
323
324    final Rect mDispatchContentInsets = new Rect();
325    final Rect mDispatchStableInsets = new Rect();
326
327    private WindowInsets mLastWindowInsets;
328
329    final Configuration mLastConfiguration = new Configuration();
330    final Configuration mPendingConfiguration = new Configuration();
331
332    boolean mScrollMayChange;
333    int mSoftInputMode;
334    WeakReference<View> mLastScrolledFocus;
335    int mScrollY;
336    int mCurScrollY;
337    Scroller mScroller;
338    static final Interpolator mResizeInterpolator = new AccelerateDecelerateInterpolator();
339    private ArrayList<LayoutTransition> mPendingTransitions;
340
341    final ViewConfiguration mViewConfiguration;
342
343    /* Drag/drop */
344    ClipDescription mDragDescription;
345    View mCurrentDragView;
346    volatile Object mLocalDragState;
347    final PointF mDragPoint = new PointF();
348    final PointF mLastTouchPoint = new PointF();
349    int mLastTouchSource;
350
351    private boolean mProfileRendering;
352    private Choreographer.FrameCallback mRenderProfiler;
353    private boolean mRenderProfilingEnabled;
354
355    // Variables to track frames per second, enabled via DEBUG_FPS flag
356    private long mFpsStartTime = -1;
357    private long mFpsPrevTime = -1;
358    private int mFpsNumFrames;
359
360    private int mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
361    private PointerIcon mCustomPointerIcon = null;
362
363    /**
364     * see {@link #playSoundEffect(int)}
365     */
366    AudioManager mAudioManager;
367
368    final AccessibilityManager mAccessibilityManager;
369
370    AccessibilityInteractionController mAccessibilityInteractionController;
371
372    AccessibilityInteractionConnectionManager mAccessibilityInteractionConnectionManager;
373    HighContrastTextManager mHighContrastTextManager;
374
375    SendWindowContentChangedAccessibilityEvent mSendWindowContentChangedAccessibilityEvent;
376
377    HashSet<View> mTempHashSet;
378
379    private final int mDensity;
380    private final int mNoncompatDensity;
381
382    private boolean mInLayout = false;
383    ArrayList<View> mLayoutRequesters = new ArrayList<View>();
384    boolean mHandlingLayoutInLayoutRequest = false;
385
386    private int mViewLayoutDirectionInitial;
387
388    /** Set to true once doDie() has been called. */
389    private boolean mRemoved;
390
391    private boolean mNeedsHwRendererSetup;
392
393    /**
394     * Consistency verifier for debugging purposes.
395     */
396    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
397            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
398                    new InputEventConsistencyVerifier(this, 0) : null;
399
400    static final class SystemUiVisibilityInfo {
401        int seq;
402        int globalVisibility;
403        int localValue;
404        int localChanges;
405    }
406
407    private String mTag = TAG;
408
409    public ViewRootImpl(Context context, Display display) {
410        mContext = context;
411        mWindowSession = WindowManagerGlobal.getWindowSession();
412        mDisplay = display;
413        mBasePackageName = context.getBasePackageName();
414
415        mDisplayAdjustments = display.getDisplayAdjustments();
416
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 ((mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0
566                        && (attrs.flags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) == 0) {
567                    Slog.d(mTag, "setView: FLAG_KEEP_SCREEN_ON changed from true to false!!!");
568                }
569                // Keep track of the actual window flags supplied by the client.
570                mClientWindowLayoutFlags = attrs.flags;
571
572                setAccessibilityFocus(null, null);
573
574                if (view instanceof RootViewSurfaceTaker) {
575                    mSurfaceHolderCallback =
576                            ((RootViewSurfaceTaker)view).willYouTakeTheSurface();
577                    if (mSurfaceHolderCallback != null) {
578                        mSurfaceHolder = new TakenSurfaceHolder();
579                        mSurfaceHolder.setFormat(PixelFormat.UNKNOWN);
580                    }
581                }
582
583                // Compute surface insets required to draw at specified Z value.
584                // TODO: Use real shadow insets for a constant max Z.
585                if (!attrs.hasManualSurfaceInsets) {
586                    attrs.setSurfaceInsets(view, false /*manual*/, true /*preservePrevious*/);
587                }
588
589                CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
590                mTranslator = compatibilityInfo.getTranslator();
591
592                // If the application owns the surface, don't enable hardware acceleration
593                if (mSurfaceHolder == null) {
594                    enableHardwareAcceleration(attrs);
595                }
596
597                boolean restore = false;
598                if (mTranslator != null) {
599                    mSurface.setCompatibilityTranslator(mTranslator);
600                    restore = true;
601                    attrs.backup();
602                    mTranslator.translateWindowLayout(attrs);
603                }
604                if (DEBUG_LAYOUT) Log.d(mTag, "WindowLayout in setView:" + attrs);
605
606                if (!compatibilityInfo.supportsScreen()) {
607                    attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
608                    mLastInCompatMode = true;
609                }
610
611                mSoftInputMode = attrs.softInputMode;
612                mWindowAttributesChanged = true;
613                mWindowAttributesChangesFlag = WindowManager.LayoutParams.EVERYTHING_CHANGED;
614                mAttachInfo.mRootView = view;
615                mAttachInfo.mScalingRequired = mTranslator != null;
616                mAttachInfo.mApplicationScale =
617                        mTranslator == null ? 1.0f : mTranslator.applicationScale;
618                if (panelParentView != null) {
619                    mAttachInfo.mPanelParentWindowToken
620                            = panelParentView.getApplicationWindowToken();
621                }
622                mAdded = true;
623                int res; /* = WindowManagerImpl.ADD_OKAY; */
624
625                // Schedule the first layout -before- adding to the window
626                // manager, to make sure we do the relayout before receiving
627                // any other events from the system.
628                requestLayout();
629                if ((mWindowAttributes.inputFeatures
630                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
631                    mInputChannel = new InputChannel();
632                }
633                mForceDecorViewVisibility = (mWindowAttributes.privateFlags
634                        & PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY) != 0;
635                try {
636                    mOrigWindowType = mWindowAttributes.type;
637                    mAttachInfo.mRecomputeGlobalAttributes = true;
638                    collectViewAttributes();
639                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
640                            getHostVisibility(), mDisplay.getDisplayId(),
641                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
642                            mAttachInfo.mOutsets, mInputChannel);
643                } catch (RemoteException e) {
644                    mAdded = false;
645                    mView = null;
646                    mAttachInfo.mRootView = null;
647                    mInputChannel = null;
648                    mFallbackEventHandler.setView(null);
649                    unscheduleTraversals();
650                    setAccessibilityFocus(null, null);
651                    throw new RuntimeException("Adding window failed", e);
652                } finally {
653                    if (restore) {
654                        attrs.restore();
655                    }
656                }
657
658                if (mTranslator != null) {
659                    mTranslator.translateRectInScreenToAppWindow(mAttachInfo.mContentInsets);
660                }
661                mPendingOverscanInsets.set(0, 0, 0, 0);
662                mPendingContentInsets.set(mAttachInfo.mContentInsets);
663                mPendingStableInsets.set(mAttachInfo.mStableInsets);
664                mPendingVisibleInsets.set(0, 0, 0, 0);
665                mAttachInfo.mAlwaysConsumeNavBar =
666                        (res & WindowManagerGlobal.ADD_FLAG_ALWAYS_CONSUME_NAV_BAR) != 0;
667                mPendingAlwaysConsumeNavBar = mAttachInfo.mAlwaysConsumeNavBar;
668                if (DEBUG_LAYOUT) Log.v(mTag, "Added window " + mWindow);
669                if (res < WindowManagerGlobal.ADD_OKAY) {
670                    mAttachInfo.mRootView = null;
671                    mAdded = false;
672                    mFallbackEventHandler.setView(null);
673                    unscheduleTraversals();
674                    setAccessibilityFocus(null, null);
675                    switch (res) {
676                        case WindowManagerGlobal.ADD_BAD_APP_TOKEN:
677                        case WindowManagerGlobal.ADD_BAD_SUBWINDOW_TOKEN:
678                            throw new WindowManager.BadTokenException(
679                                    "Unable to add window -- token " + attrs.token
680                                    + " is not valid; is your activity running?");
681                        case WindowManagerGlobal.ADD_NOT_APP_TOKEN:
682                            throw new WindowManager.BadTokenException(
683                                    "Unable to add window -- token " + attrs.token
684                                    + " is not for an application");
685                        case WindowManagerGlobal.ADD_APP_EXITING:
686                            throw new WindowManager.BadTokenException(
687                                    "Unable to add window -- app for token " + attrs.token
688                                    + " is exiting");
689                        case WindowManagerGlobal.ADD_DUPLICATE_ADD:
690                            throw new WindowManager.BadTokenException(
691                                    "Unable to add window -- window " + mWindow
692                                    + " has already been added");
693                        case WindowManagerGlobal.ADD_STARTING_NOT_NEEDED:
694                            // Silently ignore -- we would have just removed it
695                            // right away, anyway.
696                            return;
697                        case WindowManagerGlobal.ADD_MULTIPLE_SINGLETON:
698                            throw new WindowManager.BadTokenException("Unable to add window "
699                                    + mWindow + " -- another window of type "
700                                    + mWindowAttributes.type + " already exists");
701                        case WindowManagerGlobal.ADD_PERMISSION_DENIED:
702                            throw new WindowManager.BadTokenException("Unable to add window "
703                                    + mWindow + " -- permission denied for window type "
704                                    + mWindowAttributes.type);
705                        case WindowManagerGlobal.ADD_INVALID_DISPLAY:
706                            throw new WindowManager.InvalidDisplayException("Unable to add window "
707                                    + mWindow + " -- the specified display can not be found");
708                        case WindowManagerGlobal.ADD_INVALID_TYPE:
709                            throw new WindowManager.InvalidDisplayException("Unable to add window "
710                                    + mWindow + " -- the specified window type "
711                                    + mWindowAttributes.type + " is not valid");
712                    }
713                    throw new RuntimeException(
714                            "Unable to add window -- unknown error code " + res);
715                }
716
717                if (view instanceof RootViewSurfaceTaker) {
718                    mInputQueueCallback =
719                        ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();
720                }
721                if (mInputChannel != null) {
722                    if (mInputQueueCallback != null) {
723                        mInputQueue = new InputQueue();
724                        mInputQueueCallback.onInputQueueCreated(mInputQueue);
725                    }
726                    mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
727                            Looper.myLooper());
728                }
729
730                view.assignParent(this);
731                mAddedTouchMode = (res & WindowManagerGlobal.ADD_FLAG_IN_TOUCH_MODE) != 0;
732                mAppVisible = (res & WindowManagerGlobal.ADD_FLAG_APP_VISIBLE) != 0;
733
734                if (mAccessibilityManager.isEnabled()) {
735                    mAccessibilityInteractionConnectionManager.ensureConnection();
736                }
737
738                if (view.getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
739                    view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
740                }
741
742                // Set up the input pipeline.
743                CharSequence counterSuffix = attrs.getTitle();
744                mSyntheticInputStage = new SyntheticInputStage();
745                InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
746                InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
747                        "aq:native-post-ime:" + counterSuffix);
748                InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
749                InputStage imeStage = new ImeInputStage(earlyPostImeStage,
750                        "aq:ime:" + counterSuffix);
751                InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
752                InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
753                        "aq:native-pre-ime:" + counterSuffix);
754
755                mFirstInputStage = nativePreImeStage;
756                mFirstPostImeInputStage = earlyPostImeStage;
757                mPendingInputEventQueueLengthCounterName = "aq:pending:" + counterSuffix;
758            }
759        }
760    }
761
762    private void setTag() {
763        final String[] split = mWindowAttributes.getTitle().toString().split("\\.");
764        if (split.length > 0) {
765            mTag = TAG + "[" + split[split.length - 1] + "]";
766        }
767    }
768
769    /** Whether the window is in local focus mode or not */
770    private boolean isInLocalFocusMode() {
771        return (mWindowAttributes.flags & WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE) != 0;
772    }
773
774    public int getWindowFlags() {
775        return mWindowAttributes.flags;
776    }
777
778    public int getDisplayId() {
779        return mDisplay.getDisplayId();
780    }
781
782    public CharSequence getTitle() {
783        return mWindowAttributes.getTitle();
784    }
785
786    void destroyHardwareResources() {
787        if (mAttachInfo.mHardwareRenderer != null) {
788            mAttachInfo.mHardwareRenderer.destroyHardwareResources(mView);
789            mAttachInfo.mHardwareRenderer.destroy();
790        }
791    }
792
793    public void detachFunctor(long functor) {
794        if (mAttachInfo.mHardwareRenderer != null) {
795            // Fence so that any pending invokeFunctor() messages will be processed
796            // before we return from detachFunctor.
797            mAttachInfo.mHardwareRenderer.stopDrawing();
798        }
799    }
800
801    /**
802     * Schedules the functor for execution in either kModeProcess or
803     * kModeProcessNoContext, depending on whether or not there is an EGLContext.
804     *
805     * @param functor The native functor to invoke
806     * @param waitForCompletion If true, this will not return until the functor
807     *                          has invoked. If false, the functor may be invoked
808     *                          asynchronously.
809     */
810    public static void invokeFunctor(long functor, boolean waitForCompletion) {
811        ThreadedRenderer.invokeFunctor(functor, waitForCompletion);
812    }
813
814    public void registerAnimatingRenderNode(RenderNode animator) {
815        if (mAttachInfo.mHardwareRenderer != null) {
816            mAttachInfo.mHardwareRenderer.registerAnimatingRenderNode(animator);
817        } else {
818            if (mAttachInfo.mPendingAnimatingRenderNodes == null) {
819                mAttachInfo.mPendingAnimatingRenderNodes = new ArrayList<RenderNode>();
820            }
821            mAttachInfo.mPendingAnimatingRenderNodes.add(animator);
822        }
823    }
824
825    private void enableHardwareAcceleration(WindowManager.LayoutParams attrs) {
826        mAttachInfo.mHardwareAccelerated = false;
827        mAttachInfo.mHardwareAccelerationRequested = false;
828
829        // Don't enable hardware acceleration when the application is in compatibility mode
830        if (mTranslator != null) return;
831
832        // Try to enable hardware acceleration if requested
833        final boolean hardwareAccelerated =
834                (attrs.flags & WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
835
836        if (hardwareAccelerated) {
837            if (!ThreadedRenderer.isAvailable()) {
838                return;
839            }
840
841            // Persistent processes (including the system) should not do
842            // accelerated rendering on low-end devices.  In that case,
843            // sRendererDisabled will be set.  In addition, the system process
844            // itself should never do accelerated rendering.  In that case, both
845            // sRendererDisabled and sSystemRendererDisabled are set.  When
846            // sSystemRendererDisabled is set, PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED
847            // can be used by code on the system process to escape that and enable
848            // HW accelerated drawing.  (This is basically for the lock screen.)
849
850            final boolean fakeHwAccelerated = (attrs.privateFlags &
851                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED) != 0;
852            final boolean forceHwAccelerated = (attrs.privateFlags &
853                    WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED) != 0;
854
855            if (fakeHwAccelerated) {
856                // This is exclusively for the preview windows the window manager
857                // shows for launching applications, so they will look more like
858                // the app being launched.
859                mAttachInfo.mHardwareAccelerationRequested = true;
860            } else if (!ThreadedRenderer.sRendererDisabled
861                    || (ThreadedRenderer.sSystemRendererDisabled && forceHwAccelerated)) {
862                if (mAttachInfo.mHardwareRenderer != null) {
863                    mAttachInfo.mHardwareRenderer.destroy();
864                }
865
866                final Rect insets = attrs.surfaceInsets;
867                final boolean hasSurfaceInsets = insets.left != 0 || insets.right != 0
868                        || insets.top != 0 || insets.bottom != 0;
869                final boolean translucent = attrs.format != PixelFormat.OPAQUE || hasSurfaceInsets;
870                mAttachInfo.mHardwareRenderer = ThreadedRenderer.create(mContext, translucent);
871                if (mAttachInfo.mHardwareRenderer != null) {
872                    mAttachInfo.mHardwareRenderer.setName(attrs.getTitle().toString());
873                    mAttachInfo.mHardwareAccelerated =
874                            mAttachInfo.mHardwareAccelerationRequested = true;
875                }
876            }
877        }
878    }
879
880    public View getView() {
881        return mView;
882    }
883
884    final WindowLeaked getLocation() {
885        return mLocation;
886    }
887
888    void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
889        synchronized (this) {
890            final int oldInsetLeft = mWindowAttributes.surfaceInsets.left;
891            final int oldInsetTop = mWindowAttributes.surfaceInsets.top;
892            final int oldInsetRight = mWindowAttributes.surfaceInsets.right;
893            final int oldInsetBottom = mWindowAttributes.surfaceInsets.bottom;
894            final int oldSoftInputMode = mWindowAttributes.softInputMode;
895            final boolean oldHasManualSurfaceInsets = mWindowAttributes.hasManualSurfaceInsets;
896            if ((mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0
897                    && (attrs.flags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) == 0) {
898                Slog.d(mTag, "setLayoutParams: FLAG_KEEP_SCREEN_ON from true to false!!!");
899            }
900
901            // Keep track of the actual window flags supplied by the client.
902            mClientWindowLayoutFlags = attrs.flags;
903
904            // Preserve compatible window flag if exists.
905            final int compatibleWindowFlag = mWindowAttributes.privateFlags
906                    & WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
907
908            // Transfer over system UI visibility values as they carry current state.
909            attrs.systemUiVisibility = mWindowAttributes.systemUiVisibility;
910            attrs.subtreeSystemUiVisibility = mWindowAttributes.subtreeSystemUiVisibility;
911
912            mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
913            if ((mWindowAttributesChangesFlag
914                    & WindowManager.LayoutParams.TRANSLUCENT_FLAGS_CHANGED) != 0) {
915                // Recompute system ui visibility.
916                mAttachInfo.mRecomputeGlobalAttributes = true;
917            }
918            if ((mWindowAttributesChangesFlag
919                    & WindowManager.LayoutParams.LAYOUT_CHANGED) != 0) {
920                // Request to update light center.
921                mAttachInfo.mNeedsUpdateLightCenter = true;
922            }
923            if (mWindowAttributes.packageName == null) {
924                mWindowAttributes.packageName = mBasePackageName;
925            }
926            mWindowAttributes.privateFlags |= compatibleWindowFlag;
927
928            if (mWindowAttributes.preservePreviousSurfaceInsets) {
929                // Restore old surface insets.
930                mWindowAttributes.surfaceInsets.set(
931                        oldInsetLeft, oldInsetTop, oldInsetRight, oldInsetBottom);
932                mWindowAttributes.hasManualSurfaceInsets = oldHasManualSurfaceInsets;
933            } else if (mWindowAttributes.surfaceInsets.left != oldInsetLeft
934                    || mWindowAttributes.surfaceInsets.top != oldInsetTop
935                    || mWindowAttributes.surfaceInsets.right != oldInsetRight
936                    || mWindowAttributes.surfaceInsets.bottom != oldInsetBottom) {
937                mNeedsHwRendererSetup = true;
938            }
939
940            applyKeepScreenOnFlag(mWindowAttributes);
941
942            if (newView) {
943                mSoftInputMode = attrs.softInputMode;
944                requestLayout();
945            }
946
947            // Don't lose the mode we last auto-computed.
948            if ((attrs.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
949                    == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
950                mWindowAttributes.softInputMode = (mWindowAttributes.softInputMode
951                        & ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST)
952                        | (oldSoftInputMode & WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
953            }
954
955            mWindowAttributesChanged = true;
956            scheduleTraversals();
957        }
958    }
959
960    void handleAppVisibility(boolean visible) {
961        if (mAppVisible != visible) {
962            mAppVisible = visible;
963            scheduleTraversals();
964            if (!mAppVisible) {
965                WindowManagerGlobal.trimForeground();
966            }
967        }
968    }
969
970    void handleGetNewSurface() {
971        mNewSurfaceNeeded = true;
972        mFullRedrawNeeded = true;
973        scheduleTraversals();
974    }
975
976    private final DisplayListener mDisplayListener = new DisplayListener() {
977        @Override
978        public void onDisplayChanged(int displayId) {
979            if (mView != null && mDisplay.getDisplayId() == displayId) {
980                final int oldDisplayState = mAttachInfo.mDisplayState;
981                final int newDisplayState = mDisplay.getState();
982                if (oldDisplayState != newDisplayState) {
983                    mAttachInfo.mDisplayState = newDisplayState;
984                    pokeDrawLockIfNeeded();
985                    if (oldDisplayState != Display.STATE_UNKNOWN) {
986                        final int oldScreenState = toViewScreenState(oldDisplayState);
987                        final int newScreenState = toViewScreenState(newDisplayState);
988                        if (oldScreenState != newScreenState) {
989                            mView.dispatchScreenStateChanged(newScreenState);
990                        }
991                        if (oldDisplayState == Display.STATE_OFF) {
992                            // Draw was suppressed so we need to for it to happen here.
993                            mFullRedrawNeeded = true;
994                            scheduleTraversals();
995                        }
996                    }
997                }
998            }
999        }
1000
1001        @Override
1002        public void onDisplayRemoved(int displayId) {
1003        }
1004
1005        @Override
1006        public void onDisplayAdded(int displayId) {
1007        }
1008
1009        private int toViewScreenState(int displayState) {
1010            return displayState == Display.STATE_OFF ?
1011                    View.SCREEN_STATE_OFF : View.SCREEN_STATE_ON;
1012        }
1013    };
1014
1015    void pokeDrawLockIfNeeded() {
1016        final int displayState = mAttachInfo.mDisplayState;
1017        if (mView != null && mAdded && mTraversalScheduled
1018                && (displayState == Display.STATE_DOZE
1019                        || displayState == Display.STATE_DOZE_SUSPEND)) {
1020            try {
1021                mWindowSession.pokeDrawLock(mWindow);
1022            } catch (RemoteException ex) {
1023                // System server died, oh well.
1024            }
1025        }
1026    }
1027
1028    @Override
1029    public void requestFitSystemWindows() {
1030        checkThread();
1031        mApplyInsetsRequested = true;
1032        scheduleTraversals();
1033    }
1034
1035    @Override
1036    public void requestLayout() {
1037        if (!mHandlingLayoutInLayoutRequest) {
1038            checkThread();
1039            mLayoutRequested = true;
1040            scheduleTraversals();
1041        }
1042    }
1043
1044    @Override
1045    public boolean isLayoutRequested() {
1046        return mLayoutRequested;
1047    }
1048
1049    void invalidate() {
1050        mDirty.set(0, 0, mWidth, mHeight);
1051        if (!mWillDrawSoon) {
1052            scheduleTraversals();
1053        }
1054    }
1055
1056    void invalidateWorld(View view) {
1057        view.invalidate();
1058        if (view instanceof ViewGroup) {
1059            ViewGroup parent = (ViewGroup) view;
1060            for (int i = 0; i < parent.getChildCount(); i++) {
1061                invalidateWorld(parent.getChildAt(i));
1062            }
1063        }
1064    }
1065
1066    @Override
1067    public void invalidateChild(View child, Rect dirty) {
1068        invalidateChildInParent(null, dirty);
1069    }
1070
1071    @Override
1072    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
1073        checkThread();
1074        if (DEBUG_DRAW) Log.v(mTag, "Invalidate child: " + dirty);
1075
1076        if (dirty == null) {
1077            invalidate();
1078            return null;
1079        } else if (dirty.isEmpty() && !mIsAnimating) {
1080            return null;
1081        }
1082
1083        if (mCurScrollY != 0 || mTranslator != null) {
1084            mTempRect.set(dirty);
1085            dirty = mTempRect;
1086            if (mCurScrollY != 0) {
1087                dirty.offset(0, -mCurScrollY);
1088            }
1089            if (mTranslator != null) {
1090                mTranslator.translateRectInAppWindowToScreen(dirty);
1091            }
1092            if (mAttachInfo.mScalingRequired) {
1093                dirty.inset(-1, -1);
1094            }
1095        }
1096
1097        invalidateRectOnScreen(dirty);
1098
1099        return null;
1100    }
1101
1102    private void invalidateRectOnScreen(Rect dirty) {
1103        final Rect localDirty = mDirty;
1104        if (!localDirty.isEmpty() && !localDirty.contains(dirty)) {
1105            mAttachInfo.mSetIgnoreDirtyState = true;
1106            mAttachInfo.mIgnoreDirtyState = true;
1107        }
1108
1109        // Add the new dirty rect to the current one
1110        localDirty.union(dirty.left, dirty.top, dirty.right, dirty.bottom);
1111        // Intersect with the bounds of the window to skip
1112        // updates that lie outside of the visible region
1113        final float appScale = mAttachInfo.mApplicationScale;
1114        final boolean intersected = localDirty.intersect(0, 0,
1115                (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
1116        if (!intersected) {
1117            localDirty.setEmpty();
1118        }
1119        if (!mWillDrawSoon && (intersected || mIsAnimating)) {
1120            scheduleTraversals();
1121        }
1122    }
1123
1124    public void setIsAmbientMode(boolean ambient) {
1125        mIsAmbientMode = ambient;
1126    }
1127
1128    void setWindowStopped(boolean stopped) {
1129        if (mStopped != stopped) {
1130            mStopped = stopped;
1131            final ThreadedRenderer renderer = mAttachInfo.mHardwareRenderer;
1132            if (renderer != null) {
1133                if (DEBUG_DRAW) Log.d(mTag, "WindowStopped on " + getTitle() + " set to " + mStopped);
1134                renderer.setStopped(mStopped);
1135            }
1136            if (!mStopped) {
1137                scheduleTraversals();
1138            } else {
1139                if (renderer != null) {
1140                    renderer.destroyHardwareResources(mView);
1141                }
1142            }
1143        }
1144    }
1145
1146    /**
1147     * Block the input events during an Activity Transition. The KEYCODE_BACK event is allowed
1148     * through to allow quick reversal of the Activity Transition.
1149     *
1150     * @param paused true to pause, false to resume.
1151     */
1152    public void setPausedForTransition(boolean paused) {
1153        mPausedForTransition = paused;
1154    }
1155
1156    @Override
1157    public ViewParent getParent() {
1158        return null;
1159    }
1160
1161    @Override
1162    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
1163        if (child != mView) {
1164            throw new RuntimeException("child is not mine, honest!");
1165        }
1166        // Note: don't apply scroll offset, because we want to know its
1167        // visibility in the virtual canvas being given to the view hierarchy.
1168        return r.intersect(0, 0, mWidth, mHeight);
1169    }
1170
1171    @Override
1172    public void bringChildToFront(View child) {
1173    }
1174
1175    int getHostVisibility() {
1176        return (mAppVisible || mForceDecorViewVisibility) ? mView.getVisibility() : View.GONE;
1177    }
1178
1179    /**
1180     * Add LayoutTransition to the list of transitions to be started in the next traversal.
1181     * This list will be cleared after the transitions on the list are start()'ed. These
1182     * transitionsa re added by LayoutTransition itself when it sets up animations. The setup
1183     * happens during the layout phase of traversal, which we want to complete before any of the
1184     * animations are started (because those animations may side-effect properties that layout
1185     * depends upon, like the bounding rectangles of the affected views). So we add the transition
1186     * to the list and it is started just prior to starting the drawing phase of traversal.
1187     *
1188     * @param transition The LayoutTransition to be started on the next traversal.
1189     *
1190     * @hide
1191     */
1192    public void requestTransitionStart(LayoutTransition transition) {
1193        if (mPendingTransitions == null || !mPendingTransitions.contains(transition)) {
1194            if (mPendingTransitions == null) {
1195                 mPendingTransitions = new ArrayList<LayoutTransition>();
1196            }
1197            mPendingTransitions.add(transition);
1198        }
1199    }
1200
1201    /**
1202     * Notifies the HardwareRenderer that a new frame will be coming soon.
1203     * Currently only {@link ThreadedRenderer} cares about this, and uses
1204     * this knowledge to adjust the scheduling of off-thread animations
1205     */
1206    void notifyRendererOfFramePending() {
1207        if (mAttachInfo.mHardwareRenderer != null) {
1208            mAttachInfo.mHardwareRenderer.notifyFramePending();
1209        }
1210    }
1211
1212    void scheduleTraversals() {
1213        if (!mTraversalScheduled) {
1214            mTraversalScheduled = true;
1215            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
1216            mChoreographer.postCallback(
1217                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1218            if (!mUnbufferedInputDispatch) {
1219                scheduleConsumeBatchedInput();
1220            }
1221            notifyRendererOfFramePending();
1222            pokeDrawLockIfNeeded();
1223        }
1224    }
1225
1226    void unscheduleTraversals() {
1227        if (mTraversalScheduled) {
1228            mTraversalScheduled = false;
1229            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1230            mChoreographer.removeCallbacks(
1231                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
1232        }
1233    }
1234
1235    void doTraversal() {
1236        if (mTraversalScheduled) {
1237            mTraversalScheduled = false;
1238            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
1239
1240            if (mProfile) {
1241                Debug.startMethodTracing("ViewAncestor");
1242            }
1243
1244            performTraversals();
1245
1246            if (mProfile) {
1247                Debug.stopMethodTracing();
1248                mProfile = false;
1249            }
1250        }
1251    }
1252
1253    private void applyKeepScreenOnFlag(WindowManager.LayoutParams params) {
1254        // Update window's global keep screen on flag: if a view has requested
1255        // that the screen be kept on, then it is always set; otherwise, it is
1256        // set to whatever the client last requested for the global state.
1257        if (mAttachInfo.mKeepScreenOn) {
1258            params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
1259        } else {
1260            params.flags = (params.flags&~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
1261                    | (mClientWindowLayoutFlags&WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1262        }
1263    }
1264
1265    private boolean collectViewAttributes() {
1266        if (mAttachInfo.mRecomputeGlobalAttributes) {
1267            //Log.i(mTag, "Computing view hierarchy attributes!");
1268            mAttachInfo.mRecomputeGlobalAttributes = false;
1269            boolean oldScreenOn = mAttachInfo.mKeepScreenOn;
1270            mAttachInfo.mKeepScreenOn = false;
1271            mAttachInfo.mSystemUiVisibility = 0;
1272            mAttachInfo.mHasSystemUiListeners = false;
1273            mView.dispatchCollectViewAttributes(mAttachInfo, 0);
1274            mAttachInfo.mSystemUiVisibility &= ~mAttachInfo.mDisabledSystemUiVisibility;
1275            WindowManager.LayoutParams params = mWindowAttributes;
1276            mAttachInfo.mSystemUiVisibility |= getImpliedSystemUiVisibility(params);
1277            if (mAttachInfo.mKeepScreenOn != oldScreenOn
1278                    || mAttachInfo.mSystemUiVisibility != params.subtreeSystemUiVisibility
1279                    || mAttachInfo.mHasSystemUiListeners != params.hasSystemUiListeners) {
1280                applyKeepScreenOnFlag(params);
1281                params.subtreeSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1282                params.hasSystemUiListeners = mAttachInfo.mHasSystemUiListeners;
1283                mView.dispatchWindowSystemUiVisiblityChanged(mAttachInfo.mSystemUiVisibility);
1284                return true;
1285            }
1286        }
1287        return false;
1288    }
1289
1290    private int getImpliedSystemUiVisibility(WindowManager.LayoutParams params) {
1291        int vis = 0;
1292        // Translucent decor window flags imply stable system ui visibility.
1293        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) != 0) {
1294            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
1295        }
1296        if ((params.flags & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) != 0) {
1297            vis |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
1298        }
1299        return vis;
1300    }
1301
1302    private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
1303            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
1304        int childWidthMeasureSpec;
1305        int childHeightMeasureSpec;
1306        boolean windowSizeMayChange = false;
1307
1308        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) Log.v(mTag,
1309                "Measuring " + host + " in display " + desiredWindowWidth
1310                + "x" + desiredWindowHeight + "...");
1311
1312        boolean goodMeasure = false;
1313        if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
1314            // On large screens, we don't want to allow dialogs to just
1315            // stretch to fill the entire width of the screen to display
1316            // one line of text.  First try doing the layout at a smaller
1317            // size to see if it will fit.
1318            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
1319            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
1320            int baseSize = 0;
1321            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
1322                baseSize = (int)mTmpValue.getDimension(packageMetrics);
1323            }
1324            if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": baseSize=" + baseSize
1325                    + ", desiredWindowWidth=" + desiredWindowWidth);
1326            if (baseSize != 0 && desiredWindowWidth > baseSize) {
1327                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1328                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1329                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1330                if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
1331                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight()
1332                        + ") from width spec: " + MeasureSpec.toString(childWidthMeasureSpec)
1333                        + " and height spec: " + MeasureSpec.toString(childHeightMeasureSpec));
1334                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1335                    goodMeasure = true;
1336                } else {
1337                    // Didn't fit in that size... try expanding a bit.
1338                    baseSize = (baseSize+desiredWindowWidth)/2;
1339                    if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": next baseSize="
1340                            + baseSize);
1341                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
1342                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1343                    if (DEBUG_DIALOG) Log.v(mTag, "Window " + mView + ": measured ("
1344                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
1345                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
1346                        if (DEBUG_DIALOG) Log.v(mTag, "Good!");
1347                        goodMeasure = true;
1348                    }
1349                }
1350            }
1351        }
1352
1353        if (!goodMeasure) {
1354            childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
1355            childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
1356            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
1357            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
1358                windowSizeMayChange = true;
1359            }
1360        }
1361
1362        if (DBG) {
1363            System.out.println("======================================");
1364            System.out.println("performTraversals -- after measure");
1365            host.debug();
1366        }
1367
1368        return windowSizeMayChange;
1369    }
1370
1371    /**
1372     * Modifies the input matrix such that it maps view-local coordinates to
1373     * on-screen coordinates.
1374     *
1375     * @param m input matrix to modify
1376     */
1377    void transformMatrixToGlobal(Matrix m) {
1378        m.preTranslate(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
1379    }
1380
1381    /**
1382     * Modifies the input matrix such that it maps on-screen coordinates to
1383     * view-local coordinates.
1384     *
1385     * @param m input matrix to modify
1386     */
1387    void transformMatrixToLocal(Matrix m) {
1388        m.postTranslate(-mAttachInfo.mWindowLeft, -mAttachInfo.mWindowTop);
1389    }
1390
1391    /* package */ WindowInsets getWindowInsets(boolean forceConstruct) {
1392        if (mLastWindowInsets == null || forceConstruct) {
1393            mDispatchContentInsets.set(mAttachInfo.mContentInsets);
1394            mDispatchStableInsets.set(mAttachInfo.mStableInsets);
1395            Rect contentInsets = mDispatchContentInsets;
1396            Rect stableInsets = mDispatchStableInsets;
1397            // For dispatch we preserve old logic, but for direct requests from Views we allow to
1398            // immediately use pending insets.
1399            if (!forceConstruct
1400                    && (!mPendingContentInsets.equals(contentInsets) ||
1401                        !mPendingStableInsets.equals(stableInsets))) {
1402                contentInsets = mPendingContentInsets;
1403                stableInsets = mPendingStableInsets;
1404            }
1405            Rect outsets = mAttachInfo.mOutsets;
1406            if (outsets.left > 0 || outsets.top > 0 || outsets.right > 0 || outsets.bottom > 0) {
1407                contentInsets = new Rect(contentInsets.left + outsets.left,
1408                        contentInsets.top + outsets.top, contentInsets.right + outsets.right,
1409                        contentInsets.bottom + outsets.bottom);
1410            }
1411            mLastWindowInsets = new WindowInsets(contentInsets,
1412                    null /* windowDecorInsets */, stableInsets,
1413                    mContext.getResources().getConfiguration().isScreenRound(),
1414                    mAttachInfo.mAlwaysConsumeNavBar);
1415        }
1416        return mLastWindowInsets;
1417    }
1418
1419    void dispatchApplyInsets(View host) {
1420        host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));
1421    }
1422
1423    private static boolean shouldUseDisplaySize(final WindowManager.LayoutParams lp) {
1424        return lp.type == TYPE_STATUS_BAR_PANEL
1425                || lp.type == TYPE_INPUT_METHOD
1426                || lp.type == TYPE_VOLUME_OVERLAY;
1427    }
1428
1429    private int dipToPx(int dip) {
1430        final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
1431        return (int) (displayMetrics.density * dip + 0.5f);
1432    }
1433
1434    private void performTraversals() {
1435        // cache mView since it is used so much below...
1436        final View host = mView;
1437
1438        if (DBG) {
1439            System.out.println("======================================");
1440            System.out.println("performTraversals");
1441            host.debug();
1442        }
1443
1444        if (host == null || !mAdded)
1445            return;
1446
1447        mIsInTraversal = true;
1448        mWillDrawSoon = true;
1449        boolean windowSizeMayChange = false;
1450        boolean newSurface = false;
1451        boolean surfaceChanged = false;
1452        WindowManager.LayoutParams lp = mWindowAttributes;
1453
1454        int desiredWindowWidth;
1455        int desiredWindowHeight;
1456
1457        final int viewVisibility = getHostVisibility();
1458        final boolean viewVisibilityChanged = !mFirst
1459                && (mViewVisibility != viewVisibility || mNewSurfaceNeeded);
1460
1461        WindowManager.LayoutParams params = null;
1462        if (mWindowAttributesChanged) {
1463            mWindowAttributesChanged = false;
1464            surfaceChanged = true;
1465            params = lp;
1466        }
1467        CompatibilityInfo compatibilityInfo = mDisplayAdjustments.getCompatibilityInfo();
1468        if (compatibilityInfo.supportsScreen() == mLastInCompatMode) {
1469            params = lp;
1470            mFullRedrawNeeded = true;
1471            mLayoutRequested = true;
1472            if (mLastInCompatMode) {
1473                params.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1474                mLastInCompatMode = false;
1475            } else {
1476                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
1477                mLastInCompatMode = true;
1478            }
1479        }
1480
1481        mWindowAttributesChangesFlag = 0;
1482
1483        Rect frame = mWinFrame;
1484        if (mFirst) {
1485            mFullRedrawNeeded = true;
1486            mLayoutRequested = true;
1487
1488            if (shouldUseDisplaySize(lp)) {
1489                // NOTE -- system code, won't try to do compat mode.
1490                Point size = new Point();
1491                mDisplay.getRealSize(size);
1492                desiredWindowWidth = size.x;
1493                desiredWindowHeight = size.y;
1494            } else {
1495                Configuration config = mContext.getResources().getConfiguration();
1496                desiredWindowWidth = dipToPx(config.screenWidthDp);
1497                desiredWindowHeight = dipToPx(config.screenHeightDp);
1498            }
1499
1500            // We used to use the following condition to choose 32 bits drawing caches:
1501            // PixelFormat.hasAlpha(lp.format) || lp.format == PixelFormat.RGBX_8888
1502            // However, windows are now always 32 bits by default, so choose 32 bits
1503            mAttachInfo.mUse32BitDrawingCache = true;
1504            mAttachInfo.mHasWindowFocus = false;
1505            mAttachInfo.mWindowVisibility = viewVisibility;
1506            mAttachInfo.mRecomputeGlobalAttributes = false;
1507            mLastConfiguration.setTo(host.getResources().getConfiguration());
1508            mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1509            // Set the layout direction if it has not been set before (inherit is the default)
1510            if (mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
1511                host.setLayoutDirection(mLastConfiguration.getLayoutDirection());
1512            }
1513            host.dispatchAttachedToWindow(mAttachInfo, 0);
1514            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true);
1515            dispatchApplyInsets(host);
1516            //Log.i(mTag, "Screen on initialized: " + attachInfo.mKeepScreenOn);
1517
1518        } else {
1519            desiredWindowWidth = frame.width();
1520            desiredWindowHeight = frame.height();
1521            if (desiredWindowWidth != mWidth || desiredWindowHeight != mHeight) {
1522                if (DEBUG_ORIENTATION) Log.v(mTag, "View " + host + " resized to: " + frame);
1523                mFullRedrawNeeded = true;
1524                mLayoutRequested = true;
1525                windowSizeMayChange = true;
1526            }
1527        }
1528
1529        if (viewVisibilityChanged) {
1530            mAttachInfo.mWindowVisibility = viewVisibility;
1531            host.dispatchWindowVisibilityChanged(viewVisibility);
1532            host.dispatchVisibilityAggregated(viewVisibility == View.VISIBLE);
1533            if (viewVisibility != View.VISIBLE || mNewSurfaceNeeded) {
1534                endDragResizing();
1535                destroyHardwareResources();
1536            }
1537            if (viewVisibility == View.GONE) {
1538                // After making a window gone, we will count it as being
1539                // shown for the first time the next time it gets focus.
1540                mHasHadWindowFocus = false;
1541            }
1542        }
1543
1544        // Non-visible windows can't hold accessibility focus.
1545        if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
1546            host.clearAccessibilityFocus();
1547        }
1548
1549        // Execute enqueued actions on every traversal in case a detached view enqueued an action
1550        getRunQueue().executeActions(mAttachInfo.mHandler);
1551
1552        boolean insetsChanged = false;
1553
1554        boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
1555        if (layoutRequested) {
1556
1557            final Resources res = mView.getContext().getResources();
1558
1559            if (mFirst) {
1560                // make sure touch mode code executes by setting cached value
1561                // to opposite of the added touch mode.
1562                mAttachInfo.mInTouchMode = !mAddedTouchMode;
1563                ensureTouchModeLocally(mAddedTouchMode);
1564            } else {
1565                if (!mPendingOverscanInsets.equals(mAttachInfo.mOverscanInsets)) {
1566                    insetsChanged = true;
1567                }
1568                if (!mPendingContentInsets.equals(mAttachInfo.mContentInsets)) {
1569                    insetsChanged = true;
1570                }
1571                if (!mPendingStableInsets.equals(mAttachInfo.mStableInsets)) {
1572                    insetsChanged = true;
1573                }
1574                if (!mPendingVisibleInsets.equals(mAttachInfo.mVisibleInsets)) {
1575                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1576                    if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
1577                            + mAttachInfo.mVisibleInsets);
1578                }
1579                if (!mPendingOutsets.equals(mAttachInfo.mOutsets)) {
1580                    insetsChanged = true;
1581                }
1582                if (mPendingAlwaysConsumeNavBar != mAttachInfo.mAlwaysConsumeNavBar) {
1583                    insetsChanged = true;
1584                }
1585                if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT
1586                        || lp.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
1587                    windowSizeMayChange = true;
1588
1589                    if (shouldUseDisplaySize(lp)) {
1590                        // NOTE -- system code, won't try to do compat mode.
1591                        Point size = new Point();
1592                        mDisplay.getRealSize(size);
1593                        desiredWindowWidth = size.x;
1594                        desiredWindowHeight = size.y;
1595                    } else {
1596                        Configuration config = res.getConfiguration();
1597                        desiredWindowWidth = dipToPx(config.screenWidthDp);
1598                        desiredWindowHeight = dipToPx(config.screenHeightDp);
1599                    }
1600                }
1601            }
1602
1603            // Ask host how big it wants to be
1604            windowSizeMayChange |= measureHierarchy(host, lp, res,
1605                    desiredWindowWidth, desiredWindowHeight);
1606        }
1607
1608        if (collectViewAttributes()) {
1609            params = lp;
1610        }
1611        if (mAttachInfo.mForceReportNewAttributes) {
1612            mAttachInfo.mForceReportNewAttributes = false;
1613            params = lp;
1614        }
1615
1616        if (mFirst || mAttachInfo.mViewVisibilityChanged) {
1617            mAttachInfo.mViewVisibilityChanged = false;
1618            int resizeMode = mSoftInputMode &
1619                    WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
1620            // If we are in auto resize mode, then we need to determine
1621            // what mode to use now.
1622            if (resizeMode == WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED) {
1623                final int N = mAttachInfo.mScrollContainers.size();
1624                for (int i=0; i<N; i++) {
1625                    if (mAttachInfo.mScrollContainers.get(i).isShown()) {
1626                        resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
1627                    }
1628                }
1629                if (resizeMode == 0) {
1630                    resizeMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;
1631                }
1632                if ((lp.softInputMode &
1633                        WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) != resizeMode) {
1634                    lp.softInputMode = (lp.softInputMode &
1635                            ~WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST) |
1636                            resizeMode;
1637                    params = lp;
1638                }
1639            }
1640        }
1641
1642        if (params != null) {
1643            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
1644                if (!PixelFormat.formatHasAlpha(params.format)) {
1645                    params.format = PixelFormat.TRANSLUCENT;
1646                }
1647            }
1648            mAttachInfo.mOverscanRequested = (params.flags
1649                    & WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN) != 0;
1650        }
1651
1652        if (mApplyInsetsRequested) {
1653            mApplyInsetsRequested = false;
1654            mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1655            dispatchApplyInsets(host);
1656            if (mLayoutRequested) {
1657                // Short-circuit catching a new layout request here, so
1658                // we don't need to go through two layout passes when things
1659                // change due to fitting system windows, which can happen a lot.
1660                windowSizeMayChange |= measureHierarchy(host, lp,
1661                        mView.getContext().getResources(),
1662                        desiredWindowWidth, desiredWindowHeight);
1663            }
1664        }
1665
1666        if (layoutRequested) {
1667            // Clear this now, so that if anything requests a layout in the
1668            // rest of this function we will catch it and re-run a full
1669            // layout pass.
1670            mLayoutRequested = false;
1671        }
1672
1673        boolean windowShouldResize = layoutRequested && windowSizeMayChange
1674            && ((mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight())
1675                || (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT &&
1676                        frame.width() < desiredWindowWidth && frame.width() != mWidth)
1677                || (lp.height == ViewGroup.LayoutParams.WRAP_CONTENT &&
1678                        frame.height() < desiredWindowHeight && frame.height() != mHeight));
1679        windowShouldResize |= mDragResizing && mResizeMode == RESIZE_MODE_FREEFORM;
1680
1681        // If the activity was just relaunched, it might have unfrozen the task bounds (while
1682        // relaunching), so we need to force a call into window manager to pick up the latest
1683        // bounds.
1684        windowShouldResize |= mActivityRelaunched;
1685
1686        // Determine whether to compute insets.
1687        // If there are no inset listeners remaining then we may still need to compute
1688        // insets in case the old insets were non-empty and must be reset.
1689        final boolean computesInternalInsets =
1690                mAttachInfo.mTreeObserver.hasComputeInternalInsetsListeners()
1691                || mAttachInfo.mHasNonEmptyGivenInternalInsets;
1692
1693        boolean insetsPending = false;
1694        int relayoutResult = 0;
1695        boolean updatedConfiguration = false;
1696
1697        final int surfaceGenerationId = mSurface.getGenerationId();
1698
1699        final boolean isViewVisible = viewVisibility == View.VISIBLE;
1700        if (mFirst || windowShouldResize || insetsChanged ||
1701                viewVisibilityChanged || params != null || mForceNextWindowRelayout) {
1702            mForceNextWindowRelayout = false;
1703
1704            if (isViewVisible) {
1705                // If this window is giving internal insets to the window
1706                // manager, and it is being added or changing its visibility,
1707                // then we want to first give the window manager "fake"
1708                // insets to cause it to effectively ignore the content of
1709                // the window during layout.  This avoids it briefly causing
1710                // other windows to resize/move based on the raw frame of the
1711                // window, waiting until we can finish laying out this window
1712                // and get back to the window manager with the ultimately
1713                // computed insets.
1714                insetsPending = computesInternalInsets && (mFirst || viewVisibilityChanged);
1715            }
1716
1717            if (mSurfaceHolder != null) {
1718                mSurfaceHolder.mSurfaceLock.lock();
1719                mDrawingAllowed = true;
1720            }
1721
1722            boolean hwInitialized = false;
1723            boolean contentInsetsChanged = false;
1724            boolean hadSurface = mSurface.isValid();
1725
1726            try {
1727                if (DEBUG_LAYOUT) {
1728                    Log.i(mTag, "host=w:" + host.getMeasuredWidth() + ", h:" +
1729                            host.getMeasuredHeight() + ", params=" + params);
1730                }
1731
1732                if (mAttachInfo.mHardwareRenderer != null) {
1733                    // relayoutWindow may decide to destroy mSurface. As that decision
1734                    // happens in WindowManager service, we need to be defensive here
1735                    // and stop using the surface in case it gets destroyed.
1736                    if (mAttachInfo.mHardwareRenderer.pauseSurface(mSurface)) {
1737                        // Animations were running so we need to push a frame
1738                        // to resume them
1739                        mDirty.set(0, 0, mWidth, mHeight);
1740                    }
1741                    mChoreographer.mFrameInfo.addFlags(FrameInfo.FLAG_WINDOW_LAYOUT_CHANGED);
1742                }
1743                relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
1744
1745                if (DEBUG_LAYOUT) Log.v(mTag, "relayout: frame=" + frame.toShortString()
1746                        + " overscan=" + mPendingOverscanInsets.toShortString()
1747                        + " content=" + mPendingContentInsets.toShortString()
1748                        + " visible=" + mPendingVisibleInsets.toShortString()
1749                        + " visible=" + mPendingStableInsets.toShortString()
1750                        + " outsets=" + mPendingOutsets.toShortString()
1751                        + " surface=" + mSurface);
1752
1753                if (mPendingConfiguration.seq != 0) {
1754                    if (DEBUG_CONFIGURATION) Log.v(mTag, "Visible with new config: "
1755                            + mPendingConfiguration);
1756                    updateConfiguration(new Configuration(mPendingConfiguration), !mFirst);
1757                    mPendingConfiguration.seq = 0;
1758                    updatedConfiguration = true;
1759                }
1760
1761                final boolean overscanInsetsChanged = !mPendingOverscanInsets.equals(
1762                        mAttachInfo.mOverscanInsets);
1763                contentInsetsChanged = !mPendingContentInsets.equals(
1764                        mAttachInfo.mContentInsets);
1765                final boolean visibleInsetsChanged = !mPendingVisibleInsets.equals(
1766                        mAttachInfo.mVisibleInsets);
1767                final boolean stableInsetsChanged = !mPendingStableInsets.equals(
1768                        mAttachInfo.mStableInsets);
1769                final boolean outsetsChanged = !mPendingOutsets.equals(mAttachInfo.mOutsets);
1770                final boolean surfaceSizeChanged = (relayoutResult
1771                        & WindowManagerGlobal.RELAYOUT_RES_SURFACE_RESIZED) != 0;
1772                final boolean alwaysConsumeNavBarChanged =
1773                        mPendingAlwaysConsumeNavBar != mAttachInfo.mAlwaysConsumeNavBar;
1774                if (contentInsetsChanged) {
1775                    mAttachInfo.mContentInsets.set(mPendingContentInsets);
1776                    if (DEBUG_LAYOUT) Log.v(mTag, "Content insets changing to: "
1777                            + mAttachInfo.mContentInsets);
1778                }
1779                if (overscanInsetsChanged) {
1780                    mAttachInfo.mOverscanInsets.set(mPendingOverscanInsets);
1781                    if (DEBUG_LAYOUT) Log.v(mTag, "Overscan insets changing to: "
1782                            + mAttachInfo.mOverscanInsets);
1783                    // Need to relayout with content insets.
1784                    contentInsetsChanged = true;
1785                }
1786                if (stableInsetsChanged) {
1787                    mAttachInfo.mStableInsets.set(mPendingStableInsets);
1788                    if (DEBUG_LAYOUT) Log.v(mTag, "Decor insets changing to: "
1789                            + mAttachInfo.mStableInsets);
1790                    // Need to relayout with content insets.
1791                    contentInsetsChanged = true;
1792                }
1793                if (alwaysConsumeNavBarChanged) {
1794                    mAttachInfo.mAlwaysConsumeNavBar = mPendingAlwaysConsumeNavBar;
1795                    contentInsetsChanged = true;
1796                }
1797                if (contentInsetsChanged || mLastSystemUiVisibility !=
1798                        mAttachInfo.mSystemUiVisibility || mApplyInsetsRequested
1799                        || mLastOverscanRequested != mAttachInfo.mOverscanRequested
1800                        || outsetsChanged) {
1801                    mLastSystemUiVisibility = mAttachInfo.mSystemUiVisibility;
1802                    mLastOverscanRequested = mAttachInfo.mOverscanRequested;
1803                    mAttachInfo.mOutsets.set(mPendingOutsets);
1804                    mApplyInsetsRequested = false;
1805                    dispatchApplyInsets(host);
1806                }
1807                if (visibleInsetsChanged) {
1808                    mAttachInfo.mVisibleInsets.set(mPendingVisibleInsets);
1809                    if (DEBUG_LAYOUT) Log.v(mTag, "Visible insets changing to: "
1810                            + mAttachInfo.mVisibleInsets);
1811                }
1812
1813                if (!hadSurface) {
1814                    if (mSurface.isValid()) {
1815                        // If we are creating a new surface, then we need to
1816                        // completely redraw it.  Also, when we get to the
1817                        // point of drawing it we will hold off and schedule
1818                        // a new traversal instead.  This is so we can tell the
1819                        // window manager about all of the windows being displayed
1820                        // before actually drawing them, so it can display then
1821                        // all at once.
1822                        newSurface = true;
1823                        mFullRedrawNeeded = true;
1824                        mPreviousTransparentRegion.setEmpty();
1825
1826                        // Only initialize up-front if transparent regions are not
1827                        // requested, otherwise defer to see if the entire window
1828                        // will be transparent
1829                        if (mAttachInfo.mHardwareRenderer != null) {
1830                            try {
1831                                hwInitialized = mAttachInfo.mHardwareRenderer.initialize(
1832                                        mSurface);
1833                                if (hwInitialized && (host.mPrivateFlags
1834                                        & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0) {
1835                                    // Don't pre-allocate if transparent regions
1836                                    // are requested as they may not be needed
1837                                    mSurface.allocateBuffers();
1838                                }
1839                            } catch (OutOfResourcesException e) {
1840                                handleOutOfResourcesException(e);
1841                                return;
1842                            }
1843                        }
1844                    }
1845                } else if (!mSurface.isValid()) {
1846                    // If the surface has been removed, then reset the scroll
1847                    // positions.
1848                    if (mLastScrolledFocus != null) {
1849                        mLastScrolledFocus.clear();
1850                    }
1851                    mScrollY = mCurScrollY = 0;
1852                    if (mView instanceof RootViewSurfaceTaker) {
1853                        ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
1854                    }
1855                    if (mScroller != null) {
1856                        mScroller.abortAnimation();
1857                    }
1858                    // Our surface is gone
1859                    if (mAttachInfo.mHardwareRenderer != null &&
1860                            mAttachInfo.mHardwareRenderer.isEnabled()) {
1861                        mAttachInfo.mHardwareRenderer.destroy();
1862                    }
1863                } else if ((surfaceGenerationId != mSurface.getGenerationId()
1864                        || surfaceSizeChanged)
1865                        && mSurfaceHolder == null
1866                        && mAttachInfo.mHardwareRenderer != null) {
1867                    mFullRedrawNeeded = true;
1868                    try {
1869                        // Need to do updateSurface (which leads to CanvasContext::setSurface and
1870                        // re-create the EGLSurface) if either the Surface changed (as indicated by
1871                        // generation id), or WindowManager changed the surface size. The latter is
1872                        // because on some chips, changing the consumer side's BufferQueue size may
1873                        // not take effect immediately unless we create a new EGLSurface.
1874                        // Note that frame size change doesn't always imply surface size change (eg.
1875                        // drag resizing uses fullscreen surface), need to check surfaceSizeChanged
1876                        // flag from WindowManager.
1877                        mAttachInfo.mHardwareRenderer.updateSurface(mSurface);
1878                    } catch (OutOfResourcesException e) {
1879                        handleOutOfResourcesException(e);
1880                        return;
1881                    }
1882                }
1883
1884                final boolean freeformResizing = (relayoutResult
1885                        & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_FREEFORM) != 0;
1886                final boolean dockedResizing = (relayoutResult
1887                        & WindowManagerGlobal.RELAYOUT_RES_DRAG_RESIZING_DOCKED) != 0;
1888                final boolean dragResizing = freeformResizing || dockedResizing;
1889                if (mDragResizing != dragResizing) {
1890                    if (dragResizing) {
1891                        mResizeMode = freeformResizing
1892                                ? RESIZE_MODE_FREEFORM
1893                                : RESIZE_MODE_DOCKED_DIVIDER;
1894                        startDragResizing(mPendingBackDropFrame,
1895                                mWinFrame.equals(mPendingBackDropFrame), mPendingVisibleInsets,
1896                                mPendingStableInsets, mResizeMode);
1897                    } else {
1898                        // We shouldn't come here, but if we come we should end the resize.
1899                        endDragResizing();
1900                    }
1901                }
1902                if (!USE_MT_RENDERER) {
1903                    if (dragResizing) {
1904                        mCanvasOffsetX = mWinFrame.left;
1905                        mCanvasOffsetY = mWinFrame.top;
1906                    } else {
1907                        mCanvasOffsetX = mCanvasOffsetY = 0;
1908                    }
1909                }
1910            } catch (RemoteException e) {
1911            }
1912
1913            if (DEBUG_ORIENTATION) Log.v(
1914                    TAG, "Relayout returned: frame=" + frame + ", surface=" + mSurface);
1915
1916            mAttachInfo.mWindowLeft = frame.left;
1917            mAttachInfo.mWindowTop = frame.top;
1918
1919            // !!FIXME!! This next section handles the case where we did not get the
1920            // window size we asked for. We should avoid this by getting a maximum size from
1921            // the window session beforehand.
1922            if (mWidth != frame.width() || mHeight != frame.height()) {
1923                mWidth = frame.width();
1924                mHeight = frame.height();
1925            }
1926
1927            if (mSurfaceHolder != null) {
1928                // The app owns the surface; tell it about what is going on.
1929                if (mSurface.isValid()) {
1930                    // XXX .copyFrom() doesn't work!
1931                    //mSurfaceHolder.mSurface.copyFrom(mSurface);
1932                    mSurfaceHolder.mSurface = mSurface;
1933                }
1934                mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
1935                mSurfaceHolder.mSurfaceLock.unlock();
1936                if (mSurface.isValid()) {
1937                    if (!hadSurface || surfaceGenerationId != mSurface.getGenerationId()) {
1938                        mSurfaceHolder.ungetCallbacks();
1939
1940                        mIsCreating = true;
1941                        mSurfaceHolderCallback.surfaceCreated(mSurfaceHolder);
1942                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1943                        if (callbacks != null) {
1944                            for (SurfaceHolder.Callback c : callbacks) {
1945                                c.surfaceCreated(mSurfaceHolder);
1946                            }
1947                        }
1948                        surfaceChanged = true;
1949                    }
1950                    if (surfaceChanged) {
1951                        mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
1952                                lp.format, mWidth, mHeight);
1953                        SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1954                        if (callbacks != null) {
1955                            for (SurfaceHolder.Callback c : callbacks) {
1956                                c.surfaceChanged(mSurfaceHolder, lp.format,
1957                                        mWidth, mHeight);
1958                            }
1959                        }
1960                    }
1961                    mIsCreating = false;
1962                } else if (hadSurface) {
1963                    mSurfaceHolder.ungetCallbacks();
1964                    SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
1965                    mSurfaceHolderCallback.surfaceDestroyed(mSurfaceHolder);
1966                    if (callbacks != null) {
1967                        for (SurfaceHolder.Callback c : callbacks) {
1968                            c.surfaceDestroyed(mSurfaceHolder);
1969                        }
1970                    }
1971                    mSurfaceHolder.mSurfaceLock.lock();
1972                    try {
1973                        mSurfaceHolder.mSurface = new Surface();
1974                    } finally {
1975                        mSurfaceHolder.mSurfaceLock.unlock();
1976                    }
1977                }
1978            }
1979
1980            final ThreadedRenderer hardwareRenderer = mAttachInfo.mHardwareRenderer;
1981            if (hardwareRenderer != null && hardwareRenderer.isEnabled()) {
1982                if (hwInitialized
1983                        || mWidth != hardwareRenderer.getWidth()
1984                        || mHeight != hardwareRenderer.getHeight()
1985                        || mNeedsHwRendererSetup) {
1986                    hardwareRenderer.setup(mWidth, mHeight, mAttachInfo,
1987                            mWindowAttributes.surfaceInsets);
1988                    mNeedsHwRendererSetup = false;
1989                }
1990            }
1991
1992            if (!mStopped || mReportNextDraw) {
1993                boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
1994                        (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
1995                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
1996                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
1997                        updatedConfiguration) {
1998                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
1999                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
2000
2001                    if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
2002                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
2003                            + " mHeight=" + mHeight
2004                            + " measuredHeight=" + host.getMeasuredHeight()
2005                            + " coveredInsetsChanged=" + contentInsetsChanged);
2006
2007                     // Ask host how big it wants to be
2008                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
2009
2010                    // Implementation of weights from WindowManager.LayoutParams
2011                    // We just grow the dimensions as needed and re-measure if
2012                    // needs be
2013                    int width = host.getMeasuredWidth();
2014                    int height = host.getMeasuredHeight();
2015                    boolean measureAgain = false;
2016
2017                    if (lp.horizontalWeight > 0.0f) {
2018                        width += (int) ((mWidth - width) * lp.horizontalWeight);
2019                        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
2020                                MeasureSpec.EXACTLY);
2021                        measureAgain = true;
2022                    }
2023                    if (lp.verticalWeight > 0.0f) {
2024                        height += (int) ((mHeight - height) * lp.verticalWeight);
2025                        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
2026                                MeasureSpec.EXACTLY);
2027                        measureAgain = true;
2028                    }
2029
2030                    if (measureAgain) {
2031                        if (DEBUG_LAYOUT) Log.v(mTag,
2032                                "And hey let's measure once more: width=" + width
2033                                + " height=" + height);
2034                        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
2035                    }
2036
2037                    layoutRequested = true;
2038                }
2039            }
2040        } else {
2041            // Not the first pass and no window/insets/visibility change but the window
2042            // may have moved and we need check that and if so to update the left and right
2043            // in the attach info. We translate only the window frame since on window move
2044            // the window manager tells us only for the new frame but the insets are the
2045            // same and we do not want to translate them more than once.
2046            maybeHandleWindowMove(frame);
2047        }
2048
2049        final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
2050        boolean triggerGlobalLayoutListener = didLayout
2051                || mAttachInfo.mRecomputeGlobalAttributes;
2052        if (didLayout) {
2053            performLayout(lp, mWidth, mHeight);
2054
2055            // By this point all views have been sized and positioned
2056            // We can compute the transparent area
2057
2058            if ((host.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
2059                // start out transparent
2060                // TODO: AVOID THAT CALL BY CACHING THE RESULT?
2061                host.getLocationInWindow(mTmpLocation);
2062                mTransparentRegion.set(mTmpLocation[0], mTmpLocation[1],
2063                        mTmpLocation[0] + host.mRight - host.mLeft,
2064                        mTmpLocation[1] + host.mBottom - host.mTop);
2065
2066                host.gatherTransparentRegion(mTransparentRegion);
2067                if (mTranslator != null) {
2068                    mTranslator.translateRegionInWindowToScreen(mTransparentRegion);
2069                }
2070
2071                if (!mTransparentRegion.equals(mPreviousTransparentRegion)) {
2072                    mPreviousTransparentRegion.set(mTransparentRegion);
2073                    mFullRedrawNeeded = true;
2074                    // reconfigure window manager
2075                    try {
2076                        mWindowSession.setTransparentRegion(mWindow, mTransparentRegion);
2077                    } catch (RemoteException e) {
2078                    }
2079                }
2080            }
2081
2082            if (DBG) {
2083                System.out.println("======================================");
2084                System.out.println("performTraversals -- after setFrame");
2085                host.debug();
2086            }
2087        }
2088
2089        if (triggerGlobalLayoutListener) {
2090            mAttachInfo.mRecomputeGlobalAttributes = false;
2091            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
2092        }
2093
2094        if (computesInternalInsets) {
2095            // Clear the original insets.
2096            final ViewTreeObserver.InternalInsetsInfo insets = mAttachInfo.mGivenInternalInsets;
2097            insets.reset();
2098
2099            // Compute new insets in place.
2100            mAttachInfo.mTreeObserver.dispatchOnComputeInternalInsets(insets);
2101            mAttachInfo.mHasNonEmptyGivenInternalInsets = !insets.isEmpty();
2102
2103            // Tell the window manager.
2104            if (insetsPending || !mLastGivenInsets.equals(insets)) {
2105                mLastGivenInsets.set(insets);
2106
2107                // Translate insets to screen coordinates if needed.
2108                final Rect contentInsets;
2109                final Rect visibleInsets;
2110                final Region touchableRegion;
2111                if (mTranslator != null) {
2112                    contentInsets = mTranslator.getTranslatedContentInsets(insets.contentInsets);
2113                    visibleInsets = mTranslator.getTranslatedVisibleInsets(insets.visibleInsets);
2114                    touchableRegion = mTranslator.getTranslatedTouchableArea(insets.touchableRegion);
2115                } else {
2116                    contentInsets = insets.contentInsets;
2117                    visibleInsets = insets.visibleInsets;
2118                    touchableRegion = insets.touchableRegion;
2119                }
2120
2121                try {
2122                    mWindowSession.setInsets(mWindow, insets.mTouchableInsets,
2123                            contentInsets, visibleInsets, touchableRegion);
2124                } catch (RemoteException e) {
2125                }
2126            }
2127        }
2128
2129        if (mFirst) {
2130            // handle first focus request
2131            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: mView.hasFocus()="
2132                    + mView.hasFocus());
2133            if (mView != null) {
2134                if (!mView.hasFocus()) {
2135                    mView.requestFocus(View.FOCUS_FORWARD);
2136                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: requested focused view="
2137                            + mView.findFocus());
2138                } else {
2139                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "First: existing focused view="
2140                            + mView.findFocus());
2141                }
2142            }
2143        }
2144
2145        final boolean changedVisibility = (viewVisibilityChanged || mFirst) && isViewVisible;
2146        final boolean hasWindowFocus = mAttachInfo.mHasWindowFocus && isViewVisible;
2147        final boolean regainedFocus = hasWindowFocus && mLostWindowFocus;
2148        if (regainedFocus) {
2149            mLostWindowFocus = false;
2150        } else if (!hasWindowFocus && mHadWindowFocus) {
2151            mLostWindowFocus = true;
2152        }
2153
2154        if (changedVisibility || regainedFocus) {
2155            host.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2156        }
2157
2158        mFirst = false;
2159        mWillDrawSoon = false;
2160        mNewSurfaceNeeded = false;
2161        mActivityRelaunched = false;
2162        mViewVisibility = viewVisibility;
2163        mHadWindowFocus = hasWindowFocus;
2164
2165        if (hasWindowFocus && !isInLocalFocusMode()) {
2166            final boolean imTarget = WindowManager.LayoutParams
2167                    .mayUseInputMethod(mWindowAttributes.flags);
2168            if (imTarget != mLastWasImTarget) {
2169                mLastWasImTarget = imTarget;
2170                InputMethodManager imm = InputMethodManager.peekInstance();
2171                if (imm != null && imTarget) {
2172                    imm.onPreWindowFocus(mView, hasWindowFocus);
2173                    imm.onPostWindowFocus(mView, mView.findFocus(),
2174                            mWindowAttributes.softInputMode,
2175                            !mHasHadWindowFocus, mWindowAttributes.flags);
2176                }
2177            }
2178        }
2179
2180        // Remember if we must report the next draw.
2181        if ((relayoutResult & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
2182            mReportNextDraw = true;
2183        }
2184
2185        boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
2186
2187        if (!cancelDraw && !newSurface) {
2188            if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2189                for (int i = 0; i < mPendingTransitions.size(); ++i) {
2190                    mPendingTransitions.get(i).startChangingAnimations();
2191                }
2192                mPendingTransitions.clear();
2193            }
2194
2195            performDraw();
2196        } else {
2197            if (isViewVisible) {
2198                // Try again
2199                scheduleTraversals();
2200            } else if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
2201                for (int i = 0; i < mPendingTransitions.size(); ++i) {
2202                    mPendingTransitions.get(i).endChangingAnimations();
2203                }
2204                mPendingTransitions.clear();
2205            }
2206        }
2207
2208        mIsInTraversal = false;
2209    }
2210
2211    private void maybeHandleWindowMove(Rect frame) {
2212
2213        // TODO: Well, we are checking whether the frame has changed similarly
2214        // to how this is done for the insets. This is however incorrect since
2215        // the insets and the frame are translated. For example, the old frame
2216        // was (1, 1 - 1, 1) and was translated to say (2, 2 - 2, 2), now the new
2217        // reported frame is (2, 2 - 2, 2) which implies no change but this is not
2218        // true since we are comparing a not translated value to a translated one.
2219        // This scenario is rare but we may want to fix that.
2220
2221        final boolean windowMoved = mAttachInfo.mWindowLeft != frame.left
2222                || mAttachInfo.mWindowTop != frame.top;
2223        if (windowMoved) {
2224            if (mTranslator != null) {
2225                mTranslator.translateRectInScreenToAppWinFrame(frame);
2226            }
2227            mAttachInfo.mWindowLeft = frame.left;
2228            mAttachInfo.mWindowTop = frame.top;
2229        }
2230        if (windowMoved || mAttachInfo.mNeedsUpdateLightCenter) {
2231            // Update the light position for the new offsets.
2232            if (mAttachInfo.mHardwareRenderer != null) {
2233                mAttachInfo.mHardwareRenderer.setLightCenter(mAttachInfo);
2234            }
2235            mAttachInfo.mNeedsUpdateLightCenter = false;
2236        }
2237    }
2238
2239    private void handleOutOfResourcesException(Surface.OutOfResourcesException e) {
2240        Log.e(mTag, "OutOfResourcesException initializing HW surface", e);
2241        try {
2242            if (!mWindowSession.outOfMemory(mWindow) &&
2243                    Process.myUid() != Process.SYSTEM_UID) {
2244                Slog.w(mTag, "No processes killed for memory; killing self");
2245                Process.killProcess(Process.myPid());
2246            }
2247        } catch (RemoteException ex) {
2248        }
2249        mLayoutRequested = true;    // ask wm for a new surface next time.
2250    }
2251
2252    private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
2253        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
2254        try {
2255            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
2256        } finally {
2257            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2258        }
2259    }
2260
2261    /**
2262     * Called by {@link android.view.View#isInLayout()} to determine whether the view hierarchy
2263     * is currently undergoing a layout pass.
2264     *
2265     * @return whether the view hierarchy is currently undergoing a layout pass
2266     */
2267    boolean isInLayout() {
2268        return mInLayout;
2269    }
2270
2271    /**
2272     * Called by {@link android.view.View#requestLayout()} if the view hierarchy is currently
2273     * undergoing a layout pass. requestLayout() should not generally be called during layout,
2274     * unless the container hierarchy knows what it is doing (i.e., it is fine as long as
2275     * all children in that container hierarchy are measured and laid out at the end of the layout
2276     * pass for that container). If requestLayout() is called anyway, we handle it correctly
2277     * by registering all requesters during a frame as it proceeds. At the end of the frame,
2278     * we check all of those views to see if any still have pending layout requests, which
2279     * indicates that they were not correctly handled by their container hierarchy. If that is
2280     * the case, we clear all such flags in the tree, to remove the buggy flag state that leads
2281     * to blank containers, and force a second request/measure/layout pass in this frame. If
2282     * more requestLayout() calls are received during that second layout pass, we post those
2283     * requests to the next frame to avoid possible infinite loops.
2284     *
2285     * <p>The return value from this method indicates whether the request should proceed
2286     * (if it is a request during the first layout pass) or should be skipped and posted to the
2287     * next frame (if it is a request during the second layout pass).</p>
2288     *
2289     * @param view the view that requested the layout.
2290     *
2291     * @return true if request should proceed, false otherwise.
2292     */
2293    boolean requestLayoutDuringLayout(final View view) {
2294        if (view.mParent == null || view.mAttachInfo == null) {
2295            // Would not normally trigger another layout, so just let it pass through as usual
2296            return true;
2297        }
2298        if (!mLayoutRequesters.contains(view)) {
2299            mLayoutRequesters.add(view);
2300        }
2301        if (!mHandlingLayoutInLayoutRequest) {
2302            // Let the request proceed normally; it will be processed in a second layout pass
2303            // if necessary
2304            return true;
2305        } else {
2306            // Don't let the request proceed during the second layout pass.
2307            // It will post to the next frame instead.
2308            return false;
2309        }
2310    }
2311
2312    private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
2313            int desiredWindowHeight) {
2314        mLayoutRequested = false;
2315        mScrollMayChange = true;
2316        mInLayout = true;
2317
2318        final View host = mView;
2319        if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
2320            Log.v(mTag, "Laying out " + host + " to (" +
2321                    host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
2322        }
2323
2324        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
2325        try {
2326            host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2327
2328            mInLayout = false;
2329            int numViewsRequestingLayout = mLayoutRequesters.size();
2330            if (numViewsRequestingLayout > 0) {
2331                // requestLayout() was called during layout.
2332                // If no layout-request flags are set on the requesting views, there is no problem.
2333                // If some requests are still pending, then we need to clear those flags and do
2334                // a full request/measure/layout pass to handle this situation.
2335                ArrayList<View> validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters,
2336                        false);
2337                if (validLayoutRequesters != null) {
2338                    // Set this flag to indicate that any further requests are happening during
2339                    // the second pass, which may result in posting those requests to the next
2340                    // frame instead
2341                    mHandlingLayoutInLayoutRequest = true;
2342
2343                    // Process fresh layout requests, then measure and layout
2344                    int numValidRequests = validLayoutRequesters.size();
2345                    for (int i = 0; i < numValidRequests; ++i) {
2346                        final View view = validLayoutRequesters.get(i);
2347                        Log.w("View", "requestLayout() improperly called by " + view +
2348                                " during layout: running second layout pass");
2349                        view.requestLayout();
2350                    }
2351                    measureHierarchy(host, lp, mView.getContext().getResources(),
2352                            desiredWindowWidth, desiredWindowHeight);
2353                    mInLayout = true;
2354                    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
2355
2356                    mHandlingLayoutInLayoutRequest = false;
2357
2358                    // Check the valid requests again, this time without checking/clearing the
2359                    // layout flags, since requests happening during the second pass get noop'd
2360                    validLayoutRequesters = getValidLayoutRequesters(mLayoutRequesters, true);
2361                    if (validLayoutRequesters != null) {
2362                        final ArrayList<View> finalRequesters = validLayoutRequesters;
2363                        // Post second-pass requests to the next frame
2364                        getRunQueue().post(new Runnable() {
2365                            @Override
2366                            public void run() {
2367                                int numValidRequests = finalRequesters.size();
2368                                for (int i = 0; i < numValidRequests; ++i) {
2369                                    final View view = finalRequesters.get(i);
2370                                    Log.w("View", "requestLayout() improperly called by " + view +
2371                                            " during second layout pass: posting in next frame");
2372                                    view.requestLayout();
2373                                }
2374                            }
2375                        });
2376                    }
2377                }
2378
2379            }
2380        } finally {
2381            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2382        }
2383        mInLayout = false;
2384    }
2385
2386    /**
2387     * This method is called during layout when there have been calls to requestLayout() during
2388     * layout. It walks through the list of views that requested layout to determine which ones
2389     * still need it, based on visibility in the hierarchy and whether they have already been
2390     * handled (as is usually the case with ListView children).
2391     *
2392     * @param layoutRequesters The list of views that requested layout during layout
2393     * @param secondLayoutRequests Whether the requests were issued during the second layout pass.
2394     * If so, the FORCE_LAYOUT flag was not set on requesters.
2395     * @return A list of the actual views that still need to be laid out.
2396     */
2397    private ArrayList<View> getValidLayoutRequesters(ArrayList<View> layoutRequesters,
2398            boolean secondLayoutRequests) {
2399
2400        int numViewsRequestingLayout = layoutRequesters.size();
2401        ArrayList<View> validLayoutRequesters = null;
2402        for (int i = 0; i < numViewsRequestingLayout; ++i) {
2403            View view = layoutRequesters.get(i);
2404            if (view != null && view.mAttachInfo != null && view.mParent != null &&
2405                    (secondLayoutRequests || (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) ==
2406                            View.PFLAG_FORCE_LAYOUT)) {
2407                boolean gone = false;
2408                View parent = view;
2409                // Only trigger new requests for views in a non-GONE hierarchy
2410                while (parent != null) {
2411                    if ((parent.mViewFlags & View.VISIBILITY_MASK) == View.GONE) {
2412                        gone = true;
2413                        break;
2414                    }
2415                    if (parent.mParent instanceof View) {
2416                        parent = (View) parent.mParent;
2417                    } else {
2418                        parent = null;
2419                    }
2420                }
2421                if (!gone) {
2422                    if (validLayoutRequesters == null) {
2423                        validLayoutRequesters = new ArrayList<View>();
2424                    }
2425                    validLayoutRequesters.add(view);
2426                }
2427            }
2428        }
2429        if (!secondLayoutRequests) {
2430            // If we're checking the layout flags, then we need to clean them up also
2431            for (int i = 0; i < numViewsRequestingLayout; ++i) {
2432                View view = layoutRequesters.get(i);
2433                while (view != null &&
2434                        (view.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) != 0) {
2435                    view.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
2436                    if (view.mParent instanceof View) {
2437                        view = (View) view.mParent;
2438                    } else {
2439                        view = null;
2440                    }
2441                }
2442            }
2443        }
2444        layoutRequesters.clear();
2445        return validLayoutRequesters;
2446    }
2447
2448    @Override
2449    public void requestTransparentRegion(View child) {
2450        // the test below should not fail unless someone is messing with us
2451        checkThread();
2452        if (mView == child) {
2453            mView.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
2454            // Need to make sure we re-evaluate the window attributes next
2455            // time around, to ensure the window has the correct format.
2456            mWindowAttributesChanged = true;
2457            mWindowAttributesChangesFlag = 0;
2458            requestLayout();
2459        }
2460    }
2461
2462    /**
2463     * Figures out the measure spec for the root view in a window based on it's
2464     * layout params.
2465     *
2466     * @param windowSize
2467     *            The available width or height of the window
2468     *
2469     * @param rootDimension
2470     *            The layout params for one dimension (width or height) of the
2471     *            window.
2472     *
2473     * @return The measure spec to use to measure the root view.
2474     */
2475    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
2476        int measureSpec;
2477        switch (rootDimension) {
2478
2479        case ViewGroup.LayoutParams.MATCH_PARENT:
2480            // Window can't resize. Force root view to be windowSize.
2481            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
2482            break;
2483        case ViewGroup.LayoutParams.WRAP_CONTENT:
2484            // Window can resize. Set max size for root view.
2485            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
2486            break;
2487        default:
2488            // Window wants to be an exact size. Force root view to be that size.
2489            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
2490            break;
2491        }
2492        return measureSpec;
2493    }
2494
2495    int mHardwareXOffset;
2496    int mHardwareYOffset;
2497
2498    @Override
2499    public void onHardwarePreDraw(DisplayListCanvas canvas) {
2500        canvas.translate(-mHardwareXOffset, -mHardwareYOffset);
2501    }
2502
2503    @Override
2504    public void onHardwarePostDraw(DisplayListCanvas canvas) {
2505        drawAccessibilityFocusedDrawableIfNeeded(canvas);
2506        for (int i = mWindowCallbacks.size() - 1; i >= 0; i--) {
2507            mWindowCallbacks.get(i).onPostDraw(canvas);
2508        }
2509    }
2510
2511    /**
2512     * @hide
2513     */
2514    void outputDisplayList(View view) {
2515        view.mRenderNode.output();
2516        if (mAttachInfo.mHardwareRenderer != null) {
2517            ((ThreadedRenderer)mAttachInfo.mHardwareRenderer).serializeDisplayListTree();
2518        }
2519    }
2520
2521    /**
2522     * @see #PROPERTY_PROFILE_RENDERING
2523     */
2524    private void profileRendering(boolean enabled) {
2525        if (mProfileRendering) {
2526            mRenderProfilingEnabled = enabled;
2527
2528            if (mRenderProfiler != null) {
2529                mChoreographer.removeFrameCallback(mRenderProfiler);
2530            }
2531            if (mRenderProfilingEnabled) {
2532                if (mRenderProfiler == null) {
2533                    mRenderProfiler = new Choreographer.FrameCallback() {
2534                        @Override
2535                        public void doFrame(long frameTimeNanos) {
2536                            mDirty.set(0, 0, mWidth, mHeight);
2537                            scheduleTraversals();
2538                            if (mRenderProfilingEnabled) {
2539                                mChoreographer.postFrameCallback(mRenderProfiler);
2540                            }
2541                        }
2542                    };
2543                }
2544                mChoreographer.postFrameCallback(mRenderProfiler);
2545            } else {
2546                mRenderProfiler = null;
2547            }
2548        }
2549    }
2550
2551    /**
2552     * Called from draw() when DEBUG_FPS is enabled
2553     */
2554    private void trackFPS() {
2555        // Tracks frames per second drawn. First value in a series of draws may be bogus
2556        // because it down not account for the intervening idle time
2557        long nowTime = System.currentTimeMillis();
2558        if (mFpsStartTime < 0) {
2559            mFpsStartTime = mFpsPrevTime = nowTime;
2560            mFpsNumFrames = 0;
2561        } else {
2562            ++mFpsNumFrames;
2563            String thisHash = Integer.toHexString(System.identityHashCode(this));
2564            long frameTime = nowTime - mFpsPrevTime;
2565            long totalTime = nowTime - mFpsStartTime;
2566            Log.v(mTag, "0x" + thisHash + "\tFrame time:\t" + frameTime);
2567            mFpsPrevTime = nowTime;
2568            if (totalTime > 1000) {
2569                float fps = (float) mFpsNumFrames * 1000 / totalTime;
2570                Log.v(mTag, "0x" + thisHash + "\tFPS:\t" + fps);
2571                mFpsStartTime = nowTime;
2572                mFpsNumFrames = 0;
2573            }
2574        }
2575    }
2576
2577    private void performDraw() {
2578        if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
2579            return;
2580        }
2581
2582        final boolean fullRedrawNeeded = mFullRedrawNeeded;
2583        mFullRedrawNeeded = false;
2584
2585        mIsDrawing = true;
2586        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
2587        try {
2588            draw(fullRedrawNeeded);
2589        } finally {
2590            mIsDrawing = false;
2591            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
2592        }
2593
2594        // For whatever reason we didn't create a HardwareRenderer, end any
2595        // hardware animations that are now dangling
2596        if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
2597            final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
2598            for (int i = 0; i < count; i++) {
2599                mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
2600            }
2601            mAttachInfo.mPendingAnimatingRenderNodes.clear();
2602        }
2603
2604        if (mReportNextDraw) {
2605            mReportNextDraw = false;
2606
2607            // if we're using multi-thread renderer, wait for the window frame draws
2608            if (mWindowDrawCountDown != null) {
2609                try {
2610                    mWindowDrawCountDown.await();
2611                } catch (InterruptedException e) {
2612                    Log.e(mTag, "Window redraw count down interruped!");
2613                }
2614                mWindowDrawCountDown = null;
2615            }
2616
2617            if (mAttachInfo.mHardwareRenderer != null) {
2618                mAttachInfo.mHardwareRenderer.fence();
2619                mAttachInfo.mHardwareRenderer.setStopped(mStopped);
2620            }
2621
2622            if (LOCAL_LOGV) {
2623                Log.v(mTag, "FINISHED DRAWING: " + mWindowAttributes.getTitle());
2624            }
2625            if (mSurfaceHolder != null && mSurface.isValid()) {
2626                mSurfaceHolderCallback.surfaceRedrawNeeded(mSurfaceHolder);
2627                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
2628                if (callbacks != null) {
2629                    for (SurfaceHolder.Callback c : callbacks) {
2630                        if (c instanceof SurfaceHolder.Callback2) {
2631                            ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(mSurfaceHolder);
2632                        }
2633                    }
2634                }
2635            }
2636            try {
2637                mWindowSession.finishDrawing(mWindow);
2638            } catch (RemoteException e) {
2639            }
2640        }
2641    }
2642
2643    private void draw(boolean fullRedrawNeeded) {
2644        Surface surface = mSurface;
2645        if (!surface.isValid()) {
2646            return;
2647        }
2648
2649        if (DEBUG_FPS) {
2650            trackFPS();
2651        }
2652
2653        if (!sFirstDrawComplete) {
2654            synchronized (sFirstDrawHandlers) {
2655                sFirstDrawComplete = true;
2656                final int count = sFirstDrawHandlers.size();
2657                for (int i = 0; i< count; i++) {
2658                    mHandler.post(sFirstDrawHandlers.get(i));
2659                }
2660            }
2661        }
2662
2663        scrollToRectOrFocus(null, false);
2664
2665        if (mAttachInfo.mViewScrollChanged) {
2666            mAttachInfo.mViewScrollChanged = false;
2667            mAttachInfo.mTreeObserver.dispatchOnScrollChanged();
2668        }
2669
2670        boolean animating = mScroller != null && mScroller.computeScrollOffset();
2671        final int curScrollY;
2672        if (animating) {
2673            curScrollY = mScroller.getCurrY();
2674        } else {
2675            curScrollY = mScrollY;
2676        }
2677        if (mCurScrollY != curScrollY) {
2678            mCurScrollY = curScrollY;
2679            fullRedrawNeeded = true;
2680            if (mView instanceof RootViewSurfaceTaker) {
2681                ((RootViewSurfaceTaker) mView).onRootViewScrollYChanged(mCurScrollY);
2682            }
2683        }
2684
2685        final float appScale = mAttachInfo.mApplicationScale;
2686        final boolean scalingRequired = mAttachInfo.mScalingRequired;
2687
2688        int resizeAlpha = 0;
2689
2690        final Rect dirty = mDirty;
2691        if (mSurfaceHolder != null) {
2692            // The app owns the surface, we won't draw.
2693            dirty.setEmpty();
2694            if (animating && mScroller != null) {
2695                mScroller.abortAnimation();
2696            }
2697            return;
2698        }
2699
2700        if (fullRedrawNeeded) {
2701            mAttachInfo.mIgnoreDirtyState = true;
2702            dirty.set(0, 0, (int) (mWidth * appScale + 0.5f), (int) (mHeight * appScale + 0.5f));
2703        }
2704
2705        if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2706            Log.v(mTag, "Draw " + mView + "/"
2707                    + mWindowAttributes.getTitle()
2708                    + ": dirty={" + dirty.left + "," + dirty.top
2709                    + "," + dirty.right + "," + dirty.bottom + "} surface="
2710                    + surface + " surface.isValid()=" + surface.isValid() + ", appScale:" +
2711                    appScale + ", width=" + mWidth + ", height=" + mHeight);
2712        }
2713
2714        mAttachInfo.mTreeObserver.dispatchOnDraw();
2715
2716        int xOffset = -mCanvasOffsetX;
2717        int yOffset = -mCanvasOffsetY + curScrollY;
2718        final WindowManager.LayoutParams params = mWindowAttributes;
2719        final Rect surfaceInsets = params != null ? params.surfaceInsets : null;
2720        if (surfaceInsets != null) {
2721            xOffset -= surfaceInsets.left;
2722            yOffset -= surfaceInsets.top;
2723
2724            // Offset dirty rect for surface insets.
2725            dirty.offset(surfaceInsets.left, surfaceInsets.right);
2726        }
2727
2728        boolean accessibilityFocusDirty = false;
2729        final Drawable drawable = mAttachInfo.mAccessibilityFocusDrawable;
2730        if (drawable != null) {
2731            final Rect bounds = mAttachInfo.mTmpInvalRect;
2732            final boolean hasFocus = getAccessibilityFocusedRect(bounds);
2733            if (!hasFocus) {
2734                bounds.setEmpty();
2735            }
2736            if (!bounds.equals(drawable.getBounds())) {
2737                accessibilityFocusDirty = true;
2738            }
2739        }
2740
2741        mAttachInfo.mDrawingTime =
2742                mChoreographer.getFrameTimeNanos() / TimeUtils.NANOS_PER_MS;
2743
2744        if (!dirty.isEmpty() || mIsAnimating || accessibilityFocusDirty) {
2745            if (mAttachInfo.mHardwareRenderer != null && mAttachInfo.mHardwareRenderer.isEnabled()) {
2746                // If accessibility focus moved, always invalidate the root.
2747                boolean invalidateRoot = accessibilityFocusDirty || mInvalidateRootRequested;
2748                mInvalidateRootRequested = false;
2749
2750                // Draw with hardware renderer.
2751                mIsAnimating = false;
2752
2753                if (mHardwareYOffset != yOffset || mHardwareXOffset != xOffset) {
2754                    mHardwareYOffset = yOffset;
2755                    mHardwareXOffset = xOffset;
2756                    invalidateRoot = true;
2757                }
2758
2759                if (invalidateRoot) {
2760                    mAttachInfo.mHardwareRenderer.invalidateRoot();
2761                }
2762
2763                dirty.setEmpty();
2764
2765                // Stage the content drawn size now. It will be transferred to the renderer
2766                // shortly before the draw commands get send to the renderer.
2767                final boolean updated = updateContentDrawBounds();
2768
2769                if (mReportNextDraw) {
2770                    // report next draw overrides setStopped()
2771                    // This value is re-sync'd to the value of mStopped
2772                    // in the handling of mReportNextDraw post-draw.
2773                    mAttachInfo.mHardwareRenderer.setStopped(false);
2774                }
2775
2776                if (updated) {
2777                    requestDrawWindow();
2778                }
2779
2780                mAttachInfo.mHardwareRenderer.draw(mView, mAttachInfo, this);
2781            } else {
2782                // If we get here with a disabled & requested hardware renderer, something went
2783                // wrong (an invalidate posted right before we destroyed the hardware surface
2784                // for instance) so we should just bail out. Locking the surface with software
2785                // rendering at this point would lock it forever and prevent hardware renderer
2786                // from doing its job when it comes back.
2787                // Before we request a new frame we must however attempt to reinitiliaze the
2788                // hardware renderer if it's in requested state. This would happen after an
2789                // eglTerminate() for instance.
2790                if (mAttachInfo.mHardwareRenderer != null &&
2791                        !mAttachInfo.mHardwareRenderer.isEnabled() &&
2792                        mAttachInfo.mHardwareRenderer.isRequested()) {
2793
2794                    try {
2795                        mAttachInfo.mHardwareRenderer.initializeIfNeeded(
2796                                mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
2797                    } catch (OutOfResourcesException e) {
2798                        handleOutOfResourcesException(e);
2799                        return;
2800                    }
2801
2802                    mFullRedrawNeeded = true;
2803                    scheduleTraversals();
2804                    return;
2805                }
2806
2807                if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
2808                    return;
2809                }
2810            }
2811        }
2812
2813        if (animating) {
2814            mFullRedrawNeeded = true;
2815            scheduleTraversals();
2816        }
2817    }
2818
2819    /**
2820     * @return true if drawing was successful, false if an error occurred
2821     */
2822    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
2823            boolean scalingRequired, Rect dirty) {
2824
2825        // Draw with software renderer.
2826        final Canvas canvas;
2827        try {
2828            final int left = dirty.left;
2829            final int top = dirty.top;
2830            final int right = dirty.right;
2831            final int bottom = dirty.bottom;
2832
2833            canvas = mSurface.lockCanvas(dirty);
2834
2835            // The dirty rectangle can be modified by Surface.lockCanvas()
2836            //noinspection ConstantConditions
2837            if (left != dirty.left || top != dirty.top || right != dirty.right
2838                    || bottom != dirty.bottom) {
2839                attachInfo.mIgnoreDirtyState = true;
2840            }
2841
2842            // TODO: Do this in native
2843            canvas.setDensity(mDensity);
2844        } catch (Surface.OutOfResourcesException e) {
2845            handleOutOfResourcesException(e);
2846            return false;
2847        } catch (IllegalArgumentException e) {
2848            Log.e(mTag, "Could not lock surface", e);
2849            // Don't assume this is due to out of memory, it could be
2850            // something else, and if it is something else then we could
2851            // kill stuff (or ourself) for no reason.
2852            mLayoutRequested = true;    // ask wm for a new surface next time.
2853            return false;
2854        }
2855
2856        try {
2857            if (DEBUG_ORIENTATION || DEBUG_DRAW) {
2858                Log.v(mTag, "Surface " + surface + " drawing to bitmap w="
2859                        + canvas.getWidth() + ", h=" + canvas.getHeight());
2860                //canvas.drawARGB(255, 255, 0, 0);
2861            }
2862
2863            // If this bitmap's format includes an alpha channel, we
2864            // need to clear it before drawing so that the child will
2865            // properly re-composite its drawing on a transparent
2866            // background. This automatically respects the clip/dirty region
2867            // or
2868            // If we are applying an offset, we need to clear the area
2869            // where the offset doesn't appear to avoid having garbage
2870            // left in the blank areas.
2871            if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
2872                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
2873            }
2874
2875            dirty.setEmpty();
2876            mIsAnimating = false;
2877            mView.mPrivateFlags |= View.PFLAG_DRAWN;
2878
2879            if (DEBUG_DRAW) {
2880                Context cxt = mView.getContext();
2881                Log.i(mTag, "Drawing: package:" + cxt.getPackageName() +
2882                        ", metrics=" + cxt.getResources().getDisplayMetrics() +
2883                        ", compatibilityInfo=" + cxt.getResources().getCompatibilityInfo());
2884            }
2885            try {
2886                canvas.translate(-xoff, -yoff);
2887                if (mTranslator != null) {
2888                    mTranslator.translateCanvas(canvas);
2889                }
2890                canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
2891                attachInfo.mSetIgnoreDirtyState = false;
2892
2893                mView.draw(canvas);
2894
2895                drawAccessibilityFocusedDrawableIfNeeded(canvas);
2896            } finally {
2897                if (!attachInfo.mSetIgnoreDirtyState) {
2898                    // Only clear the flag if it was not set during the mView.draw() call
2899                    attachInfo.mIgnoreDirtyState = false;
2900                }
2901            }
2902        } finally {
2903            try {
2904                surface.unlockCanvasAndPost(canvas);
2905            } catch (IllegalArgumentException e) {
2906                Log.e(mTag, "Could not unlock surface", e);
2907                mLayoutRequested = true;    // ask wm for a new surface next time.
2908                //noinspection ReturnInsideFinallyBlock
2909                return false;
2910            }
2911
2912            if (LOCAL_LOGV) {
2913                Log.v(mTag, "Surface " + surface + " unlockCanvasAndPost");
2914            }
2915        }
2916        return true;
2917    }
2918
2919    /**
2920     * We want to draw a highlight around the current accessibility focused.
2921     * Since adding a style for all possible view is not a viable option we
2922     * have this specialized drawing method.
2923     *
2924     * Note: We are doing this here to be able to draw the highlight for
2925     *       virtual views in addition to real ones.
2926     *
2927     * @param canvas The canvas on which to draw.
2928     */
2929    private void drawAccessibilityFocusedDrawableIfNeeded(Canvas canvas) {
2930        final Rect bounds = mAttachInfo.mTmpInvalRect;
2931        if (getAccessibilityFocusedRect(bounds)) {
2932            final Drawable drawable = getAccessibilityFocusedDrawable();
2933            if (drawable != null) {
2934                drawable.setBounds(bounds);
2935                drawable.draw(canvas);
2936            }
2937        } else if (mAttachInfo.mAccessibilityFocusDrawable != null) {
2938            mAttachInfo.mAccessibilityFocusDrawable.setBounds(0, 0, 0, 0);
2939        }
2940    }
2941
2942    private boolean getAccessibilityFocusedRect(Rect bounds) {
2943        final AccessibilityManager manager = AccessibilityManager.getInstance(mView.mContext);
2944        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
2945            return false;
2946        }
2947
2948        final View host = mAccessibilityFocusedHost;
2949        if (host == null || host.mAttachInfo == null) {
2950            return false;
2951        }
2952
2953        final AccessibilityNodeProvider provider = host.getAccessibilityNodeProvider();
2954        if (provider == null) {
2955            host.getBoundsOnScreen(bounds, true);
2956        } else if (mAccessibilityFocusedVirtualView != null) {
2957            mAccessibilityFocusedVirtualView.getBoundsInScreen(bounds);
2958        } else {
2959            return false;
2960        }
2961
2962        // Transform the rect into window-relative coordinates.
2963        final AttachInfo attachInfo = mAttachInfo;
2964        bounds.offset(0, attachInfo.mViewRootImpl.mScrollY);
2965        bounds.offset(-attachInfo.mWindowLeft, -attachInfo.mWindowTop);
2966        if (!bounds.intersect(0, 0, attachInfo.mViewRootImpl.mWidth,
2967                attachInfo.mViewRootImpl.mHeight)) {
2968            // If no intersection, set bounds to empty.
2969            bounds.setEmpty();
2970        }
2971        return !bounds.isEmpty();
2972    }
2973
2974    private Drawable getAccessibilityFocusedDrawable() {
2975        // Lazily load the accessibility focus drawable.
2976        if (mAttachInfo.mAccessibilityFocusDrawable == null) {
2977            final TypedValue value = new TypedValue();
2978            final boolean resolved = mView.mContext.getTheme().resolveAttribute(
2979                    R.attr.accessibilityFocusedDrawable, value, true);
2980            if (resolved) {
2981                mAttachInfo.mAccessibilityFocusDrawable =
2982                        mView.mContext.getDrawable(value.resourceId);
2983            }
2984        }
2985        return mAttachInfo.mAccessibilityFocusDrawable;
2986    }
2987
2988    /**
2989     * Requests that the root render node is invalidated next time we perform a draw, such that
2990     * {@link WindowCallbacks#onPostDraw} gets called.
2991     */
2992    public void requestInvalidateRootRenderNode() {
2993        mInvalidateRootRequested = true;
2994    }
2995
2996    boolean scrollToRectOrFocus(Rect rectangle, boolean immediate) {
2997        final Rect ci = mAttachInfo.mContentInsets;
2998        final Rect vi = mAttachInfo.mVisibleInsets;
2999        int scrollY = 0;
3000        boolean handled = false;
3001
3002        if (vi.left > ci.left || vi.top > ci.top
3003                || vi.right > ci.right || vi.bottom > ci.bottom) {
3004            // We'll assume that we aren't going to change the scroll
3005            // offset, since we want to avoid that unless it is actually
3006            // going to make the focus visible...  otherwise we scroll
3007            // all over the place.
3008            scrollY = mScrollY;
3009            // We can be called for two different situations: during a draw,
3010            // to update the scroll position if the focus has changed (in which
3011            // case 'rectangle' is null), or in response to a
3012            // requestChildRectangleOnScreen() call (in which case 'rectangle'
3013            // is non-null and we just want to scroll to whatever that
3014            // rectangle is).
3015            final View focus = mView.findFocus();
3016            if (focus == null) {
3017                return false;
3018            }
3019            View lastScrolledFocus = (mLastScrolledFocus != null) ? mLastScrolledFocus.get() : null;
3020            if (focus != lastScrolledFocus) {
3021                // If the focus has changed, then ignore any requests to scroll
3022                // to a rectangle; first we want to make sure the entire focus
3023                // view is visible.
3024                rectangle = null;
3025            }
3026            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Eval scroll: focus=" + focus
3027                    + " rectangle=" + rectangle + " ci=" + ci
3028                    + " vi=" + vi);
3029            if (focus == lastScrolledFocus && !mScrollMayChange && rectangle == null) {
3030                // Optimization: if the focus hasn't changed since last
3031                // time, and no layout has happened, then just leave things
3032                // as they are.
3033                if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Keeping scroll y="
3034                        + mScrollY + " vi=" + vi.toShortString());
3035            } else {
3036                // We need to determine if the currently focused view is
3037                // within the visible part of the window and, if not, apply
3038                // a pan so it can be seen.
3039                mLastScrolledFocus = new WeakReference<View>(focus);
3040                mScrollMayChange = false;
3041                if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Need to scroll?");
3042                // Try to find the rectangle from the focus view.
3043                if (focus.getGlobalVisibleRect(mVisRect, null)) {
3044                    if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Root w="
3045                            + mView.getWidth() + " h=" + mView.getHeight()
3046                            + " ci=" + ci.toShortString()
3047                            + " vi=" + vi.toShortString());
3048                    if (rectangle == null) {
3049                        focus.getFocusedRect(mTempRect);
3050                        if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Focus " + focus
3051                                + ": focusRect=" + mTempRect.toShortString());
3052                        if (mView instanceof ViewGroup) {
3053                            ((ViewGroup) mView).offsetDescendantRectToMyCoords(
3054                                    focus, mTempRect);
3055                        }
3056                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3057                                "Focus in window: focusRect="
3058                                + mTempRect.toShortString()
3059                                + " visRect=" + mVisRect.toShortString());
3060                    } else {
3061                        mTempRect.set(rectangle);
3062                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3063                                "Request scroll to rect: "
3064                                + mTempRect.toShortString()
3065                                + " visRect=" + mVisRect.toShortString());
3066                    }
3067                    if (mTempRect.intersect(mVisRect)) {
3068                        if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3069                                "Focus window visible rect: "
3070                                + mTempRect.toShortString());
3071                        if (mTempRect.height() >
3072                                (mView.getHeight()-vi.top-vi.bottom)) {
3073                            // If the focus simply is not going to fit, then
3074                            // best is probably just to leave things as-is.
3075                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3076                                    "Too tall; leaving scrollY=" + scrollY);
3077                        } else if ((mTempRect.top-scrollY) < vi.top) {
3078                            scrollY -= vi.top - (mTempRect.top-scrollY);
3079                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3080                                    "Top covered; scrollY=" + scrollY);
3081                        } else if ((mTempRect.bottom-scrollY)
3082                                > (mView.getHeight()-vi.bottom)) {
3083                            scrollY += (mTempRect.bottom-scrollY)
3084                                    - (mView.getHeight()-vi.bottom);
3085                            if (DEBUG_INPUT_RESIZE) Log.v(mTag,
3086                                    "Bottom covered; scrollY=" + scrollY);
3087                        }
3088                        handled = true;
3089                    }
3090                }
3091            }
3092        }
3093
3094        if (scrollY != mScrollY) {
3095            if (DEBUG_INPUT_RESIZE) Log.v(mTag, "Pan scroll changed: old="
3096                    + mScrollY + " , new=" + scrollY);
3097            if (!immediate) {
3098                if (mScroller == null) {
3099                    mScroller = new Scroller(mView.getContext());
3100                }
3101                mScroller.startScroll(0, mScrollY, 0, scrollY-mScrollY);
3102            } else if (mScroller != null) {
3103                mScroller.abortAnimation();
3104            }
3105            mScrollY = scrollY;
3106        }
3107
3108        return handled;
3109    }
3110
3111    /**
3112     * @hide
3113     */
3114    public View getAccessibilityFocusedHost() {
3115        return mAccessibilityFocusedHost;
3116    }
3117
3118    /**
3119     * @hide
3120     */
3121    public AccessibilityNodeInfo getAccessibilityFocusedVirtualView() {
3122        return mAccessibilityFocusedVirtualView;
3123    }
3124
3125    void setAccessibilityFocus(View view, AccessibilityNodeInfo node) {
3126        // If we have a virtual view with accessibility focus we need
3127        // to clear the focus and invalidate the virtual view bounds.
3128        if (mAccessibilityFocusedVirtualView != null) {
3129
3130            AccessibilityNodeInfo focusNode = mAccessibilityFocusedVirtualView;
3131            View focusHost = mAccessibilityFocusedHost;
3132
3133            // Wipe the state of the current accessibility focus since
3134            // the call into the provider to clear accessibility focus
3135            // will fire an accessibility event which will end up calling
3136            // this method and we want to have clean state when this
3137            // invocation happens.
3138            mAccessibilityFocusedHost = null;
3139            mAccessibilityFocusedVirtualView = null;
3140
3141            // Clear accessibility focus on the host after clearing state since
3142            // this method may be reentrant.
3143            focusHost.clearAccessibilityFocusNoCallbacks(
3144                    AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
3145
3146            AccessibilityNodeProvider provider = focusHost.getAccessibilityNodeProvider();
3147            if (provider != null) {
3148                // Invalidate the area of the cleared accessibility focus.
3149                focusNode.getBoundsInParent(mTempRect);
3150                focusHost.invalidate(mTempRect);
3151                // Clear accessibility focus in the virtual node.
3152                final int virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
3153                        focusNode.getSourceNodeId());
3154                provider.performAction(virtualNodeId,
3155                        AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null);
3156            }
3157            focusNode.recycle();
3158        }
3159        if (mAccessibilityFocusedHost != null) {
3160            // Clear accessibility focus in the view.
3161            mAccessibilityFocusedHost.clearAccessibilityFocusNoCallbacks(
3162                    AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
3163        }
3164
3165        // Set the new focus host and node.
3166        mAccessibilityFocusedHost = view;
3167        mAccessibilityFocusedVirtualView = node;
3168
3169        if (mAttachInfo.mHardwareRenderer != null) {
3170            mAttachInfo.mHardwareRenderer.invalidateRoot();
3171        }
3172    }
3173
3174    void setPointerCapture(View view) {
3175        if (!mAttachInfo.mHasWindowFocus) {
3176            Log.w(mTag, "Can't set capture if it's not focused.");
3177            return;
3178        }
3179        if (mCapturingView == view) {
3180            return;
3181        }
3182        mCapturingView = view;
3183        InputManager.getInstance().setPointerIconDetached(true);
3184    }
3185
3186    void releasePointerCapture(View view) {
3187        if (mCapturingView != view || mCapturingView == null) {
3188            return;
3189        }
3190
3191        mCapturingView = null;
3192        InputManager.getInstance().setPointerIconDetached(false);
3193    }
3194
3195    boolean hasPointerCapture(View view) {
3196        return view != null && mCapturingView == view;
3197    }
3198
3199    @Override
3200    public void requestChildFocus(View child, View focused) {
3201        if (DEBUG_INPUT_RESIZE) {
3202            Log.v(mTag, "Request child focus: focus now " + focused);
3203        }
3204        checkThread();
3205        scheduleTraversals();
3206    }
3207
3208    @Override
3209    public void clearChildFocus(View child) {
3210        if (DEBUG_INPUT_RESIZE) {
3211            Log.v(mTag, "Clearing child focus");
3212        }
3213        checkThread();
3214        scheduleTraversals();
3215    }
3216
3217    @Override
3218    public ViewParent getParentForAccessibility() {
3219        return null;
3220    }
3221
3222    @Override
3223    public void focusableViewAvailable(View v) {
3224        checkThread();
3225        if (mView != null) {
3226            if (!mView.hasFocus()) {
3227                v.requestFocus();
3228            } else {
3229                // the one case where will transfer focus away from the current one
3230                // is if the current view is a view group that prefers to give focus
3231                // to its children first AND the view is a descendant of it.
3232                View focused = mView.findFocus();
3233                if (focused instanceof ViewGroup) {
3234                    ViewGroup group = (ViewGroup) focused;
3235                    if (group.getDescendantFocusability() == ViewGroup.FOCUS_AFTER_DESCENDANTS
3236                            && isViewDescendantOf(v, focused)) {
3237                        v.requestFocus();
3238                    }
3239                }
3240            }
3241        }
3242    }
3243
3244    @Override
3245    public void recomputeViewAttributes(View child) {
3246        checkThread();
3247        if (mView == child) {
3248            mAttachInfo.mRecomputeGlobalAttributes = true;
3249            if (!mWillDrawSoon) {
3250                scheduleTraversals();
3251            }
3252        }
3253    }
3254
3255    void dispatchDetachedFromWindow() {
3256        if (mView != null && mView.mAttachInfo != null) {
3257            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
3258            mView.dispatchDetachedFromWindow();
3259        }
3260
3261        mAccessibilityInteractionConnectionManager.ensureNoConnection();
3262        mAccessibilityManager.removeAccessibilityStateChangeListener(
3263                mAccessibilityInteractionConnectionManager);
3264        mAccessibilityManager.removeHighTextContrastStateChangeListener(
3265                mHighContrastTextManager);
3266        removeSendWindowContentChangedCallback();
3267
3268        destroyHardwareRenderer();
3269
3270        setAccessibilityFocus(null, null);
3271
3272        mView.assignParent(null);
3273        mView = null;
3274        mAttachInfo.mRootView = null;
3275
3276        if (mCapturingView != null) {
3277            releasePointerCapture(mCapturingView);
3278        }
3279
3280        mSurface.release();
3281
3282        if (mInputQueueCallback != null && mInputQueue != null) {
3283            mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
3284            mInputQueue.dispose();
3285            mInputQueueCallback = null;
3286            mInputQueue = null;
3287        }
3288        if (mInputEventReceiver != null) {
3289            mInputEventReceiver.dispose();
3290            mInputEventReceiver = null;
3291        }
3292        try {
3293            mWindowSession.remove(mWindow);
3294        } catch (RemoteException e) {
3295        }
3296
3297        // Dispose the input channel after removing the window so the Window Manager
3298        // doesn't interpret the input channel being closed as an abnormal termination.
3299        if (mInputChannel != null) {
3300            mInputChannel.dispose();
3301            mInputChannel = null;
3302        }
3303
3304        mDisplayManager.unregisterDisplayListener(mDisplayListener);
3305
3306        unscheduleTraversals();
3307    }
3308
3309    void updateConfiguration(Configuration config, boolean force) {
3310        if (DEBUG_CONFIGURATION) Log.v(mTag,
3311                "Applying new config to window "
3312                + mWindowAttributes.getTitle()
3313                + ": " + config);
3314
3315        CompatibilityInfo ci = mDisplayAdjustments.getCompatibilityInfo();
3316        if (!ci.equals(CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO)) {
3317            config = new Configuration(config);
3318            ci.applyToConfiguration(mNoncompatDensity, config);
3319        }
3320
3321        synchronized (sConfigCallbacks) {
3322            for (int i=sConfigCallbacks.size()-1; i>=0; i--) {
3323                sConfigCallbacks.get(i).onConfigurationChanged(config);
3324            }
3325        }
3326        if (mView != null) {
3327            // At this point the resources have been updated to
3328            // have the most recent config, whatever that is.  Use
3329            // the one in them which may be newer.
3330            config = mView.getResources().getConfiguration();
3331            if (force || mLastConfiguration.diff(config) != 0) {
3332                final int lastLayoutDirection = mLastConfiguration.getLayoutDirection();
3333                final int currentLayoutDirection = config.getLayoutDirection();
3334                mLastConfiguration.setTo(config);
3335                if (lastLayoutDirection != currentLayoutDirection &&
3336                        mViewLayoutDirectionInitial == View.LAYOUT_DIRECTION_INHERIT) {
3337                    mView.setLayoutDirection(currentLayoutDirection);
3338                }
3339                mView.dispatchConfigurationChanged(config);
3340            }
3341        }
3342    }
3343
3344    /**
3345     * Return true if child is an ancestor of parent, (or equal to the parent).
3346     */
3347    public static boolean isViewDescendantOf(View child, View parent) {
3348        if (child == parent) {
3349            return true;
3350        }
3351
3352        final ViewParent theParent = child.getParent();
3353        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
3354    }
3355
3356    private static void forceLayout(View view) {
3357        view.forceLayout();
3358        if (view instanceof ViewGroup) {
3359            ViewGroup group = (ViewGroup) view;
3360            final int count = group.getChildCount();
3361            for (int i = 0; i < count; i++) {
3362                forceLayout(group.getChildAt(i));
3363            }
3364        }
3365    }
3366
3367    private final static int MSG_INVALIDATE = 1;
3368    private final static int MSG_INVALIDATE_RECT = 2;
3369    private final static int MSG_DIE = 3;
3370    private final static int MSG_RESIZED = 4;
3371    private final static int MSG_RESIZED_REPORT = 5;
3372    private final static int MSG_WINDOW_FOCUS_CHANGED = 6;
3373    private final static int MSG_DISPATCH_INPUT_EVENT = 7;
3374    private final static int MSG_DISPATCH_APP_VISIBILITY = 8;
3375    private final static int MSG_DISPATCH_GET_NEW_SURFACE = 9;
3376    private final static int MSG_DISPATCH_KEY_FROM_IME = 11;
3377    private final static int MSG_CHECK_FOCUS = 13;
3378    private final static int MSG_CLOSE_SYSTEM_DIALOGS = 14;
3379    private final static int MSG_DISPATCH_DRAG_EVENT = 15;
3380    private final static int MSG_DISPATCH_DRAG_LOCATION_EVENT = 16;
3381    private final static int MSG_DISPATCH_SYSTEM_UI_VISIBILITY = 17;
3382    private final static int MSG_UPDATE_CONFIGURATION = 18;
3383    private final static int MSG_PROCESS_INPUT_EVENTS = 19;
3384    private final static int MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST = 21;
3385    private final static int MSG_INVALIDATE_WORLD = 22;
3386    private final static int MSG_WINDOW_MOVED = 23;
3387    private final static int MSG_SYNTHESIZE_INPUT_EVENT = 24;
3388    private final static int MSG_DISPATCH_WINDOW_SHOWN = 25;
3389    private final static int MSG_REQUEST_KEYBOARD_SHORTCUTS = 26;
3390    private final static int MSG_UPDATE_POINTER_ICON = 27;
3391
3392    final class ViewRootHandler extends Handler {
3393        @Override
3394        public String getMessageName(Message message) {
3395            switch (message.what) {
3396                case MSG_INVALIDATE:
3397                    return "MSG_INVALIDATE";
3398                case MSG_INVALIDATE_RECT:
3399                    return "MSG_INVALIDATE_RECT";
3400                case MSG_DIE:
3401                    return "MSG_DIE";
3402                case MSG_RESIZED:
3403                    return "MSG_RESIZED";
3404                case MSG_RESIZED_REPORT:
3405                    return "MSG_RESIZED_REPORT";
3406                case MSG_WINDOW_FOCUS_CHANGED:
3407                    return "MSG_WINDOW_FOCUS_CHANGED";
3408                case MSG_DISPATCH_INPUT_EVENT:
3409                    return "MSG_DISPATCH_INPUT_EVENT";
3410                case MSG_DISPATCH_APP_VISIBILITY:
3411                    return "MSG_DISPATCH_APP_VISIBILITY";
3412                case MSG_DISPATCH_GET_NEW_SURFACE:
3413                    return "MSG_DISPATCH_GET_NEW_SURFACE";
3414                case MSG_DISPATCH_KEY_FROM_IME:
3415                    return "MSG_DISPATCH_KEY_FROM_IME";
3416                case MSG_CHECK_FOCUS:
3417                    return "MSG_CHECK_FOCUS";
3418                case MSG_CLOSE_SYSTEM_DIALOGS:
3419                    return "MSG_CLOSE_SYSTEM_DIALOGS";
3420                case MSG_DISPATCH_DRAG_EVENT:
3421                    return "MSG_DISPATCH_DRAG_EVENT";
3422                case MSG_DISPATCH_DRAG_LOCATION_EVENT:
3423                    return "MSG_DISPATCH_DRAG_LOCATION_EVENT";
3424                case MSG_DISPATCH_SYSTEM_UI_VISIBILITY:
3425                    return "MSG_DISPATCH_SYSTEM_UI_VISIBILITY";
3426                case MSG_UPDATE_CONFIGURATION:
3427                    return "MSG_UPDATE_CONFIGURATION";
3428                case MSG_PROCESS_INPUT_EVENTS:
3429                    return "MSG_PROCESS_INPUT_EVENTS";
3430                case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST:
3431                    return "MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST";
3432                case MSG_WINDOW_MOVED:
3433                    return "MSG_WINDOW_MOVED";
3434                case MSG_SYNTHESIZE_INPUT_EVENT:
3435                    return "MSG_SYNTHESIZE_INPUT_EVENT";
3436                case MSG_DISPATCH_WINDOW_SHOWN:
3437                    return "MSG_DISPATCH_WINDOW_SHOWN";
3438                case MSG_UPDATE_POINTER_ICON:
3439                    return "MSG_UPDATE_POINTER_ICON";
3440            }
3441            return super.getMessageName(message);
3442        }
3443
3444        @Override
3445        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
3446            if (msg.what == MSG_REQUEST_KEYBOARD_SHORTCUTS && msg.obj == null) {
3447                // Debugging for b/27963013
3448                throw new NullPointerException(
3449                        "Attempted to call MSG_REQUEST_KEYBOARD_SHORTCUTS with null receiver:");
3450            }
3451            return super.sendMessageAtTime(msg, uptimeMillis);
3452        }
3453
3454        @Override
3455        public void handleMessage(Message msg) {
3456            switch (msg.what) {
3457            case MSG_INVALIDATE:
3458                ((View) msg.obj).invalidate();
3459                break;
3460            case MSG_INVALIDATE_RECT:
3461                final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj;
3462                info.target.invalidate(info.left, info.top, info.right, info.bottom);
3463                info.recycle();
3464                break;
3465            case MSG_PROCESS_INPUT_EVENTS:
3466                mProcessInputEventsScheduled = false;
3467                doProcessInputEvents();
3468                break;
3469            case MSG_DISPATCH_APP_VISIBILITY:
3470                handleAppVisibility(msg.arg1 != 0);
3471                break;
3472            case MSG_DISPATCH_GET_NEW_SURFACE:
3473                handleGetNewSurface();
3474                break;
3475            case MSG_RESIZED: {
3476                // Recycled in the fall through...
3477                SomeArgs args = (SomeArgs) msg.obj;
3478                if (mWinFrame.equals(args.arg1)
3479                        && mPendingOverscanInsets.equals(args.arg5)
3480                        && mPendingContentInsets.equals(args.arg2)
3481                        && mPendingStableInsets.equals(args.arg6)
3482                        && mPendingVisibleInsets.equals(args.arg3)
3483                        && mPendingOutsets.equals(args.arg7)
3484                        && mPendingBackDropFrame.equals(args.arg8)
3485                        && args.arg4 == null
3486                        && args.argi1 == 0) {
3487                    break;
3488                }
3489                } // fall through...
3490            case MSG_RESIZED_REPORT:
3491                if (mAdded) {
3492                    SomeArgs args = (SomeArgs) msg.obj;
3493
3494                    Configuration config = (Configuration) args.arg4;
3495                    if (config != null) {
3496                        updateConfiguration(config, false);
3497                    }
3498
3499                    final boolean framesChanged = !mWinFrame.equals(args.arg1)
3500                            || !mPendingOverscanInsets.equals(args.arg5)
3501                            || !mPendingContentInsets.equals(args.arg2)
3502                            || !mPendingStableInsets.equals(args.arg6)
3503                            || !mPendingVisibleInsets.equals(args.arg3)
3504                            || !mPendingOutsets.equals(args.arg7);
3505
3506                    mWinFrame.set((Rect) args.arg1);
3507                    mPendingOverscanInsets.set((Rect) args.arg5);
3508                    mPendingContentInsets.set((Rect) args.arg2);
3509                    mPendingStableInsets.set((Rect) args.arg6);
3510                    mPendingVisibleInsets.set((Rect) args.arg3);
3511                    mPendingOutsets.set((Rect) args.arg7);
3512                    mPendingBackDropFrame.set((Rect) args.arg8);
3513                    mForceNextWindowRelayout = args.argi1 != 0;
3514                    mPendingAlwaysConsumeNavBar = args.argi2 != 0;
3515
3516                    args.recycle();
3517
3518                    if (msg.what == MSG_RESIZED_REPORT) {
3519                        mReportNextDraw = true;
3520                    }
3521
3522                    if (mView != null && framesChanged) {
3523                        forceLayout(mView);
3524                    }
3525
3526                    requestLayout();
3527                }
3528                break;
3529            case MSG_WINDOW_MOVED:
3530                if (mAdded) {
3531                    final int w = mWinFrame.width();
3532                    final int h = mWinFrame.height();
3533                    final int l = msg.arg1;
3534                    final int t = msg.arg2;
3535                    mWinFrame.left = l;
3536                    mWinFrame.right = l + w;
3537                    mWinFrame.top = t;
3538                    mWinFrame.bottom = t + h;
3539
3540                    mPendingBackDropFrame.set(mWinFrame);
3541
3542                    // Suppress layouts during resizing - a correct layout will happen when resizing
3543                    // is done, and this just increases system load.
3544                    boolean isDockedDivider = mWindowAttributes.type == TYPE_DOCK_DIVIDER;
3545                    boolean suppress = (mDragResizing && mResizeMode == RESIZE_MODE_DOCKED_DIVIDER)
3546                            || isDockedDivider;
3547                    if (!suppress) {
3548                        if (mView != null) {
3549                            forceLayout(mView);
3550                        }
3551                        requestLayout();
3552                    } else {
3553                        maybeHandleWindowMove(mWinFrame);
3554                    }
3555                }
3556                break;
3557            case MSG_WINDOW_FOCUS_CHANGED: {
3558                if (mAdded) {
3559                    boolean hasWindowFocus = msg.arg1 != 0;
3560                    mAttachInfo.mHasWindowFocus = hasWindowFocus;
3561
3562                    profileRendering(hasWindowFocus);
3563
3564                    if (hasWindowFocus) {
3565                        boolean inTouchMode = msg.arg2 != 0;
3566                        ensureTouchModeLocally(inTouchMode);
3567
3568                        if (mAttachInfo.mHardwareRenderer != null && mSurface.isValid()){
3569                            mFullRedrawNeeded = true;
3570                            try {
3571                                final WindowManager.LayoutParams lp = mWindowAttributes;
3572                                final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null;
3573                                mAttachInfo.mHardwareRenderer.initializeIfNeeded(
3574                                        mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets);
3575                            } catch (OutOfResourcesException e) {
3576                                Log.e(mTag, "OutOfResourcesException locking surface", e);
3577                                try {
3578                                    if (!mWindowSession.outOfMemory(mWindow)) {
3579                                        Slog.w(mTag, "No processes killed for memory; killing self");
3580                                        Process.killProcess(Process.myPid());
3581                                    }
3582                                } catch (RemoteException ex) {
3583                                }
3584                                // Retry in a bit.
3585                                sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500);
3586                                return;
3587                            }
3588                        }
3589                    }
3590
3591                    mLastWasImTarget = WindowManager.LayoutParams
3592                            .mayUseInputMethod(mWindowAttributes.flags);
3593
3594                    InputMethodManager imm = InputMethodManager.peekInstance();
3595                    if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3596                        imm.onPreWindowFocus(mView, hasWindowFocus);
3597                    }
3598                    if (mView != null) {
3599                        mAttachInfo.mKeyDispatchState.reset();
3600                        mView.dispatchWindowFocusChanged(hasWindowFocus);
3601                        mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus);
3602                    }
3603
3604                    // Note: must be done after the focus change callbacks,
3605                    // so all of the view state is set up correctly.
3606                    if (hasWindowFocus) {
3607                        if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) {
3608                            imm.onPostWindowFocus(mView, mView.findFocus(),
3609                                    mWindowAttributes.softInputMode,
3610                                    !mHasHadWindowFocus, mWindowAttributes.flags);
3611                        }
3612                        // Clear the forward bit.  We can just do this directly, since
3613                        // the window manager doesn't care about it.
3614                        mWindowAttributes.softInputMode &=
3615                                ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3616                        ((WindowManager.LayoutParams)mView.getLayoutParams())
3617                                .softInputMode &=
3618                                    ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
3619                        mHasHadWindowFocus = true;
3620                    } else if (mCapturingView != null) {
3621                        releasePointerCapture(mCapturingView);
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
4452                    && event.isFromSource(InputDevice.SOURCE_MOUSE)) {
4453                if (event.getActionMasked() == MotionEvent.ACTION_HOVER_ENTER
4454                        || event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
4455                    // Other apps or the window manager may change the icon shape outside of
4456                    // this app, therefore the icon shape has to be reset on enter/exit event.
4457                    mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4458                }
4459
4460                if (event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
4461                    if (!updatePointerIcon(event) &&
4462                            event.getActionMasked() == MotionEvent.ACTION_HOVER_MOVE) {
4463                        mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4464                    }
4465                }
4466            }
4467        }
4468
4469        private int processTrackballEvent(QueuedInputEvent q) {
4470            final MotionEvent event = (MotionEvent)q.mEvent;
4471
4472            if (mView.dispatchTrackballEvent(event)) {
4473                return FINISH_HANDLED;
4474            }
4475            return FORWARD;
4476        }
4477
4478        private int processGenericMotionEvent(QueuedInputEvent q) {
4479            final MotionEvent event = (MotionEvent)q.mEvent;
4480
4481            // Deliver the event to the view.
4482            if (mView.dispatchGenericMotionEvent(event)) {
4483                return FINISH_HANDLED;
4484            }
4485            return FORWARD;
4486        }
4487    }
4488
4489    private void resetPointerIcon(MotionEvent event) {
4490        mPointerIconShape = PointerIcon.STYLE_NOT_SPECIFIED;
4491        updatePointerIcon(event);
4492    }
4493
4494    private boolean updatePointerIcon(MotionEvent event) {
4495        final float x = event.getX();
4496        final float y = event.getY();
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.getPointerIcon(event, x, y);
4508        final int pointerShape = (pointerIcon != null) ?
4509                pointerIcon.getStyle() : PointerIcon.STYLE_DEFAULT;
4510
4511        if (mPointerIconShape != pointerShape) {
4512            mPointerIconShape = pointerShape;
4513            if (mPointerIconShape != PointerIcon.STYLE_CUSTOM) {
4514                mCustomPointerIcon = null;
4515                InputManager.getInstance().setPointerIconShape(pointerShape);
4516                return true;
4517            }
4518        }
4519        if (mPointerIconShape == PointerIcon.STYLE_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            if (what == DragEvent.ACTION_DRAG_EXITED) {
5515                // A direct EXITED event means that the window manager knows we've just crossed
5516                // a window boundary, so the current drag target within this one must have
5517                // just been exited.  Send it the usual notifications and then we're done
5518                // for now.
5519                mView.dispatchDragEvent(event);
5520            } else {
5521                // Cache the drag description when the operation starts, then fill it in
5522                // on subsequent calls as a convenience
5523                if (what == DragEvent.ACTION_DRAG_STARTED) {
5524                    mCurrentDragView = null;    // Start the current-recipient tracking
5525                    mDragDescription = event.mClipDescription;
5526                } else {
5527                    event.mClipDescription = mDragDescription;
5528                }
5529
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