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